得到作用域对象有三种方法,这里用代码来解释:

 package com.cy.action;

 import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware,ServletContextAware { private static final long serialVersionUID = 1L;
private ServletContext servletContext;
private HttpServletRequest request;
private HttpServletResponse response; @Override
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
this.servletContext=arg0; } @Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
this.response=arg0; } @Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
this.request=arg0;
} public HttpServletRequest getRequest() {
return request;
} public void setRequest(HttpServletRequest request) {
this.request = request;
} public HttpServletResponse getResponse() {
return response;
} public void setResponse(HttpServletResponse response) {
this.response = response;
} public ServletContext getServletContext() {
return servletContext;
} }
 //--------------Struts2 操作作用域的3种方式-------------------
// //采用实现接口的方式,来获取作用域(最常用)
// getRequest().setAttribute(arg0, arg1)
// getRequest().getSession().setAttribute(arg0, arg1)
// getServletContext().setAttribute(arg0, arg1)
// // //采用ActionContext对象来对作用域进行操作
// ActionContext ac = ActionContext.getContext();
// ac.put(key, value);//直接对request进行操作。
// ac.getSession().put(key, value)//向Session中设值
// ac.getApplication().put(key, value)//向ServletContext中设值 // //采用ServletActionContext对象来对作用域进行操作
// HttpServletRequest request = ServletActionContext.getRequest();
// HttpServletResponse response = ServletActionContext.getResponse();
// ServletContext sevletContext = ServletActionContext.getServletContext();
//

随着技术不断的更新,这里的仅供参考!(Struts在公司里已经不再是主流了!)

05-11 15:08