解耦与耦合

摘要:
解耦是使用数学方法来分离两个运动来处理问题。常用的解耦方法是忽略或简化对所研究问题影响不大的运动,只分析主要运动。为了避免与servlet API耦合并促进Action的单元测试,Struts2封装了HttpServletRequest、HttpSession和ServletContext,并构造了三个Map对象来替换这三个对象。在Action中,您可以直接使用与HttpServletRequest、HttpSession和ServletContext对应的Map对象来保存和读取数据。两种解耦方法:1。使用Struts2提供的工具类中提供的静态方法获取要使用的封装对象。
概念:

 耦合是指两个或两个以上的体系或两种运动形式间通过相互作用而彼此影响以至联合起来的现象。

 解耦就是用数学方法将两种运动分离开来处理问题,常用解耦方法就是忽略或简化对所研究问题影响较小的一种运动,只分析主要的运动。
 

什么是与Servlet API解耦?

为了避免与servlet API耦合在一起,方便Action做单元测试,

Struts2对HttpServletRequest,HttpSession,和ServletContext进行了封装,构造了3个Map对象来替代这三个对象,在Action中可以直接使用HttpServletRequest,HttpSession,ServletContext对应的Map对象来保存和读取数据。

 

两种解耦方式:

1、    使用Struts2提供的工具类中提供的静态方法,得到对用的封装后对象。

  

复制代码
复制代码
复制代码
package cn.itcast.context;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ContextAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public String test() throws Exception{
        System.out.println("ContextAction ****** test()");
        
        HttpServletRequest request=ServletActionContext.getRequest();
        request.setAttribute("username","username_request");
        
        HttpServletResponse response=ServletActionContext.getResponse();
        
        Map sessionMap=ServletActionContext.getContext().getSession();
        sessionMap.put("username", "username_session");
        
        ServletContext sc=ServletActionContext.getServletContext();
        sc.setAttribute("username", "username_application");
        
        return "attr";
    }
}
复制代码
复制代码
复制代码

 

2、    Action实现ServletRequestAware,ServletResponseAware,ServletContextAware,SessionAware四个接口,分别重写对应的set方法,达到操作该4个封装后对象。

复制代码
复制代码
复制代码
package cn.itcast.context;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class Context02Action extends ActionSupport 
    implements ServletRequestAware,ServletResponseAware,ServletContextAware,SessionAware{

    HttpServletRequest request;
    HttpServletResponse response;
    ServletContext context;
    Map<String, Object> sessionMap;
    
    private static final long serialVersionUID = 1L;

    public String test() throws Exception{
        System.out.println("ContextAction ****** test()");
        
        HttpServletRequest request=ServletActionContext.getRequest();
        request.setAttribute("username","username_request");
        
        HttpServletResponse response=ServletActionContext.getResponse();
        
        Map sessionMap=ServletActionContext.getContext().getSession();
        sessionMap.put("username", "username_session");
        
        ServletContext sc=ServletActionContext.getServletContext();
        sc.setAttribute("username", "username_application");
        
        return "attr";
    }

    public void setSession(Map<String, Object> session) {
        this.sessionMap=session;
    }

    public void setServletContext(ServletContext context) {
        this.context=context;
        
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response=response;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request=request;
        
    }
}
复制代码
复制代码
复制代码

其他代码:

 

解耦与耦合第13张 struts_context.xml
解耦与耦合第14张 context/test.jsp
解耦与耦合第15张 context/success.jsp
解耦与耦合第16张 context/attr.jsp

 

struts2与servlet的耦合有三种实现方案:

1.ActionContext

在xwork2.jar的com.opensymphony.xwork2.ActionContext中。

这个是最推荐的一种实现。

action不需要实现接口,只需要引入这个目录就可以。

ActionContext.getContext().put("zhangsan","helloworld");

 

只需要一句代码就可以放入response中,页面直接用EL表达式${requestScope.zhangsan}获取。取代了标签

<s:property value="zhangsan"/>

 

2.servletActionContext

在struts2-core.jar中,org.apache.struts2.ServletActionContext

同样action不需要实现接口,只需要引入这个目录就可以。

HttpServletResponse response = ServletActionContext.getResponse();

 

实现了response对象,然后只需要像往常一样适用

 

Cookie cookie = new Cookie("username", this.getUsername());
cookie.setMaxAge(1000);
response.addCookie(cookie);

 

3.ServletRequestAware,ServletResponseAware接口实现

首先实现接口,然后实现request或response对象。

 

复制代码
复制代码
复制代码
package com.test.action;

解耦与耦合第20张解耦与耦合第20张解耦与耦合第20张.

