码迷,mamicode.com
首页 > Windows程序 > 详细

Struts 2之Servlet API

时间:2015-02-10 09:16:15      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:struts 2   servlet   aware   


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

标签:struts 2   servlet   aware   

原文地址:http://blog.csdn.net/u012152619/article/details/43698801

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!