Struts2中获取requset,session,application

struts2中Action是集成于com.opensymphony.xwork2.ActionSupport

假如我们需要再Action的execute方法中获取request对象,我们可以通过在实现ServletRequestAware, SessionAware, ServletContextAware这三个接口即可,前提是我们需要导入servlet-api.jar

 

比如我们可以定义一个基础的Action类:BaseAction.java

 

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware, SessionAware, ServletContextAware{
	@SuppressWarnings("unused")
	protected HttpServletRequest request;
    @SuppressWarnings("unused")
	protected Map<String, String> session;
    @SuppressWarnings("unused")
	protected ServletContext application;
	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unchecked")
	public void setSession(Map session) {
		this.session = session;      
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public void setServletContext(ServletContext application) {
		this.application = application;
	}

}

 之后我们在也Action的时候直接继承BaseAction 即可

 

public class UserListAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	@Resource(name="userService")
	private UserService userService;
	
	private List<UserVo> userList;
	
	public List<UserVo> getUserList() {
		return userList;
	}

	public void setUserList(List<UserVo> userList) {
		this.userList = userList;
	}

	public String execute() throws Exception {
		request.setAttribute("userName", "Max From request");
        session.put("userName", "Max From session");
        application.setAttribute("userName", "Max From application");

		userList = userService.getUsers();
		return SUCCESS;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}



}

 

你可能感兴趣的:(apache,servlet)