Struts2 + Spring 3.2 + Hibernate 3 java.lang.NullPointerException in action (execute)

I have a problem with an example.

I get this error when I am listing Elements in an action, but I don't know why.

I think that the bean wasn't created, because the error occurs when execute() action is called.

Struts Problem Report:

Struts has detected an unhandled exception:
Messages:   
File:   actions/ListingAction.java
Line number:    26

Stacktraces:

java.lang.NullPointerException    
    actions.ListingAction.execute(ListingAction.java:26)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:446)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:285)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:238)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:238)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:544)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
    com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    java.lang.Thread.run(Thread.java:680)

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">

    <display-name>PFC</display-name>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

            <!-- Spring -->

    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            /WEB-INF/applicationContext*.xml  
        </param-value>  
    </context-param>
    <listener> <!-- Required for the struts2 spring plugin to work -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
    <listener>  
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
    </listener>  

    <filter> <!-- Get spring to keep the session open for the whole request, so hibernate's lazy loads work -->
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

<!-- Sitemesh (needs to be before struts) -->
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

<!-- Struts2 config (needs to be after sitemesh) -->


    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

<!-- La configuraciĆ³n de los struts..  el nombre se pone registro el fichero de confi-spring en registro-struts.xml-->


</web-app>

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">


    <!-- The singleton hibernate session factory -->
    <bean id="sessionFactory" 
          class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    </bean> 

    <!-- Spring's hibernate transaction manager, in charge of making hibernate sessions/txns -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean> 

    <bean id="sessionLocaleResolver"
          class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

    <bean id="eventoService" class="services.EventoService" scope="singleton">
        <property name="sessionFactory" ref="sessionFactory"/>
        <!--property name="sessionFactory" ref="sessionFactory"/-->
    </bean>

    <bean id="listingAction" class="actions.ListingAction">
        <property name="serviceEvento" ref="eventoService"/>   
    </bean>


</beans>

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" /> <!-- set to false for prod -->

    <constant name="struts.configuration.xml.reload" value="true" />

    <package name="eventos" extends="struts-default">
        <action name="ListingAction" class="actions.ListingAction">
            <result name="success">/vistas/eventos/Listing.jsp</result>
        </action>
    </package>

    <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />


</struts>

hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
"-//Hibernate/Hibernate Configuration DTD//EN"  
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  

<hibernate-configuration>   
<session-factory>   
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>   
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/events</property>   
<property name="hibernate.connection.username">eventuser</property>   
<property name="connection.password">eventuser</property>   
<property name="connection.pool_size">1</property>   
<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>   
<property name="show_sql">true</property>   
<property name="hbm2ddl.auto">create</property>   
<mapping resource="model/Evento.hbm.xml"/>
</session-factory>   
</hibernate-configuration> 

ListingAction.java:

package actions;

import com.opensymphony.xwork2.ActionSupport;
import services.EventoService;
import java.util.List;
import model.Evento;
/**
 *
 * @author 
 */
public class ListingAction extends ActionSupport{


// So that spring can inject the business singleton
    protected EventoService serviceEvento;

    public void setServiceEvento(EventoService value) {
        serviceEvento=value;
    }

    public String execute() {
        events = serviceEvento.getEvents();
        return "success";
    }

    List<Evento> events;
    public List<Evento> getEvents() { return events; }

    // For redirect results
    protected String redirectUrl;

    public String getRedirectUrl() {
        return redirectUrl;
    }
    public String redirect(String to) {
        redirectUrl = to;
        return "redirect";
    }
}

EventoService.java:

package services;

import java.util.List;
import model.Evento;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

/**
 *
 * @author 
 */
public class EventoService {

    SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory value) {
        sessionFactory = value;
    }

    // Shortcut for sessionFactory.getCurrentSession()
    public Session sess() {
        return sessionFactory.getCurrentSession();
    }

    public Evento getEventById(long id) {
        return (Evento) sess().load(Evento.class, id);
    }


    public void deleteEventById(long id) {
        sess().delete(getEventById(id));
    }


    public void createEvent(String name) {
        Evento theEvent = new Evento();
        theEvent.setName(name);
        sess().save(theEvent);

    }

    @SuppressWarnings("unchecked")
    public List<Evento> getEvents() {
            System.out.println("\n\nGET EVENTS SERVICE");
        return sess().createQuery("from Event").list();
    }


}

Answers


// So that spring can inject the business singleton
protected EventoService serviceEvento;

public void setServiceEvento(EventoService value) {
    serviceEvento=value;
}

oops, replace to

// So that spring can inject the business singleton
protected EventoService eventoService;

public void setEventoService(EventoService value) {
    eventoService=value;
}

These changes is required to wire the object that configured with id="eventoService" in the spring configuration to the action property. The action is managed by the struts container and by default it uses the autowiring strategy by name

 ### specifies the autoWiring logic when using the SpringObjectFactory.
 ### valid values are: name, type, auto, and constructor (name is the default) 
 struts.objectFactory.spring.autoWire = name

Without wiring objects properly struts is unable to inject the dependency from the spring container. As a result the action property serviceEvento is not initialized and throws NPE. You may try other strategies for autowiring by type, or auto.

Another approach is to let the spring to manage action objects:


I see why you are getting a null pointer exception. In your applicationContext.xml, you asked spring to create an Instance of actions.ListingAction and inject an instance of serviceEvento in the created action class. That is perfect and it is suppose to work.

In your struts.xml, you specified that spring will be responsible for creating your actions by specifying <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />, that is also perfect.

I think the null pointer you are having is as a result of the below configuration in struts.xml.

    <action name="ListingAction" class="actions.ListingAction">
        <result name="success">/vistas/eventos/Listing.jsp</result>
    </action>

Here you specified the full path of actions.ListingAction, as a result this class is created and used in executing your actions. The instance previously created in applicationContext.xml wasn't used. That is the source of your null pointer, the serviceEvento by default using this method of creation is null. That's why you are having a null pointer.

Solution

Replace the full path of your action class in the struts.xml to the bean name that you defined in applicationContext.xml. That is

From

    <action name="ListingAction" class="actions.ListingAction">
        <result name="success">/vistas/eventos/Listing.jsp</result>
    </action>

To

    <action name="ListingAction" class="listingAction">
        <result name="success">/vistas/eventos/Listing.jsp</result>
    </action>

Let me know if this solves your problem.


Need Your Help

exporting an SSRS report to Excel failure

reporting-services ssrs-2008

When trying to export an SSRS report to excel, I am getting a runtime error. I have looked at the logs and see the following:

Generate a Javadoc for my Android project

java android javadoc

i was hoping someone could help me in generating a javadoc for my eclipse project. When i select 'Generate Javadoc' from the project menu I get lots of errors like

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.