SpringMVC是Spring子框架
SpringMVC是Spring 为【展现层|表示层|表述层|控制层】提供的基于 MVC 设计理念的优秀的 Web 框架,是目前最主流的MVC 框架。
SpringMVC是非侵入式:可以使用注解让普通java对象,作为请求处理器【Controller】。
SpringMVC是用来代替Servlet
Servlet作用
- 处理请求
- 将数据共享到域中
- 做出响应
- 跳转页面【视图】
web.xml
<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">
web-app>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.1version>
dependency>
<dependency>
<groupId>org.thymeleafgroupId>
<artifactId>thymeleaf-spring5artifactId>
<version>3.0.12.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
// src/main/webapp/WEB-INF/web.xml
<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">
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
中的pages
是可变的,代表的是WEB-INF文件下的文件名
// src/main/resources/springmvc.xml
<context:component-scan base-package="com.atguigu">context:component-scan>
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".html"/>
<property name="characterEncoding" value="UTF-8" />
bean>
property>
bean>
property>
bean>
demo演示:
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页title>
head>
<body>
<a th:href="@{/HelloController}">发送请求a>
body>
html>
package com.atguigu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller // 标识当前类是一个请求处理器类
public class HelloController {
/**
* 配置url【/】,会映射(跳转)到 WEB-INF/index.html
* @return
*/
@RequestMapping("/")
public String toIndex(){
// /WEB-INF/pages/index.html
// 物理视图名 = 视图前缀+逻辑视图名+视图后缀
// 物理视图名 = "/WEB-INF/pages/" + "index" + ".html"
return "index";
}
}
@RequestMapping注解作用:为指定的类或方法设置相应URL
注意:当类和类中方法都有
@RequestMapping
注解时,此时路径应为/类的RequestMapping路径/方法的RequestMapping路径
value属性
path属性
method属性
类型:RequestMethod[]
public enum RequestMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE }
作用:为当前URL【类或方法】设置请求方式【POST、DELETE、PUT、GET】
注意:
params
headers
示例代码
@RequestMapping(value = {"/saveEmp","/insertEmp"},
method = RequestMethod.GET,
params = "lastName=lisi",
headers = "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36")
public String saveEmp(){
System.out.println("添加员工信息!!!!");
return SUCCESS;
}
@RequestMapping(method = RequestMethod.POST) public @interface PostMapping {} @RequestMapping(method = RequestMethod.GET) public @interface GetMapping {} @RequestMapping(method = RequestMethod.PUT) public @interface PutMapping {} @RequestMapping(method = RequestMethod.DELETE) public @interface DeleteMapping {}
常用通配符
a) ?:匹配一个字符
b) *:匹配任意字符
c) **:匹配多层路径
示例代码
@RequestMapping("/testAnt/**")
public String testAnt(){
System.out.println("==>testAnt!!!");
return SUCCESS;
}
@Target(ElementType.PARAMETER)
获取URL中占位符参数
占位符语法:{}
示例代码
<a th:href="@{/EmpController/testPathVariable/1001}">测试PathVariable注解a><br>
/**
* testPathVariable
* @return
*/
@RequestMapping("/testPathVariable/{empId}")
public String testPathVariable(@PathVariable("empId") Integer empId){
System.out.println("empId = " + empId);
return SUCCESS;
}
传统风格CRUD
REST风格CRUD
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<h3>修改员工--PUT方式提交h3>
<form th:action="@{/emp}" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="修改员工信息">
form>
<h3>删除员工--DELETE方式提交h3>
<form th:action="@{/emp/1001}" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="删除员工信息">
form>
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter(requestToUse, response);
}
/**
* Simple {@link HttpServletRequest} wrapper that returns the supplied method for
* {@link HttpServletRequest#getMethod()}.
*/
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
}
使用Servlet处理请求数据
- 请求参数
- String param = request.getParameter();
- 请求头
- request.getHeader();
- Cookie
- request.getCookies();
<h2>测试SpringMVC处理请求数据h2>
<h3>处理请求参数h3>
<a th:href="@{/requestParam1(stuName='zs', stuAge=18)}">测试处理请求参数1a>
/**
* 获取请求参数
* @return
*/
@RequestMapping("/requestParam1")
public String requestParam1(String stuName,Integer stuAge){
System.out.println("stuName = "+ stuName);
System.out.println("stuAge = "+ stuAge);
return SUCCESS;
}
SpringMVC支持POJO入参
要求:请求参数名与POJO的属性名保持一致
示例代码
<form th:action="@{/saveEmp}" method="POST">
id:<input type="text" name="id"><br>
LastName:<input type="text" name="lastName"><br>
Email:<input type="text" name="email"><br>
Salary:<input type="text" name="salary"><br>
<input type="submit" value="添加员工信息">
form>
/**
* 获取请求参数POJO
* @return
*/
@RequestMapping(value = "/saveEmp",method = RequestMethod.POST)
public String saveEmp(Employee employee){
System.out.println("employee = " + employee);
return SUCCESS;
}
@RequestParam注解
作用:如请求参数与入参参数名不一致时,可以使用@RequestParam注解设置入参参数名
属性
示例代码
<h2>测试SpringMVC处理请求数据h2>
<h3>处理请求参数h3>
<a th:href="@{/requestParam1(sName='zs', stuAge=18)}">测试处理请求参数1a>
/**
* 获取请求参数
* @return
*/
@RequestMapping("/requestParam1")
public String requestParam1(@RequestParam(value = "sName",required = false,
defaultValue = "zhangsan")
String stuName,
Integer stuAge){
System.out.println("stuName = " + stuName);
System.out.println("stuAge = " + stuAge);
return SUCCESS;
}
语法:@RequestHeader注解
属性
示例代码
<a th:href="@{/testGetHeader}">测试获取请求头a>
/**
* 获取请求头
* @return
*/
@RequestMapping(value = "/testGetHeader")
public String testGetHeader(@RequestHeader("Accept-Language")String al,
@RequestHeader("Referer") String ref){
System.out.println("al = " + al);
System.out.println("ref = " + ref);
return SUCCESS;
}
语法:@CookieValue获取Cookie数值
属性
示例代码
<a th:href="@{/setCookie}">设置Cookie信息a><br>
<a th:href="@{/getCookie}">获取Cookie信息a><br>
/**
* 设置Cookie
* @return
*/
@RequestMapping("/setCookie")
public String setCookie(HttpSession session){
// Cookie cookie = new Cookie();
System.out.println("session.getId() = " + session.getId());
return SUCCESS;
}
/**
* 获取Cookie
* @return
*/
@RequestMapping("/getCookie")
public String getCookie(@CookieValue("JSESSIONID")String cookieValue){
System.out.println("cookieValue = " + cookieValue);
return SUCCESS;
}
@RequestMapping("/useRequestObject")
public String useRequestObject(HttpServletRequest request){}
语法:使用ModelAndView对象作为方法返回值类型,处理响应数据
ModelAndView是模型数据与视图对象的集成对象,源码如下
public class ModelAndView {
/** View instance or view name String. */
//view代表view对象或viewName【建议使用viewName】
@Nullable
private Object view;
/** Model Map. */
//ModelMap集成LinkedHashMap,存储数据
@Nullable
private ModelMap model;
/**
设置视图名称
*/
public void setViewName(@Nullable String viewName) {
this.view = viewName;
}
/**
* 获取视图名称
*/
@Nullable
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
}
/**
获取数据,返回Map【无序,model可以为null】
*/
@Nullable
protected Map<String, Object> getModelInternal() {
return this.model;
}
/**
* 获取数据,返回 ModelMap【有序】
*/
public ModelMap getModelMap() {
if (this.model == null) {
this.model = new ModelMap();
}
return this.model;
}
/**
* 获取数据,返回Map【无序】
*/
public Map<String, Object> getModel() {
return getModelMap();
}
/**
设置数据
*/
public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
getModelMap().addAttribute(attributeName, attributeValue);
return this;
}
}
底层实现原理
示例代码
<h2>测试SpringMVC处理响应数据h2>
<h3>1、测试响应数据--ModelAndViewh3>
<a th:href="@{/ResponseDataController/testModelAndView}">测试处理请求参数1a>
<br>
@Controller
@RequestMapping("/ResponseDataController")
public class ResponseDataController {
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mv = new ModelAndView();
// 设置数据
mv.addObject("stuName","lisi");
// 设置视图
mv.setViewName("response_success");
return mv;
}
}
<h2>响应数据--成功页面h2>
stuName:<span th:text="${stuName}">span>
语法:使用Model、ModelMap、Map作为方法入参,处理响应数据
示例代码
<h3>2、测试响应数据--ModelOrModelMapOrMaph3>
<a th:href="@{/ResponseDataController/testModelOrModelMapOrMap}">测试处理响应参数2a>
<br>
/**
* 使用Map、Model、ModelMap处理响应数据
* @return
*/
// @RequestMapping("/testModelOrModelMapOrMap")
// public String testModelOrModelMapOrMap(Map map){
设置数据--Map方式
// map.put("stuName","zhangsan");
//
// return "response_success";
// }
@RequestMapping("/testModelOrModelMapOrMap")
public String testModelOrModelMapOrMap(Model model){
// 设置数据--Model/ModelMap方式
model.addAttribute("stuName","wangwu");
return "response_success";
}
<h2>响应数据--成功页面h2>
stuName:<span th:text="${stuName}">span>
底层实现原理
SpringMVC封装数据,默认使用request域对象
session域的使用
方式一
/**
* 测试响应数据【其他域对象】
* @return
*/
@GetMapping("/testScopeResponsedata")
public String testScopeResponsedata(HttpSession session){
session.setAttribute("stuName","xinlai");
return "response_success";
}
方式二
@Controller
@SessionAttributes(value = "stuName") //将request域中数据,同步到session域中
public class TestResponseData {
@RequestMapping("/testSession")
public String testSession( Map<String, Object> map ){
// 设置数据--数据在Session域
map.put("stuName","sunqi");
return "response_success";
}
}
JavaWeb解决乱码:三行代码
public class CharacterEncodingFilter extends OncePerRequestFilter {
//需要设置字符集
@Nullable
private String encoding;
//true:处理请乱码
private boolean forceRequestEncoding = false;
//true:处理响应乱码
private boolean forceResponseEncoding = false;
public String getEncoding() {
return this.encoding;
}
public boolean isForceRequestEncoding() {
return this.forceRequestEncoding;
}
public void setForceResponseEncoding(boolean forceResponseEncoding) {
this.forceResponseEncoding = forceResponseEncoding;
}
public void setForceEncoding(boolean forceEncoding) {
// 合并了forceRequestEncoding和forceResponseEncoding
this.forceRequestEncoding = forceEncoding;
this.forceResponseEncoding = forceEncoding;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 字符集
String encoding = getEncoding();
if (encoding != null) {
if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
// 解决请求乱码
request.setCharacterEncoding(encoding);
}
if (isForceResponseEncoding()) {
// 解决响应乱码
response.setCharacterEncoding(encoding);
}
}
filterChain.doFilter(request, response);
}
}
SpringMVC底层默认处理响应乱码
SpringMVC处理请求乱码步骤
示例代码
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
概述:SpringMVC中所有的视图解析器对象均实现了ViewResolver接口
作用:使用ViewResolver,将View从ModelAndView中解析出来
无论方法返回是ModelAndView还是String,最终SpringMVC底层,均会封装为ModelAndView对象
//DispatcherServlet的1061行代码
ModelAndView mv = null;
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
SpringMVC解析mv【ModelAndView】
//DispatcherServlet的1078行代码
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
ThymeleafView对象中344行代码【SpringMVC底层处理响应乱码】
//computedContentType="text/html;charset=UTF-8"
response.setContentType(computedContentType);
WebEngineContext对象中783行代码【SpringMVC底层将数据默认共享到request域】
this.request.setAttribute(name, value);
视图解析器将View从ModelAndView中解析出来
ThymeleafViewResolver的837行代码
//底层使用反射的方式,newInstance()创建视图对象
final AbstractThymeleafView viewInstance = BeanUtils.instantiateClass(getViewClass());
<mvc:view-controller path="/" view-name="index">mvc:view-controller>
<mvc:view-controller path="/toRestPage" view-name="rest_page">mvc:view-controller>
<mvc:view-controller path="/toRequestDataPage" view-name="toRequestDataPage">mvc:view-controller>
<mvc:view-controller path="/toResponseDataPage" view-name="toResponseDataPage">mvc:view-controller>
<mvc:annotation-driven>mvc:annotation-driven>
return "redirect: / xxx.html";
由DefaultServlet加载静态资源到服务器
<servlet>
<servlet-name>defaultservlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServletservlet-class>
<init-param>
<param-name>debugparam-name>
<param-value>0param-value>
init-param>
<init-param>
<param-name>listingsparam-name>
<param-value>falseparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
发现问题
解决方案
<mvc:default-servlet-handler>mvc:default-servlet-handler>
<mvc:annotation-driven>mvc:annotation-driven>
创建RedirectView对象【ThymeleafViewResolver的775行代码】
// Process redirects (HTTP redirects)
if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length(), viewName.length());
final RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
return (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, REDIRECT_URL_PREFIX);
}
RedirectView视图渲染