技術共有

春のMVC学習

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

第4章 Spring MVC

セクション 1 Spring MVC の概要

1. スプリングMVC

SpringMVC は Java オープン ソース フレームワークであり、Spring Framework エコシステムの独立したモジュールであり、Spring に基づいた Web MVC (データ、ビジネス、プレゼンテーション) 設計パターンのリクエスト駆動型の軽量 Web フレームワークを実装しています。利便性。

2. Spring MVC コアコンポーネント

  • DispatcherServlet フロント コントローラー

    リクエストの受信と配信を担当します

  • ハンドラプロセッサ

    プロセッサにはインターセプタやコントローラ内のメソッドなどが含まれており、主にリクエストの処理を担当します。

  • HandlerMapping プロセッサ マッパー

    構成ファイルを解析し、注釈をスキャンし、リクエストをプロセッサに照合します。

  • HandlerAdpter ハンドラーアダプター

    リクエストに基づいて一致するプロセッサを見つけるこのプロセスはアダプテーションと呼ばれます。

  • ViewResolver ビューリゾルバー

    プロセッサが実行された後に得られる結果はビューになる場合がありますが、このビューは論理ビュー(ページ内にループや判定などのロジックコードが存在します)であり、ビューリゾルバーを使用して処理する必要があります。ビューのレンダリングと呼ばれます。

セクション 2 Spring MVC の開発と進化

<!--低版本-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

1. Bean 名または ID が URL リクエストと一致する

1.1 web.xml の設定
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <!--配置Servlet初始化参数-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!--前置控制器要接收所有的请求,因此在容器启动的时候就应该完成初始化-->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
1.2 spring-mvc.xml の設定
<!--视图解析器:在控制器返回视图的时候生效-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--视图资源的前缀-->
    <property name="prefix" value="/" />
    <!--视图资源的后缀-->
    <property name="suffix" value=".jsp" />
</bean>
<!--处理器映射的方式:使用bean的名字或者id的值来与请求匹配-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
1.3 コントローラーの作成
public class UserController extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //这里使用配置的视图解析器进行解析  user => / + user + .jsp => /user.jsp
        return new ModelAndView("user");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
1.4 コントローラーの設定
<!--通过id值匹配请求的URL-->
<bean id="/view" class="com.qf.spring.mvc.controller.UserController" />
  • 1
  • 2

考え方: このリクエストのマッチング方法では、各リクエストに対応するコントローラーが必要になるため、大量のコントローラーを作成することになり、開発効率が非常に低くなります。

Spring 提供了方法名来匹配请求来解决这个问题
  • 1

2. Bean のメソッド名がリクエストと一致する

2.1 メソッド名パーサー

Spring は、コントローラー内のメソッド名のリゾルバーである InternalPathMethodNameResolver を提供します。このリゾルバーの機能は、URL リクエストを照合するための基礎としてメソッド名を使用し、それをコントローラーに関連付けることです。

2.2 マルチオペレーションコントローラ

Spring は、他のコントローラー クラスが継承する MultiActionController コントローラー クラスを提供し、開発者はリクエストを処理するための複数のメソッドを記述し、メソッド名パーサーを使用してリクエストを照合できます。

2.3 コントローラーの作成
public class UserMultiController extends MultiActionController {
    //这个方法就匹配 /login 请求
    //请求格式必须是 
    //ModelAndView 方法名(HttpServletRequest req, HttpServletResponse resp){}
    public ModelAndView login(HttpServletRequest req, HttpServletResponse resp){
        return new ModelAndView("login");
    }

