附录⼀ 乱码问题解决

1. Post请求乱码,web.xml中加⼊过滤器

  1. <!-- 解决post乱码问题 -->
  2. <filter>
  3. <filter-name>encoding</filter-name>
  4. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  5. <!-- 设置编码参是UTF8 -->
  6. <init-param>
  7. <param-name>encoding</param-name>
  8. <param-value>UTF-8</param-value>
  9. </init-param>
  10. <init-param>
  11. <param-name>forceEncoding</param-name>
  12. <param-value>true</param-value>
  13. </init-param>
  14. </filter>
  15. <filter-mapping>
  16. <filter-name>encoding</filter-name>
  17. <url-pattern>/*</url-pattern>
  18. </filter-mapping>

2. Get请求乱码(Get请求乱码需要修改tomcat下server.xml的配置)

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080"
protocol="HTTP/1.1" redirectPort="8443"/>

附录⼆ 玩转Spring MVC 必备设计模式

说明:本部分设计模式作为直播扩展内容的⼀部分

1. 策略模式

策略模式(Strategy),就是⼀个问题有多种解决⽅案,选择其中的⼀种使⽤,这种情况下我们
使⽤策略模式来实现灵活地选择,也能够⽅便地增加新的解决⽅案。⽐如做数学题,⼀个问题的
解法可能有多种;再⽐如商场的打折促销活动,打折⽅案也有很多种,有些商品是不参与折扣活
动要按照原价销售,有些商品打8.5折,有些打6折,有些是返现5元等。

1.1 结构

(1)策略(Strategy)

定义所有⽀持算法的公共接⼝。 Context 使⽤这个接⼝来调⽤某 ConcreteStrategy 定义的算法。

(2)策略实现(ConcreteStrategy)

实现了Strategy 接⼝的具体算法

(3)上下⽂(Context)

维护⼀个 Strategy 对象的引⽤
⽤⼀个 ConcreteStrategy 对象来装配
可定义⼀个接⼝⽅法让 Strategy 访问它的数据

1.2 示例

假如现在有⼀个商场优惠活动,有的商品原价售卖,有的商品打8.5折,有的商品打6折,有的返现5元

package designpattern.strategy.old;

import java.text.MessageFormat;
public class BuyGoods {
  private String goods;
  private double price;
  private double finalPrice;
  private String desc;
  public BuyGoods(String goods, double price) {
    this.goods = goods;
    this.price = price;
  }
  public double calculate(String discountType) {
    if ("discount85".equals(discountType)) {
      finalPrice = price * 0.85;
      desc = "该商品可享受8.5折优惠";
    } else if ("discount6".equals(discountType)) {
      finalPrice = price * 0.6;
      desc = "该商品可享受6折优惠";
    } else if ("return5".equals(discountType)) {
      finalPrice = price >= 5 ? price - 5 : 0;
      desc = "该商品可返现5元";
    } else {
      finalPrice = price;
      desc = "对不起,该商品不参与优惠活动";
    }
    System.out.println(MessageFormat.format("您购买的商品为:{0},原价为:{1},{2},最终售卖价格为:{3}", goods, price, desc, finalPrice));
    return finalPrice;
  }
}

1.2.1 测试

package designpattern.strategy.old;

public class Test {
    public static void main(String[] args) {
        BuyGoods buyGoods1 = new BuyGoods("Java编程思想", 99.00);
        buyGoods1.calculate("discount85");
        BuyGoods buyGoods2 = new BuyGoods("罗技⿏标", 66 );
        buyGoods2.calculate("discount6");
        BuyGoods buyGoods3 = new BuyGoods("苹果笔记本", 15000.00);
        buyGoods3.calculate("return5");
        BuyGoods buyGoods4 = new BuyGoods("佳能相机", 1900);
        buyGoods4.calculate(null);
    }
}

1.2.2 问题

上述代码可以解决问题,但是从代码设计的⻆度还是存在⼀些问题

  • 增加或者修改打折⽅案时必须修改 BuyGoods 类源代码,违反了⾯向对象设计的 “开闭原则”,代码的灵活性和扩展性较差。
  • 打折⽅案代码聚合在⼀起,如果其他项⽬需要重⽤某个打折⽅案的代码,只能复制粘贴对应代码,⽆法以类组件的⽅式进⾏重⽤,代码的复⽤性差。
  • BuyGoods 类的 calculate() ⽅法随着优惠⽅案的增多会⾮常庞⼤,代码中会出现很多if分⽀,可维护性差。

    1.2.3 解决方法

    此时,我们可以使⽤策略模式对 BuyGoods 类进⾏重构,将打折⽅案逻辑(算法)的定义和使⽤分离。
    抽象策略类 AbstractDiscount,它是所有具体打折⽅案(算法)的⽗类,定义了⼀个 discount抽象⽅法
    package designpattern.strategy.now.discount;
    public abstract class AbstractDiscount {
      public double getFinalPrice() {
          return finalPrice;
      }
      public void setFinalPrice(double finalPrice) {
          this.finalPrice = finalPrice;
      }
      public String getDesc() {
          return desc;
      }
      public void setDesc(String desc) {
          this.desc = desc;
      }
      protected double finalPrice;
      protected String desc;
      public IDiscount(String desc) {
          this.desc = desc;
      }
      public abstract double discount(double price);
    }
    
    四种具体策略类,继承⾃抽象策略类 AbstractDiscount,并在 discount ⽅法中实现具体的打折⽅案(算法) ```java package designpattern.strategy.now.discount.impl;

import designpattern.strategy.now.discount.AbstractDiscount; public class Discount85 extends AbstractDiscount { public Discount85() { super(“该商品可享受8.5折优惠”); } @Override public double discount(double price) { finalPrice = price * 0.85; return finalPrice; } }

```java
package designpattern.strategy.now.discount.impl;

import designpattern.strategy.now.discount.AbstractDiscount;
public class Discount6 extends AbstractDiscount {
    public Discount6() {
        super("该商品可享受6折优惠");
    }
    @Override
    public double discount(double price) {
        finalPrice = price * 0.6;
        return finalPrice;
    }
}
package designpattern.strategy.now.discount.impl;

import designpattern.strategy.now.discount.AbstractDiscount;
public class Return5 extends AbstractDiscount {
    public Return5() {
        super("该商品可返现5元");
    }
    @Override
    public double discount(double price) {
        this.finalPrice = price >= 5 ? price - 5 : 0;
        return finalPrice;
    }
}
package designpattern.strategy.now.discount.impl;

import designpattern.strategy.now.discount.AbstractDiscount;
public class NoDiscount extends AbstractDiscount {
    public NoDiscount() {
        super("对不起,该商品不参与优惠活动");
    }
    @Override
    public double discount(double price) {
        finalPrice = price;
        return finalPrice;
    }
}

类 BuyGoods,维护了⼀个 AbstractDiscount 引用

package designpattern.strategy.now;

import designpattern.strategy.now.discount.AbstractDiscount;
import java.text.MessageFormat;
public class BuyGoods {
    private String goods;
    private double price;
    private AbstractDiscount abstractDiscount;
    public BuyGoods(String goods, double price, AbstractDiscount abstractDiscount) {
        this.goods = goods;
        this.price = price;
        this.abstractDiscount = abstractDiscount;
    }
    public double calculate() {
        double finalPrice = abstractDiscount.discount(this.price);
        String desc = abstractDiscount.getDesc();
        System.out.println(MessageFormat.format("商品:{0},原价:{1},{2},最终价格为:{3}", goods, price, desc, finalPrice));
        return finalPrice;
    }
}

1.2.4 测试

package designpattern.strategy.now;

import designpattern.strategy.now.discount.impl.*;
public class Test {
    public static void main(String[] args) {
        BuyGoods buyGoods1 = new BuyGoods("Java编程思想", 99.00, new
        Discount85());
        buyGoods1.calculate();
        BuyGoods buyGoods2 = new BuyGoods("罗技⿏标", 66, new Discount6());
        buyGoods2.calculate();
        BuyGoods buyGoods3 = new BuyGoods("苹果笔记本", 15000.00, new
        Return5());
        buyGoods3.calculate();
        BuyGoods buyGoods4 = new BuyGoods("佳能相机", 1900, new
        NoDiscount());
        buyGoods4.calculate();
    }
}

重构后:

  • 增加新的优惠⽅案时只需要继承抽象策略类即可,修改优惠⽅案时不需要修改BuyGoods类源码;
  • 代码复⽤也变得简单,直接复⽤某⼀个具体策略类即可;
  • BuyGoods类的calculate变得简洁,没有了原本的if分⽀

    2. 模板⽅法模式

    模板⽅法模式是指定义⼀个算法的⻣架,并允许⼦类为⼀个或者多个步骤提供实现。模板⽅法模式使得⼦类可以在不改变算法结构的情况下,重新定义算法的某些步骤,属于⾏为型设计模式。采⽤模板⽅法模式的核⼼思路是处理某个流程的代码已经具备,但其中某些节点的代码暂时不能确定。此时可以使⽤模板⽅法。

    2.1 示例

    ```java package com.lagou.edu; /**
  • ⾯试⼤⼚流程类 */ public abstract class Interview { private final void register() {
      System.out.println("⾯试登记");
    
    } protected abstract void communicate(); private final void notifyResult() {
      System.out.println("HR⼩姐姐通知⾯试结果");
    
    } protected final void process() {
      this.register();
      this.communicate();
      this.notifyResult();
    
    } } ```

    Java岗位⾯试者

    ```java package com.lagou.edu; /**
  • ⾯试⼈员1,它是来⾯试Java⼯程师的 */ public class Interviewee1 extends Interview{ public void communicate() {
      System.out.println("我是⾯试⼈员1,来⾯试Java⼯程师,我们聊的是Java相关内容");
    
    } } ```

    前端岗位⾯试者

    ```java package com.lagou.edu; /**
  • ⾯试⼈员2,它是来⾯试前端⼯程师的 */ public class Interviewee2 extends Interview{ public void communicate() {
      System.out.println("我是⾯试⼈员2,来⾯试前端⼯程师,我们聊的是前端相关内容");
    
    } } ```

    客户端测试类

    ```java package com.lagou.edu;

