解耦与耦合的你我他

概念:

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

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

什么是与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;

    }
}

其他代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

     <package name="context" namespace="/context" extends="struts-default">
         <action name="contextAction_test" class="cn.itcast.context.ContextAction" method="test">
             <result name="success">/context/success.jsp</result>
             <result name="attr">/context/attr.jsp</result>
         </action>
         <action name="contextAction02_test" class="cn.itcast.context.Context02Action" method="test">
             <result name="success">/context/success.jsp</result>
             <result name="attr">/context/attr.jsp</result>
         </action>
     </package>

</struts>

struts_context.xml

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘test.jsp‘ starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <a href="${pageContext.request.contextPath }/context/contextAction_test.do">textContext</a><br/>
    <a href="${pageContext.request.contextPath }/context/contextAction02_test.do">testContext</a><br/>
  </body>
</html>

context/test.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘success.jsp‘ starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    xxxxxxxxxxxxxx<br/>
  </body>
</html>

context/success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘attr.jsp‘ starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    ${requestScope.username }<br/>
    ${sessionScope.username }<br/>
    ${applicationScope.username }
  </body>
</html>

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;

.

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 {
        .        
    }

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

.

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

.

}

public void setServletRequest(HttpServletRequest request) {

this.request=request;
    }

}

时间: 2024-07-29 07:45:56

解耦与耦合的你我他的相关文章

解耦与耦合

概念: 耦合是指两个或两个以上的体系或两种运动形式间通过相互作用而彼此影响以至联合起来的现象. 解耦就是用数学方法将两种运动分离开来处理问题,常用解耦方法就是忽略或简化对所研究问题影响较小的一种运动,只分析主要的运动. 什么是与Servlet API解耦? 为了避免与servlet API耦合在一起,方便Action做单元测试, Struts2对HttpServletRequest,HttpSession,和ServletContext进行了封装,构造了3个Map对象来替代这三个对象,在Acti

解耦和耦合

概念: 耦合是指两个或两个以上的体系或两种运动形式间通过相互作用而彼此影响以至联合起来的现象. 解耦就是用数学方法将两种运动分离开来处理问题,常用解耦方法就是忽略或简化对所研究问题影响较小的一种运动,只分析主要的运动. 什么是与Servlet API解耦? 为了避免与servlet API耦合在一起,方便Action做单元测试, Struts2对HttpServletRequest,HttpSession,和ServletContext进行了封装,构造了3个Map对象来替代这三个对象,在Acti

struts2案例

Struts 2是一个MVC框架,以WebWork框架的设计思想为核心,吸收了Struts 1的部分优点.Struts 2拥有更加广阔的前景,自身功能强大,还对其他框架下开发的程序提供很好的兼容性.下面我们了解一下syruts2的应用 1.1引入架包 1.2创建loginAction类 package cn.happy.action; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.st

四、初识耦合(一)

什么是耦合 我们总是听到说这有耦合,那要解耦.耦合看起来很高大上的名词,实际上耦合代表的就是各种元素之间的依赖性和相关性. 耦合的种类 数据之间的耦合:例如: class Person{ string name; int age; } name和age属于同一个类里面,他们就产生了耦合 函数之间的耦合: 同理,一个类中的两个函数也有相关性.如果两个函数之间有调用,即使不在同一个类中,也有耦合.例如:DriverCar()函数就和FillFuel函数产生了耦合. public DriverCar(

设计模式之禅之六大设计原则-迪米特原则

迪米特法则 一:迪米特法则定义:        ---->迪米特法则(Law of Demeter,LoD)也称为最少知识原则(Least KnowledgePrinciple,LKP),        ---->一个对象应该对其他对象有最少的了解.通俗地讲,一个类应该对自己需要耦合或调用的类知道得最少,你(被耦合或调用的类)的内部是如何复杂都和我没关系,那是你的事情,我就知道你提供的这么多public方法,我就调用这么多,其他的我一概不关心. 二:迪米特法则对类的低耦合提出明确的要求.   

Java--接口的思想

1.接口的出现,扩展了功能: 2.接口其实就是暴露出来的规则: 3.接口的出现降低了耦合性,解耦.        耦合性是联系的紧密程度. 接口的出现:一个在使用接口,一个在实现接口.     电脑在使用usb接口,插的设备在实现接口.

那些年搞不懂的高深术语——依赖倒置?控制反转?依赖注入?面向接口编程

那些年,空气中仿佛还能闻到汉唐盛世的余韵,因此你决不允许自己的脸上有油光,时刻保持活力.然而,你一定曾为这些“高深术语”感到过困扰.也许时至今日,你仍对它们一知半解.不过就在今天,这一切都将彻底改变!我将带领你以一种全新的高清视角进入奇妙的编程世界,领略涵泳在这些“高深术语”中的活泼泼的地气,以及翩跹于青萍之末的云水禅心. ·内聚 内聚,通俗的来讲,就是自己的东西自己保管,自己的事情自己做. 经典理论告诉我们,程序的两大要素:一个是数据(data),一个是操作(opration).而 PASCA

【设计模式】 面向对象六大设计原则

面向对象设计的六大原则 : 单一职责原则, 里氏替换原则, 依赖倒置原则, 接口隔离原则, 迪米特法则, 开闭原则; 一. 单一职责原则 1. 单一职责简介 单一职责定义 : 有且只有一个原因引起类的变化, 一个接口 或者 类 只有一个职责; 单一职责的好处 : -- 复杂性 : 降低类的复杂性, 对类或接口的职责有清晰明确定义; -- 可读性 : 提高可读性; -- 维护 : 提高可维护性; -- 变更风险 : 降低变更引起的风险, 接口改变只影响相应的实现类, 不影响其他类; 2. 单一职责

MVC 编程笔记2

转载自http://blog.csdn.net/kenkao/article/details/50291991 作者:吴秦 出处:http://www.cnblogs.com/skynet/ 本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名吴秦(包含链接). 参考资料 [1]     PureMVC官方网站:www.puremvc.org [2]     Wikipedia:http://zh.wikipedia.org/zh-cn/MVC [3]