2

我有一个例子的问题。

当我在操作中列出元素时出现此错误,但我不知道为什么。

我认为没有创建 bean,因为execute() 调用 action 时会发生错误。

Struts 问题报告:

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

堆栈跟踪:

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


}
4

2 回答 2

0

我明白为什么你会得到一个空指针异常。在您的applicationContext.xml中,您要求 spring 创建一个实例并在创建的操作类中actions.ListingAction注入一个实例。serviceEvento这是完美的,它应该可以工作。

在 yourstruts.xml中,您指定spring将负责通过指定来创建您的操作<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />,这也是完美的。

我认为您拥有的空指针是由于struts.xml.

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

在这里,您指定了 的完整路径actions.ListingAction,因此该类被创建并用于执行您的操作。之前创建的实例applicationContext.xml没有被使用。那是你的空指针的来源,serviceEvento默认情况下使用这种创建方法是空的。这就是为什么你有一个空指针。

解决方案

将 中的操作类的完整路径替换为您在 中struts.xml定义的 bean 名称applicationContext.xml。那是

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

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

让我知道这是否可以解决您的问题。

于 2013-08-06T05:12:00.957 回答
0
// So that spring can inject the business singleton
protected EventoService serviceEvento;

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

哎呀,换成

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

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

需要这些更改才能将id="eventoService"在 spring 配置中配置的对象连接到 action 属性。该操作由 struts 容器管理,默认情况下它使用名称自动装配策略

### 指定使用 SpringObjectFactory 时的 autoWiring 逻辑。
 ### 有效值为:名称、类型、自动和构造函数(名称为默认值)
 struts.objectFactory.spring.autoWire = 名称

如果没有正确连接对象,struts 将无法从 spring 容器中注入依赖项。结果,action 属性serviceEvento未初始化并抛出 NPE。type您可以尝试通过或进行自动装配的其他策略auto

另一种做法是让spring来管理action对象:

于 2013-08-05T19:15:51.803 回答