码迷,mamicode.com
首页 > 其他好文 > 详细

在Struts2 Action中快速简便的访问Request、Session等变量

时间:2017-07-18 00:04:55      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:string   bbb   response   home   protect   extend   omr   ase   cte   

前言——正常情况下如何在Action中获取到这些变量

全部方法(共四种)可以参考:http://blog.csdn.net/itmyhome1990/article/details/7019476

这里采用其中一种作为示例,即利用ServletActionContext上下文来完成:

 1     public class LoginAction {  
 2         private HttpServletRequest request;  
 3         private HttpSession session;  
 4         private ServletContext application;  
 5         public String execute() {  
 6                   
 7             request = ServletActionContext.getRequest();  
 8             session = request.getSession();  
 9             application = session.getServletContext();  
10               
11             //application = ServletActionContext.getRequest().getSession().getServletContext();  
12               
13             request.setAttribute("aaa", "aaa");  
14             session.setAttribute("bbb", "bbb");  
15             application.setAttribute("ccc", "ccc");  
16               
17             return "success";  
18         }  
19     }  


但是呢,在我之前的学习过程中,在每个Action中都要重复这三部,显得过于繁琐。

在这样的情况下,我们可以通过继承一个BaseAction来解决这些问题。

 1 public class BaseAction extends ActionSupport{
 2 
 3     protected HttpServletRequest getRequest(){
 4         return ServletActionContext.getRequest();
 5     }
 6     
 7     protected HttpServletResponse getResponse(){
 8         return ServletActionContext.getResponse();
 9     }
10     protected HttpSession getSession(){
11         return getRequest().getSession();
12     }
13     
14         //快速执行标签
15     public void addActionErrorsFromResult(ExecuteResult<?> result) {
16         for (String error : result.getErrorMessages()) {
17             this.addActionError(error);
18         }
19     }
20     public void addFieldErrorsFromResult(ExecuteResult<?> result) {
21         for (String field : result.getFieldErrors().keySet()) {
22             this.addFieldError(field, result.getFieldErrors().get(field));
23         }
24     }
25 }    

这样,我们在写新的Action的时候,就只用extends BaseAction。

即可实现在Action中像在Servlet中一样直接获取Session、Request、Respose了,当然Application也可以实现,这里就不一一呈现了。

 

在Struts2 Action中快速简便的访问Request、Session等变量

标签:string   bbb   response   home   protect   extend   omr   ase   cte   

原文地址:http://www.cnblogs.com/rekent/p/7197869.html

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