    //这个方法就匹配 /register 请求
    public ModelAndView register(HttpServletRequest req, HttpServletResponse resp){
        return new ModelAndView("register");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
2.4 spring-mvc.xml の設定
 <!--方法名解析器-->
<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver" />
<!-- /login 请求使用该bean对象处理-->
<bean id="/login" class="com.qf.spring.mvc.controller.UserMultiController">
    <property name="methodNameResolver" ref="methodNameResolver" />
</bean>
<!-- /register 请求使用该bean对象处理-->
<bean id="/register" class="com.qf.spring.mvc.controller.UserMultiController">
    <property name="methodNameResolver" ref="methodNameResolver" />
</bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

考え方: このリクエストのマッチング方法によると、コントローラーが複数のリクエストを処理する必要がある場合、大量の構成情報が発生し、後で保守することが困難になる問題が発生します。

Spring 提供了 SimpleUrlHandlerMapping 映射器, 该映射器支持一个控制器与多个请求匹配的同时也解决了配置信息繁多的问题。
  • 1

3. 単純な URL ハンドラー マッピング

SimpleUrlHandlerMapping を使用するには、spring-mvc.xml 構成を変更するだけです。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--视图解析器:在控制器返回视图的时候生效-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图资源的前缀-->
        <property name="prefix" value="/" />
        <!--视图资源的后缀-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--处理器映射的方式:使用bean的名字或者id的值来与请求匹配-->
<!--    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->
    <!--通过id值匹配请求的URL-->
<!--    <bean id="/view" class="com.qf.spring.mvc.controller.UserController" />-->
    <!--方法名解析器-->
<!--    <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver" />-->
    <!-- /login 请求使用该bean对象处理-->
<!--    <bean id="/login" class="com.qf.spring.mvc.controller.UserMultiController">-->
<!--        <property name="methodNameResolver" ref="methodNameResolver" />-->
<!--    </bean>-->
    <!-- /register 请求使用该bean对象处理-->
<!--    <bean id="/register" class="com.qf.spring.mvc.controller.UserMultiController">-->
<!--        <property name="methodNameResolver" ref="methodNameResolver" />-->
<!--    </bean>-->
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/view">userController</prop>
                <prop key="/user/*">userMultiController</prop>
            </props>
        </property>
    </bean>
    <bean id="userController" class="com.qf.spring.mvc.controller.UserController" />
    <bean id="userMultiController" class="com.qf.spring.mvc.controller.UserMultiController" />
</beans>
  • 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

考え方: プロジェクトの開発が進むにつれて、より多くのビジネス機能が開発され、コントローラーの数も増加し、リクエストの一致の数も増加します。これにより、後からのメンテナンスが困難になる問題も発生します。 ?

Spring 提供了 DefaultAnnotationHandlerMapping 映射器,支持使用注解来匹配请求,这样就解决了请求匹配导致配置信息繁多的问题,同时还提升了开发效率。
  • 1

4. 一致するリクエストに注釈を付ける

4.1 コントローラーの作成
@Controller
public class UserAnnotationController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(){
        return "register";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
4.2 spring-mvc.xml の設定
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--视图解析器:在控制器返回视图的时候生效-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图资源的前缀-->
        <property name="prefix" value="/" />
        <!--视图资源的后缀-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--处理器映射的方式:使用bean的名字或者id的值来与请求匹配-->
<!--    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->
    <!--通过id值匹配请求的URL-->
<!--    <bean id="/view" class="com.qf.spring.mvc.controller.UserController" />-->
    <!--方法名解析器-->
<!--    <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver" />-->
    <!-- /login 请求使用该bean对象处理-->
<!--    <bean id="/login" class="com.qf.spring.mvc.controller.UserMultiController">-->
<!--        <property name="methodNameResolver" ref="methodNameResolver" />-->
<!--    </bean>-->
    <!-- /register 请求使用该bean对象处理-->
<!--    <bean id="/register" class="com.qf.spring.mvc.controller.UserMultiController">-->
<!--        <property name="methodNameResolver" ref="methodNameResolver" />-->
<!--    </bean>-->
    <!--<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/view">userController</prop>
                <prop key="/login">userMultiController</prop>
                <prop key="/register">userMultiController</prop>
            </props>
        </property>
    </bean>
    <bean id="userController" class="com.qf.spring.mvc.controller.UserController" />
    <bean id="userMultiController" class="com.qf.spring.mvc.controller.UserMultiController" />-->
    <!--类上的注解处理器-->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <!--方法上的注解处理器-->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <!--扫描包,使得该包下类以及类中定义的方法上所使用的注解生效-->
    <context:component-scan base-package="com.qf.spring.mvc.controller" />
</beans>
  • 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

5. 新しいバージョンの構成

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--视图解析器:在控制器返回视图的时候生效-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图资源的前缀-->
        <property name="prefix" value="/" />
        <!--视图资源的后缀-->
        <property name="suffix" value=".jsp" />
    </bean>
    <!--较新的版本使用该标签开启注解支持-->
    <mvc:annotation-driven />
    <!--扫描包,使得该包下类以及类中定义的方法上所使用的注解生效-->
    <context:component-scan base-package="com.qf.spring.mvc.controller" />
</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

セクション 3 Spring MVC の共通アノテーション

1. @コントローラー

このアノテーションはコントローラの識別子です

@Controller
public class UserController{
    
}
  • 1
  • 2
  • 3
  • 4

2. @リクエストマッピング

このアノテーションはリクエストを照合するために使用されます

@Controller
@RequestMapping("/user")
public class UserController{
    
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public int login(){
        return 1;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3. @リクエストボディ

このアノテーションはメソッドのパラメーターにのみ適用でき、リクエスト本文からデータを取得してパラメーターに挿入するために使用されます。

@Controller
@RequestMapping("/user")
public class UserController{
    
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public int login(@RequestBody User user){
        return 1;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4. @レスポンスボディ

このアノテーションは、データをページに渡すために使用されます。

@Controller
@RequestMapping("/user")
public class UserController{
    
    @RequestMapping(value="/login", method=RequestMethod.POST)
    @ResponseBody
    public int login(@RequestBody User user){
        return 1;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5. @リクエストパラメータ

このアノテーションはメソッドのパラメータにのみ適用でき、リクエスト ヘッダーからデータを取得してパラメータに挿入するために使用されます。

@Controller
@RequestMapping("/user")
public class UserController{
    
    @RequestMapping(value="/search", method=RequestMethod.GET)
    @ResponseBody
    public List<User> searchUsers(@RequestParam(value="name") String name){
        return new ArrayList<>();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

6. @パス変数

このアノテーションはメソッドのパラメータにのみ適用でき、リクエスト パスからデータを取得してパラメータに挿入するために使用されます。

@Controller
@RequestMapping("/user")
public class UserController{
    // /user/admin
    @RequestMapping(value="/{username}", method=RequestMethod.GET)
    @ResponseBody
    public User queryUser(@PathVariable("username") String username){
        return new User();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

7. @SessionAttributes[重要ではありません]

このアノテーションはクラス定義でのみ使用でき、セッションに入力を入れるために使用されます。

@SessionAttributes(types=User.class) //会将model中所有类型为 User的属性添加到会话中。
@SessionAttributes(value={“user1”, “user2”}) //会将model中属性名为user1和user2的属性添加到会话中。
@SessionAttributes(types={User.class, Dept.class}) //会将model中所有类型为 User和Dept的属性添加到会话中。
@SessionAttributes(value={“user1”,“user2”},types={Dept.class}) //会将model中属性名为user1和user2以及类型为Dept的属性添加到会话中。
  • 1
  • 2
  • 3
  • 4

8. @リクエストヘッダー

このアノテーションはメソッドのパラメータにのみ適用でき、リクエスト ヘッダーからデータを取得するために使用されます。

@RequestMapping("/find")  
public void findUsers(@RequestHeader("Content-Type") String contentType) {//从请求头中获取Content-Type的值
}  
  • 1
  • 2
  • 3

9. @Cookie値

このアノテーションはメソッドのパラメータにのみ適用でき、リクエストから Cookie 値を取得するために使用されます。

@RequestMapping("/find")  
public void findUsers(@CookieValue("JSESSIONID") String jsessionId) {//从请cookie中获取jsessionId的值
}  
  • 1
  • 2
  • 3

10. @コントローラーアドバイス

このアノテーションはクラスにのみ適用でき、このクラスが例外を処理するコントローラーであることを示します。

/**
 * 异常处理的控制器
 */
@ControllerAdvice //这个注解就是spring mvc提供出来做全局异常统一处理的
public class ExceptionController {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

11. @例外ハンドラ

このアノテーションは、例外を処理するために @ControllerAdvice または @RestControllerAdvice によって識別されるクラスのメソッドにのみ適用できます。

/**
 * 异常处理的控制器
 */
@ControllerAdvice //这个注解就是spring mvc提供出来做全局异常统一处理的
public class ExceptionController {

    @ExceptionHandler //异常处理器
    @ResponseBody //响应至页面
    public String handleException(Exception e){
        return e.getMessage();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

セクション4 JSR-303

1. JSR-303の概要

JSR は Java Specific Requests の略で、Java 仕様の提案を表します。 JSR-303 は、Java Bean データの有効性検証のために Java によって提供される標準フレームワークであり、メンバー変数および属性メソッドに注釈を付けることができる一連の検証注釈を定義します。 Hibernate Validator は、この標準の実装を提供します。

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.0.1.Final</version>
  <!-- 最新7.0.1.Final -->
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2. 検証の注釈

注釈説明する注釈説明する
@ヌルnull でなければなりません@NotNullnull にすることはできません
@アサートTrue本当でなければなりません@アサート偽偽でなければなりません
@ミン値が指定された最小値以上の数値である必要があります@マックス値が指定された最大値以下の数値である必要があります
@小数点値が指定された最小値以上の数値である必要があります10進数値が指定された最大値以下の数値である必要があります
@サイズセットの長さ@数字数値である必要があり、その値は許容範囲内である必要があります
@過去過去の日付である必要があります@未来将来の日付である必要があります
@パターン正規表現と一致する必要があります@Eメール電子メール形式である必要があります
@長さ(最小=,最大=)文字列のサイズは指定された範囲内である必要があります@空ではないnull は使用できません。長さは 0 より大きくなります。
@範囲(最小=,最大=,メッセージ=)要素は適切なスコープ内にある必要があります空白ではありませんnull は使用できません。文字列の長さは 0 より大きくなります (文字列に限定されます)。

3. アプリケーション

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.3.10</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.10</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.1.Final</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
  • 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
<!-- web.xml -->
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

    <mvc:annotation-driven>
        <mvc:message-converters>
            <!--处理字符串的消息转换器-->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <!--处理JSON格式的消息转换器-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.qf.spring.controller" />
</beans>
  • 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
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotNull;

public class User {

    @NotNull(message = "账号不能为空")
    @Length(min = 8, max = 15, message = "账号长度必须为8~15位")
    private String username;

    @NotNull(message = "密码不能为空")
    @Length(min = 8, max = 20, message = "密码长度必须为8~20位")
    private String password;

    @Range(min = 0, max = 120, message = "年龄只能在0~120岁之间")
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/add")
    @ResponseBody
    public Object saveUser(@Valid User user, BindingResult result){
        if(result.hasErrors()) return result.getAllErrors();
        return 1;
    }
}
  • 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

セクション 5 安静

1. RESTFUL の概要

RESTの正式名称は、 表現状態転送、急行 表現状態の転送

RESTFUL には次のような特徴があります。

  • 各 URI はリソースを表します
  • クライアントは、GET、POST、PUT、および DELETE を使用してサーバー リソースを操作します。GET はリソースの取得に使用され、POST は新しいリソースの作成に使用されます (リソースの更新にも使用できます)。PUT はリソースの更新に使用され、DELETE はリソースの更新に使用されます。リソースを削除するために使用されます

2.RESTFULリクエスト

/user GET => 获取用户资源
/user POST => 增加用户资源
/user PUT => 修改用户资源
/user DELETE => 删除用户资源

/user/{username} GET => 获取指定用户资源  这是RESTFUL风格中子资源的表述方式
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. Spring の RESTFUL のサポート

3.1 @レストコントローラ

このアノテーションはクラスにのみ適用でき、@Controller アノテーションと @ResponseBody アノテーションの組み合わせと同等です。このクラスのすべてのメソッドが実行された後に返される結果がページに直接出力されることを示します。

3.2 @GetMapping
3.2 @ポストマッピング
3.2 @PutMapping
3.2 @削除マッピング

セクション 6 静的リソースの処理

1. 静的リソースにアクセスできない理由

静的リソースには、html、js、css、画像、フォント ファイルなどが含まれます。静的ファイルには URL パターンがないため、デフォルトではアクセスできません。これにアクセスできる理由は、tomcat にグローバル サーブレット org.apache.catalina.servlets.DefaultServlet があるためです。その URL パターンは「/」であるため、プロジェクト内で一致しない静的リソース リクエストはすべてこのサーブレットで処理されます。ただし、SpringMVC では、DispatcherServlet も URL パターンとして「/」を使用するため、グローバル Serlvet がプロジェクトで使用されなくなり、静的リソースにアクセスできなくなります。

2. 解決策

2.1 オプション 1

DispathcerServlet に対応する URL パターンを「/」以外の一致するパターンに変更するだけです。たとえば、*.do、*.action。この変更後は、リクエストを送信するときに、リクエスト URL が .do または .action と一致する必要があります。

2.2 オプション 2
<!-- web.xml -->
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
  </servlet-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
2.2 オプション 3
<!-- spring-mvc.xml -->
<!-- 
这个handler就是处理静态资源的,它的处理方式就是将请求转会到tomcat中名为default的Servlet 
-->
<mvc:default-servlet-handler/>
<!-- mapping是访问路径,location是静态资源存放的路径 -->
<mvc:resources mapping="/static/**" location="/static/" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

第7章 中国語文字化け処理

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <!--字符编码过滤器-->
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <!--编码格式-->
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <!--强制编码-->
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
  • 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

セクション 8 Spring MVC の動作原理

checkMultipart(request); //检测是否是多部分请求,这个只可能在文件上传的时候为真


getHandler(processedRequest); //获取处理器 => 遍历HandlerMapping,找到匹配当前请求的执行器链
//没有找到执行器链 就直接向页面报一个404
noHandlerFound(processedRequest, response);
//找到处理当前请求的适配器
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

//控制器之前执行的拦截器将先执行,如果拦截器不通过,则方法直接结束
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
    return;
}
//控制器处理请求,可能会得到一个ModelAndView
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

//控制器之后的拦截器执行
mappedHandler.applyPostHandle(processedRequest, response, mv);
//处理分发的结果:这个结果就是控制器处理后的结果
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
//拦截器在控制器给出的结果DispatcherServlet处理后执行
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22