Struts的 action访问servlet API的三种方法

1、提供ActionContext类访问

2、提供ServletRequestAware、ServletResponseAware、ServletContextAware接口访问servlet API 。

具体操作

分别要定义private HttpServletRequest request 再实现接口中的public void setServletRequest(HttpServletRequest request)方法

                   private HttpServletResponse response 再实现接口中的public void setServletResponse(HttpServletResponse response)方法

                   private ServletConetext context 再实现接口中的public void setServletResponse(ServletConetext context )方法

例如:

action类:

package org.cai.app.action;

import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;

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


public class LoginAction implements Action,ServletResponseAware {
 private String username;
 private String password;
 private HttpServletResponse response;
 
 public void setResqonse(HttpServletResponse response) {
  this.response = response;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 /**public String execute() throws Exception
 {
  if(getUsername().equals("cai") && getPassword().equals("123456"))
  {
   ActionContext.getContext().getSession().put("user", getUsername());
   return SUCCESS;
  }
  else
  {
   return ERROR;
  }
 
 public String execute() throws Exception
 {
  ActionContext ctx = ActionContext.getContext();
  Integer counter = (Integer) ctx.getApplication().get("counter");
  if(counter == null)
  {
   counter = 1;
  }else
  {
   counter = counter + 1;
  }
  ctx.getApplication().put("counter", counter);
  ctx.getSession().put("user", getUsername());
  if(getUsername().equals("cai") && getPassword().equals("123456"))
  {
   Cookie c = new Cookie("user",getUsername());
   c.setMaxAge(60*60);
   response.addCookie(c);
   ctx.put("tip", "服务器提示:您已经成功登录");
   return SUCCESS;
  }
  else
  {
   ctx.put("tip", "服务器提示:登录失败");
   return ERROR;
  }
 }
 

}


3、提供ServletActionContext 工具类访问servlet API,该类提供如下几个静态方法

     static PageContext getPageContext() 获取web 的PageContext

     static ServletContext getServletContext() 获取ServletContext

     static HttpServletRequest getRequest() 获取HttpServletReques

     static HttpServletResponse getResponse() 获取HttpServletResponse 

例如例子中的response.addCookie(c); 可以换成 ServletActionContext.getResponse().addCookie(c);





你可能感兴趣的:(Struts的 action访问servlet API的三种方法)