第4章 Web MVC 核心
Spring Boot2.0深度实践之核心技术篇
– 第4章 Web MVC 核心
理解 Spring Web MVC 架构
1. 基础架构 Servlet
- 特点
- 请求/响应式 (Request/Response)
- 屏蔽网络通讯的细节
- API 特性
- 面向 HTTP 协议
- 完整生命周期
- 职责
- 处理请求
- 资源管理(数据库连接、消息连接、其他)
- 视图渲染
2. 核心架构: 前端控制器(Front Controller)
- 资源:http://www.corej2eepatterns.com/FrontController.htm
- 实现:Spring Web MVC DispatcherServlet
- https://docs.spring.io/spring/docs/1.0.0/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html
3. Spring Web MVC 架构
https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/mvc.html#mvc-servlet
认识 Spring Web MVC
1. Spring Framework 时代的一般认识
- 实现 Controller
@Controller
public class HelloWorldController {
@RequestMapping("/")
public String index() {
// index.jsp
return "index";
}
}
- 配置 Web MVC 组件
webapp/WEB-INF/app-context.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">
<!-- 扫描-->
<context:component-scan base-package="com.imooc.web"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 部署 DispatcherServlet
webapp/WEB-INF/web.xml
<web-app>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dive-in-spring-boot</artifactId>
<groupId>com.imooc</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-webmvc</artifactId>
<packaging>war</packaging>
<dependencies>
<!-- Servlet 3.1 API 依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Spring Web MVC 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 使用可执行 Tomcat Maven 插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<id>tomcat-run</id>
<goals>
<goal>exec-war-only</goal>
</goals>
<phase>package</phase>
<configuration>
<!-- ServletContext path -->
<path>/</path>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Spring Framework 时代的重新认识
- Web MVC 核心组件
- 处理器(Handler)
- 映射 HandlerMapping
- 适配 HandlerAdapter
- 执行 HandlerExecutionChain
- 页面渲染(view)
- 视图解析 ViewResolver
- 国际化 LocaleResolver、LocaleContextResolver
- 个性化 ThemeResolver
- 异常处理
- 异常解析 HandlerExceptionResolver
交互流程
- Web MVC 注解驱动
- 版本依赖
- Spring Framework 3.1 +
基本配置步骤
- 注解配置 @Configuration
- 组件激活 @EnableWebMvc
- 自定义组件 WebMvcConfiguer
package com.imooc.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
// <!--<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
// <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
// <!--<property name="prefix" value="/WEB-INF/jsp/"/>-->
// <!--<property name="suffix" value=".jsp"/>-->
// <!--</bean>-->
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截中...");
return true;
}
});
}
}
常用注解
- 注册模型属性: @ModelAttribute
- 读取请求头: @RequestHeader
- 读取 Cookie: @CookieValue
- 校验参数: @Valid 、 @Validated
- 注解处理: @ExceptionHandler
- 切面通知: @ControllerAdvice
package com.imooc.web.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice(assignableTypes = HelloWorldController.class)
public class HelloWorldControllerAdvice {
@ModelAttribute("acceptLanguage")
public String acceptLanguage(@RequestHeader("Accept-Language") String acceptLanguage){
return acceptLanguage;
}
@ModelAttribute("jsessionId")
public String jsessionId(@CookieValue("JSESSIONID") String jsessionId){
return jsessionId;
}
@ModelAttribute("message")
public String message(){
return "Hello,World";
}
@ExceptionHandler(Throwable.class)
public ResponseEntity<String> onException(Throwable throwable) {
return ResponseEntity.ok(throwable.getMessage());
}
}
index.jsp
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<body>
<message>${message}</message>
<language>${acceptLanguage}</language>
<jsessionId>${jsessionId}</jsessionId>
</body>
</jsp:root>
- Web MVC 自动装配
- 版本依赖
- Spring Framework 3.1 +
- Servlet 3.0 +
4-11 ~ 4.12
简化 Spring Web MVC
4-13
Spring Boot 时代的简化
- 完全自动装配
4-14
- 装配条件
4-15
- 外部化配置
4-16
实践