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 list Elements in action, but I don't know why.

I think the bean was not created because the error is thrown when the execute()

activity is called.

Struts Issue 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 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 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();
    }


}

      

+2


source to share


2 answers


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

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

      

oops, replace with

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

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

      

These changes are needed to bind the object configured with id="eventoService"

spring configuration to the action property. The action is managed by the struts container and by default uses the autwiring 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 mounting objects, the correct racks cannot inject dependency from spring container. As a result, the action property is serviceEvento

not initialized and throws the NPE. You can try other strategies for autowiring on type

or auto

.

Another approach is to let spring manage the action objects:

0


source


I understand why you are getting a null pointer exception. In applicationContext.xml

you asked spring to create an instance actions.ListingAction

and insert an instance serviceEvento

into the generated action class. This is perfect and it should work.

In struts.xml

you have indicated what spring

will be responsible for creating your actions, indicating <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />

which is also ideal.

I think the null pointer you have is the result of the following configuration in struts.xml

.

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

      

Here you have specified the full path actions.ListingAction

, as a result this class is created and used to perform your actions. An instance previously created in applicationContext.xml

was not used. This is the source of your null pointer, serviceEvento

by default using this create method is null. This is why you have a null pointer.

Decision



Replace the full path of your action class in struts.xml

with the bean name specified in applicationContext.xml

. it

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.

0


source







All Articles