1. Web.xml 配置将ApplicationContext.xml读取到Session保存
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. 书写Action基类
Action基类必须继承ActionSupport , 实现spring的三个接口ServletRequestAware,ServletResponseAware,SessionAware。这三个结口提供了request、response、session的注入。
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport implements
ServletRequestAware,ServletResponseAware,SessionAware{
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map session;
protected Logger logger = Logger.getLogger(getClass());
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setSession(Map session) {
this.session = session;
}
public ApplicationContext getContext() {
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getSession()
.getServletContext());
return ctx;
}
}
3.以上代码提供了将ApplicationContext.xml读取到Session保存,然后又从session中读取ApplicationContext.xml的实现办法
本文介绍了如何在Web.xml中配置加载ApplicationContext.xml,并在Action基类中利用Servlet监听器将上下文保存到Session,以便在需要时从Session中获取。Action基类实现了ServletRequestAware, ServletResponseAware, SessionAware接口,提供了对请求、响应和Session的访问,同时提供了获取ApplicationContext的方法。"
91385152,7676821,C语言链表实现:录入学生信息并查找特定学号,"['C语言', '链表实现', '数据结构']
519

被折叠的 条评论
为什么被折叠?



