spring 管理action实例 scope="session"

来源:互联网 发布:京东万象数据平台 编辑:程序博客网 时间:2024/04/28 02:55
很多人都采用scope="request"这种解决方案,殊不知此方治标不治本,原因:scope="request"表示每次请求都要创建一个action实例,spring容器会很累的,

以下是我的解决方案:

写一个拦截器:

public class ClearFieldErrorInterceptor extends AbstractInterceptor {

private static final long serialVersionUID = 4515996553750206887L;

@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionSupport actionSupport = (ActionSupport)invocation.getAction();
actionSupport.clearErrorsAndMessages();
String resultCode = invocation.invoke();
return resultCode;
}

}
此拦截器作用是每次request过来时先把上次遗留下来的fieldError清空,然后此拦截器放的位置也有讲究,必须放在struts2默认拦截器的后面,以下是片段:

<action name="validateTest" class="test">
  <interceptor-ref name="clearFieldErrorCacheInterceptor"/><!-- 这就是自定义的拦截器-->
  <interceptor-ref name="strutsDefaultInterceptor"/><!-- 这是struts2的默认拦截器,必须加上,它的定义这里没有给出,要具体方案msn我 -->
  <result name="input">/jsp/message/test.jsp</result>
  <result name="success">/jsp/message/test.jsp</result>
</action>

最后将每个action类的生命周期设置为session,表示为一个session只创建一个action实例,代码片段:

<bean name="test" class="com.shanghai.home.action.message.TestAction" scope="session"/>

至此问题解决,不是很难,熟习struts2.0的都应该看得懂我写的,如果你是初学者建议你就scope="request"那么设置,但是万万不能用在项目中,否则项目经理打你PP可别哭........

这是我的msn联系邮箱:b03153122@hotmail.com,不懂的可以问我

哦,忘记说了,要在spring中将action的范围设置为session必须引入一个listener,在web.xml中写上:

<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

这样,spring才能认识scope="session"这句话!

原创粉丝点击