Struts 2之Servlet API


Struts 2对Servlet API进行了封装,是业务层更加独立,如果需要调用Request、Response等Servlet API有两种途径

利用ServletActinContext的静态方法

Struts 2利用ServletActinContext来维护Servlet对象,ServletActinContext利用ThreadLocal来维护不同线程的Servlet对象,因此可以使用ServletActinContext来获得Servlet的各种对象

import  org.apache.struts2. ServletActinContext;
public  class  LoginActin extends ActionSupport{
 
      public String login(){
             HttpServletRequest request = ServletActinContext.getRequest();
             HttpServletResponse response = ServletActinContext.getResponse();
             HttpServletContext context = ServletActinContext.getServletContext();
             HttpSession session = request.getSession();
             ……
      }
     
}

利用相关的Aware接口

Struts 2在实例化一个Action实例时,如果发现它实现了相关的Aware接口,会把相应的资源通过Aware接口方法注射进去,Aware接口其实是一种拦截器

Servlet API常用对象application、request、response、session对应的Aware接口分别为ServletContextAware、ServletRequestAware、ServletResponseAware、SessionAware

public class ServletAwareActionextends ActionSupport implementsServletContextAware,ServletRequestAware,ServletResponseAware,SessionAware{
 
      private HttpServletRequest request ;
      private HttpServletResponse response;
      private HttpServletContext application;
      private HttpSession session ;
 
      //相应的setter方法
      public void setServletRequest(HttpServletRequest request ){
             this.request = request;
      }
      public void setServletResponse(HttpServletResponse response ){
             this.reponse = reponse;
      }
      public void setServletContext(HttpServletContext application ){
             this. application = application;
      }
      public void setSession(Map sessionValues){
             this.session = sessionValues;
      }
      //然后可以在Action中直接使用这些对象
      public String execute(){
             request.getRemoteAddr();
             response.getContentType()
             session.get(“account”);
             return SUCCESS;
      }
}


Struts 2之Servlet API

上一篇:在Windows平台上安装Node.js及NPM模块管理


下一篇:sql语句执行顺序