解耦

1.概述

解耦就是尽量降低代码的耦合度。

 

2.方式一

 1 /**
 2      * 解耦方式一:
 3      *     通过ActionContext对象的getContext()获取Servlet对象
 4      * @return
 5      */
 6     public String api1(){
 7         //1、设置Session
 8         //Session中的数据是以键值对的形式存在的
 9         Map<String,Object> session = ActionContext.getContext().getSession();
10         //将键值对存储到Map集合中
11         session.put("user", "Mike");
12         session.put("age", 20);
13         //将Session添加到ActionContext中
14         ActionContext.getContext().setSession(session);
15                 
16         //2、Application
17         Map<String,Object> application = ActionContext.getContext().getApplication();
18         //设置Application的值
19         application.put("count", "100");
20         ActionContext.getContext().setApplication(application);
21     
22         
23         //3、获取parameter(URL地址中的请求参数)
24         //http://localhost:8080/03ServletAPI/api1.action?name=Mike&age=20&gender=true
25         Map<String,Object> parameters = ActionContext.getContext().getParameters();
26         //获取Key的集合
27         Set<String> keys = parameters.keySet();
28         //获取set的迭代器
29         Iterator<String> iterator = keys.iterator();
30         //遍历迭代器
31         while(iterator.hasNext()){
32             //获取key的值
33             String key = iterator.next();
34             System.out.println(key + " = " + parameters.get(key));
35         }
36         
37         //4、request
38         Map<String,Object> request = (Map<String,Object>)ActionContext.getContext().get("request");
39         
40         return "success";
41     }

 

3.方式二(推荐使用)

 

 1     /**
 2      * 解耦方式二:
 3      *     StrutsStatics中定义了常用对象的字符串(字符串内容是类的完整名称)
 4      * @return
 5      * @throws IOException 
 6      */
 7     public String api2() throws IOException{
 8         //1、获取Request对象
 9         HttpServletRequest req = (HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
10         
11         //通过Request对象获取Session对象
12         HttpSession session = req.getSession();
13         
14         //通过Request对象获取application对象
15         ServletContext application = req.getServletContext();
16         
17         //通过Reqeust对象获取请求参数
18         String name = req.getParameter("name");
19         
20         
21         //2、获取Response对象
22         HttpServletResponse resp = (HttpServletResponse)ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
23         resp.getWriter().print("abvc");
24         
25         return "success";
26     }

 

posted @ 2018-11-11 14:02  猩生柯北  阅读(466)  评论(0编辑  收藏  举报