public class LoginAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = 3936066275134469754L;
    // private HttpServletResponse response;

     private HttpServletRequest request;

    @SuppressWarnings("unchecked")
    public String execute() throws Exception {
        解耦与耦合第20张解耦与耦合第20张.        
    }

    @SuppressWarnings("unchecked")
    public String hello() throws Exception {

        解耦与耦合第20张解耦与耦合第20张.

            request.setAttribute("zhangsan","helloworld");

        解耦与耦合第20张解耦与耦合第20张.

    }

    public void setServletRequest(HttpServletRequest request) {

        this.request=request;
    }

}
复制代码
复制代码
复制代码

 

Action类案例:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
publicclassFirstAction implementsAction,ModelDriven<UserInfo>,ServletRequestAware{
    privateMap<String, Object> map;
    privateHttpServletRequest request;
    //前台输入的用户名和密码 在Action中如何捕获
        privateUserInfo user=newUserInfo();
        publicString execute() throwsException {
            System.out.println("====FirstAction   ==============+++execute");
            System.out.println("================="+user);
            if(user.getUsername().equals("admin")&&user.getPassword().equals("admin")){
 
                //解耦合方式一
                //Map<String, Object> session = ActionContext.getContext().getSession();
                 
                 
                //解耦合方式2:IOC(注入)SessionAware
                 
                 
                //耦合方式一
                /*HttpSession session2 = ServletActionContext.getRequest().getSession();
                 
                //耦合方式2
                Map<String, Object> session = ServletActionContext.getContext().getSession();
                */
                //session.put("uname", user.getUsername());
                 
                //session2.setAttribute("uname", user.getUsername());
                 
                 
                 
                //map.put("uname", user.getUsername());
                 
                request.getSession().setAttribute("uname", user.getUsername());
             return"success";
            }else{
                return"login";
            }
        }
         
         
    publicMap<String, Object> getMap() {
        returnmap;
    }
 
    publicvoidsetMap(Map<String, Object> map) {
        this.map = map;
    }
 
     
    publicHttpServletRequest getRequest() {
        returnrequest;
    }
 
    publicvoidsetRequest(HttpServletRequest request) {
        this.request = request; 
    }
 
     
    publicUserInfo getUser() {
        returnuser;
    }
    publicvoidsetUser(UserInfo user) {
        this.user = user;
    }
 
    publicUserInfo getModel() {
        returnnull;
    }
 
    publicvoidsetServletRequest(HttpServletRequest request) {
        this.request=request;
         
    }
    publicvoidsetSession(Map<String, Object> map) {
        this.map=map;
   }
}

免责声明:文章转载自《解耦与耦合》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android中RadioGroup的初始化和简单的使用(转)32位win7用尽4g内存的几种解决方式下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C++实现ftp客户端

#ifndef CLIENT_H_ #define CLIENT_H_ #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include &...

02_View

1、View 1、基于类的视图 Class-based Views REST framework提供APIView是Django的View的子类发送到View的Request请求:是REST framework的Request类的实例,而不是Django的HttpRequest类的实例View返回的Response响应:返回REST framework的R...

服务器使用Gzip压缩数据,加快网络传输(Java 例子)

The next version of the Project will provide support for gzip in order to faster speed of data transmission on the network。在我们的项目中,添加对gzip的支持,是为了加快数据在网络中的传输速度。If you need to trans...

Response.flush的用法

很多时候我们写的程序,会花上一分钟甚至几分钟时间。为了使软件使用者能够耐心的等待程序的执行,我们经常会希望有一个进度条来表示程序执行的状态。或者最起码要显示一个类似: “数据载入中”,“正在保存数据” 等的说明性文字。此时我们就会用到Response.flush()(刷新缓冲区数据)。他会将缓冲区中编译完成的数据先发送到客户端。 (引用: 但是有很多时候,...

Struts2升级出现的问题

由于大家都懂的原因,涉struts2的项目需要将struts2相关包升级至2.3.15.1。今将升级方法和常见问题解决简单总结如下。   一、基本升级操作 1. 获取Struts2.3.15.1jar包 从Struts官网下载struts2.3.15.1发布包: http://apache.fayea.com/apache-mirror//struts/l...

python3 + Django + Mysql + Vue + Element-UI 学习笔记:从0搭建前后端分离的测试工具平台

2020.03.23  INIT 中间换了工作,好久没写了 2021.05.08  新增:页面预览、功能实现样例(含后端接口、前端页面、配置绑定) 2021.05.13  新增:首页增加访问人数统计功能 2021.05.19  新增:用户信息查询接口、页面开发 2021.06.10  新增:生成图片功能 2021.06.18  新增:文本处理工具下载页面...