关闭

struts2获得servlet对象的2种方式

623人阅读 评论(0) 收藏 举报

前言:struts2的Action里面放弃了request  response 等servlet API,使得业务层更加独立。但是有时候需要这些servlet对象,如用request获得session,用response向cookie对象中写数据等,如下为获得这些对象的两种方式:

 

方式一,通过ServletActionContext获得:

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

 

public class LoginAction extends ActionSupport {

 

public String login() {

  // 获取 request、response
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();

  // 将帐号放到 session 中
  HttpSession session = request.getSession(true);
  session.setAttribute("account", account);

  // 获取web应用根目录下 /upload 文件夹
  ServletContext context = ServletActionContext.getServletContext();
  File uploadFile = new File(context.getRealPath("upload"));

  return execute();
 }

}

方式二,利用相关的接口获得:ServletContextAware  servletRequestAware  ServletResponseAware SessionAware

import java.util.Map;

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.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class ServletAwareAction extends ActionSupport implements
  ServletRequestAware, ServletResponseAware, SessionAware,
  ServletContextAware {

 private static final long serialVersionUID = -2489850710438755365L;

 private ServletContext application;
 private HttpServletRequest request;
 private HttpServletResponse response;
 private Map session;

 public void setServletRequest(HttpServletRequest request) {
  this.request = request;
 }

 public void setServletResponse(HttpServletResponse response) {
  this.response = response;
 }

 public void setSession(Map sessionValues) {
  this.session = sessionValues;
 }

 public void setServletContext(ServletContext application) {
  this.application = application;
 }

 public String execute() {

  String upload = application.getRealPath("upload");
  
  request.getRemoteAddr();
  response.getContentType();
  session.get("account");

  return Action.SUCCESS;
 }
}

 

 

 

 

 

 

 

 

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:493208次
    • 积分:6238
    • 等级:
    • 排名:第4080名
    • 原创:231篇
    • 转载:93篇
    • 译文:3篇
    • 评论:29条