Struts2获取web资源的几种方式

1、通过ActionContext直接获取

 1 public testAction extends ActionSupport {
 2     private Map request;
 3     private Map session;
 4     private Map application;
 5         public testAction(){
 6                 request = (Map)ActionContext.getContext().get("request");
 7             session = ActionContext.getContext().getSession();
 8             application = ActionContext.getContext().getApplication();
 9         }
10 }

2 通过实现XXXXAware接口

 1 public class testAction extends ActionSupport implements  RequestAware, SessionAware, ApplicationAware, ParameterAware {
 2     private Map<String, Object> request;
 3     private Map<String, Object> session;
 4     private Map<String, Object> application;
 5         public void setApplication(Map<String, Object> application) {
 6         // TODO Auto-generated method stub
 7         this.application = application;
 8     }
 9     public void setSession(Map<String, Object> session) {//实现接口中的方法
10         // TODO Auto-generated method stub
11         this.session = session;
12     }
13     public void setRequest(Map<String, Object> request) {//实现接口中的方法
14         // TODO Auto-generated method stub
15         this.request = request;
16     }
17     public void setParameters(Map<String, String[]> parameters) {//实现接口中的方法
18         // TODO Auto-generated method stub
19         this.parameters = parameters;
20     } 
21 }
22         

3、获取Servlet中原生的web元素

 1   public class testAction extends ActionSupport {
 2       private HttpServletRequest request;
 3       private HttpSession session;
 4       private ServletContext application;
 5       
 6       public testAction(){
 7           /**
 8            * ServletActionContext对象获取原生web元素
 9            * HttpServletRequest等
10            */
11          request = ServletActionContext.getRequest();
12          session = request.getSession();
13          application = ServletActionContext.getServletContext();
14      }
15  }

4、实现ServletXXXAware接口获取原生Servlet中的Web元素

 1 /**
 2  * 实现ServletXXXAware 接口 
 3  * 可以获取到原生的Servlet API中的
 4  * request 
 5  * response servletcontext对象
 6  * @author ThinkPad
 7  *
 8  */
 9 public class loginAction4 
10     implements ServletRequestAware, ServletContextAware, ServletResponseAware {
11     public String execute(){
12         return "success";
13     }
14     @Override
15     public void setServletResponse(HttpServletResponse response) {
16         // TODO Auto-generated method stub
17         System.out.println(response);
18     }
19 
20     @Override
21     public void setServletContext(ServletContext context) {
22         // TODO Auto-generated method stub
23         System.out.println(context);
24     }
25 
26     @Override
27     public void setServletRequest(HttpServletRequest request) {
28         // TODO Auto-generated method stub
29         System.out.println(request);
30     }
31 
32     
33     
34 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。