在Action中获取servlet API(1)

Struts2的Action组件是不依赖servlet API 的。那么当你在action中的业务需要处理HttpServletRequest和HttpServletResponse的时候(比如要对响应做处理写cookie,生成验证码)怎么办呢?

有3种办法可以实现action中获取servlet api


1.使用ServletActionContext的静态方法


Struts2使用ServletActionContext对象维护Servlet api 对象(像request,response,session,application)。ServletActionContext使用ThreadLocal(线程局部变量,关于ThreadLocal请参看本博另一篇文章《理解TheadLocal(线程局部变量)》),这样能保证获取的是当前用户当前线程的servlet api对象。



public class TestAction {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session =  request.getSession();
ActionContext actionContext = ServletActionContext.getActionContext(request);
ActionContext context = ServletActionContext.getContext();
ActionMapping mapping = ServletActionContext.getActionMapping();
PageContext pageContext =  ServletActionContext.getPageContext();
ServletContext servletContext = ServletActionContext.getServletContext();
ValueStack valueStack = ServletActionContext.getValueStack(request);
}


2.使用ActionContext

public class TestAction {
    ActionContext context = ActionContext.getContext();
    
    public void test(){
ActionInvocation actionInvocation = context.getActionInvocation();
Locale locale = context.getLocale();
ValueStack valueStack = context.getValueStack();
Container container =  context.getContainer();
Map<String, Object> parameters = context.getParameters();
Map<String, Object> session = context.getSession();
Map<String, Object> application = context.getApplication();
Map<String, Object> contextMpap = context.getContextMap();
Map<String, Object> conversionErrorss = context.getConversionErrors();
    }
    
}



3.使用Struts2的资源注入拦截器


让你的action继承几个接口,实现他们的方法,然后声明serlvet api对象的变量就行了,在运行时struts2会把相对的对象注入到你的变量中。

这种注入不用多解释肯定是拦截器实现的啦!

而且值得注意的是session的接收变量是一个map而不是httpsession


public class TestAction implements ServletContextAware,ServletRequestAware,ServletResponseAware,SessionAware {
private ServletContext servletContext;
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, Object> session;
/***实现相应接口的方法******/
public void setServletContext(ServletContext arg0) {
this.servletContext  = arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
This.request = arg0;
}
public void setServletResponse(HttpServletResponse arg0) {
This.response = arg0;
}
public void setSession(Map<String, Object> arg0) {
This.sessoin = arg0;
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值