public class InterviewTest { public static void main(String[] args) { // ⾯试Java⼯程师 Interview interviewee1 = new Interviewee1(); interviewee1.process(); // ⾯试前端⼯程师 Interview interviewee2 = new Interviewee2(); interviewee2.process(); } }

<a name="gx9bq"></a>
#### 打印结果
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21859640/1639414129240-04bed294-ce84-4ab1-b03a-7ecfd03ace80.png#clientId=uf9e846b4-add3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=190&id=u4300dcab&margin=%5Bobject%20Object%5D&name=image.png&originHeight=190&originWidth=833&originalType=binary&ratio=1&rotation=0&showTitle=false&size=68376&status=done&style=none&taskId=u693d732e-8b2e-428a-92a5-b3625f85913&title=&width=833)
<a name="FSneG"></a>
## 3. 适配器模式
使得原本由于接⼝不兼容⽽不能⼀起⼯作、不能统⼀管理的那些类可以⼀起⼯作、可以进⾏统⼀管理
<a name="Evtxf"></a>
### 3.1 解决接⼝不兼容⽽不能⼀起⼯作问题,看下⾯⼀个⾮常经典的案例
在中国,⺠⽤电都是220v交流电,但是⼿机锂电池⽤的都是5v直流电。因此,我们给⼿机充电时就需要使⽤电源适配器来进⾏转换。使⽤代码还原这个⽣活场景
<a name="ixT2P"></a>
#### 创建AC220类,表示220v交流电
```java
package com.lagou.edu;

import com.sun.org.apache.bcel.internal.generic.RETURN;
public class AC220 {
    public int outputAC220V() {
        int output = 220;
        System.out.println("输出交流电" + output + "V");
        return output;
    }
}

创建DC5接⼝,表示5V直流电

package com.lagou.edu;
public interface DC5 {
    int outputDC5V();
}

创建电源适配器类 PowerAdapter

package com.lagou.edu;
public class PowerAdapter implements DC5 {
    private AC220 ac220;
    public PowerAdapter(AC220 ac220) {
        this.ac220 = ac220;
    }
    public int outputDC5V() {
        int adapterInput = ac220.outputAC220V();
        // 变压器...
        int adapterOutput = adapterInput/44;
        System.out.println("使⽤ PowerAdapter 输⼊AC:" + adapterInput + "V输出DC:" + adapterOutput + "V");
        return adapterOutput;
    }
}

客户端测试代码

package com.lagou.edu;
public class AdapterTest {
    public static void main(String[] args) {
        DC5 dc5 = new PowerAdapter(new AC220());
        dc5.outputDC5V();
    }
}

在上⾯的案例中,通过增加电源适配器类PowerAdapter实现了⼆者的兼容

3.2 解决不能统⼀管理的问题

SpringMVC中处理器适配器(HandlerAdapter)机制就是解决类统⼀管理问题⾮常经典的场景
其中 HandlerAdapter接⼝是处理器适配器的顶级接⼝,它有多个⼦类,包括AbstractHandlerMethodAdapter、SimpleServletHandlerAdapter、SimpleControllerHandlerAdapter、HttpRequestHandlerAdapter、RequestMappingHandlerAdapter

其适配器调⽤的关键代码也在DispatcherServlet的doDispatch()⽅法中
image.png

在 doDispatch() ⽅法中调⽤了 getHandlerAdapter() ⽅法
image.png

在 getHandlerAdapter() ⽅法中循环调⽤了 supports() ⽅法判断是否兼容,循环迭代集合中的“Adapter” 在初始化时已经赋值。