域对象的引用,ActionContext 和ServletActionContext类的使用

 

ActionContext 获取 域引用的map

ServletActionContext获取具体域对象

 

//域范围

        ActionContext ac = ActionContext.getContext();
        Map<String,Object> applicationMap = ac.getApplication();//这个就是ServletContext对象中维护的那个Map
        applicationMap.put("p", "application_p");// ServletContext.setAttribute(key,object);
        
        Map<String,Object> sessionMap = ac.getSession();//这个就是HttpSession对象中维护的那个Map
        sessionMap.put("p", "session_p");// HttpSession.setAttribute(key,object);
        
        ac.put("p", "request_p");//相当于ServletRequest.setAttribute(key,obj);

 

 1 //获取Servlet中的常用对象的引用
 2 
 3 //ServletContextAware接口
 4 
 5 public class WebObjectAction extends ActionSupport implements Serializable,ServletContextAware,ServletRequestAware,ServletResponseAware {
 6     private ServletContext context;
 7     private HttpServletRequest request;
 8     private HttpServletResponse response;
 9     //方式一
10     public String execute1(){
11         ServletContext sc = ServletActionContext.getServletContext();
12         System.out.println(sc);
13         ServletRequest request = ServletActionContext.getRequest();
14         System.out.println(request);
15         return SUCCESS;
16     }
17     //方式二
18     public String execute2(){
19         System.out.println(context);
20         System.out.println(request);
21         System.out.println(response);
22         return SUCCESS;
23     }
24     public void setServletContext(ServletContext context) {//如果动作类实现了ServletContextAware接口,就会自动调用该方法
25         this.context = context;
26     }
27     public void setServletRequest(HttpServletRequest request) {
28         this.request = request;
29     }
30     public void setServletResponse(HttpServletResponse response) {
31         this.response = response;
32     }
33 
34     
35     
36 }

 

你可能感兴趣的:(ActionContext)