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);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值