目录
我们tomcat当中配置的上下文路径为 /springMVC
注意的是::这里的请求路径就变成了初始信息加上具体信息,因为一个界面你得先访问到初始界面,才能进入具体界面的展示。
三.SpringMVC获取请求参数 springMVC-HttpservletRequest
3.请求参数与控制器形参之间的映射@RequestParam
4.@RequestHeader将请求头信息和控制器方法的形参创建映射关系
2.使用ModelAndView向request域对象共享数据
4.将我们的webConfig和SpringConfig创建出来
一。我的第一个helloword程序
1.首先导入jar包依赖
注意,打包方式使用war的方式,因为是web工程
<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
2.配置web.xml文件
<?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">
<!--注册前端控制器DispatcherServlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springmvc配置文件的位置和名称-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!--作为框架的核心组件,在启动过程中有大量的初始化操作要做
而这些操作放在第一次请求时才执行会严重影响访问速度
因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!--设置springMVC的核心控制器所能处理的请求的请求路径
/所匹配的请求可以是/login或.html或.js或.css方式的请求路径
但是/不能匹配.jsp请求路径的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.springmvc.xml配置
这里要注意的是,我们要引入命名空间
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
<!--开启组件扫描-->
<context:component-scan base-package="com.xsh.mvc.controller"/>
<!-- 让Spring MVC不处理静态资源 .css .js .html .mp3-->
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<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/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
</beans>
4.创建请求控制器类 HelloController
@RequestMapping注解:处理请求和控制器方法之间的映射关系
@RequestMapping注解的value属性可以通过请求地址匹配请求,/表示的当前工程的上下文路径
localhost:8080/springMVC/
package com.xsh.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//这个我们使用的是注解配置,引入spring.依赖,然后在spring.xml文件当中
//引入命名空间,配置扫描组件的包就可以使用
@Controller
public class HelloController {
//这个是配置首页的
@RequestMapping("/")//访问路径只有上下文路径的时候,我们返回视图名称,然后通过视图加载器配置访问路径
public String index(){
String s = "index";
return s;
}
//这个是配置超链接访问的
@RequestMapping("/target")
public String toTarget(){
return "target";
}
}
注意: 这里要注意,因为前面springmvc.xml当中配置的视图解析器当中前缀路径是“/WEB-INF/templates/”,所以我们需要将html页面创建在WEB-INF下的templates包当中
5.配置index.html展示页面
这里有个中重点::超链接里面的路径我们需要加上下文路径,而上下文路径如果改了的话,我们很多html页面当中配置的都需要更改,所以我们使用 <a th:href="@{/target}">,这里可以直接写我们的绝对路径,th在我们点击请求的时候,会帮我们加上 上下文路径
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>这个是首页</h1>
<a th:href="@{/target}">跳转欢迎页面</a>
<!--这里我们加上 th: 就可以直接通过@{}来写绝对路径,就可以不用加上下文路径了
使用th: 需要在前面加上xmlns:th="http://www.thymeleaf.org"-->
</body>
</html>
6.配置超链接跳转页面target.xml
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>这个是target页面 Hello word</h2>
</body>
</html>
总结::
我们tomcat当中配置的上下文路径为 /springMVC
浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器DispatcherServlet处理。前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应页面
二.RequestMapper属性
1. 注解功能:
从注解名称上我们可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求。
2.注解的位置:
@RequestMapping标识一个类:设置映射请求的请求路径的初始信息
@RequestMapping标识一个方法:设置映射请求请求路径的具体信息
@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
return "success";
}
}
注意的是::这里的请求路径就变成了初始信息加上具体信息,因为一个界面你得先访问到初始界面,才能进入具体界面的展示。
3.注解的value属性
@RequestMapping注解的value属性通过请求的请求地址匹配请求映射
@RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求
@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射
```html
<a th:href="@{/testRequestMapping}">测试@RequestMapping的value属性-->/testRequestMapping</a><br>
<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>
```
```java
@RequestMapping(
value = {"/testRequestMapping", "/test"}
)
public String testRequestMapping(){
return "success";
}
```
这里可以看到的是,这个界面可以通过两个地址去访问。这个就是value属性,还可以更多。
4.注解的请求方式 mothod
@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求
若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错405:Request method 'POST' not supported
```html
<a th:href="@{/method}">测试RequestMapper注解的method属性---get请求方式</a><br>
<form th:action="@{/method}" method="post">
<input type="submit" value="测试RequestMapper注解的method属性---post请求方式">
</form>
```java
@RequestMapping(value = "/method",
method = {RequestMethod.GET,RequestMethod.POST}
)
//如果method只填写一个的话,那就只能访问哪一个
public String testMethod(){
return "method";
}
注意:
1、对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解
处理get请求的映射-->@GetMapping
处理post请求的映射-->@PostMapping
处理put请求的映射-->@PutMapping
处理delete请求的映射-->@DeleteMapping
2、常用的请求方式有get,post,put,delete
但是目前浏览器只支持get和post,若在form表单提交时,为method设置了其他请求方式的字符串(put或delete),则按照默认的请求方式get处理
5.注解的params属性(了解)
@RequestMapping注解的params属性通过请求的请求参数匹配请求映射
@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系
"param":要求请求映射所匹配的请求必须携带param请求参数
"!param":要求请求映射所匹配的请求必须不能携带param请求参数
"param=value":要求请求映射所匹配的请求必须携带param请求参数且param=value
"param!=value":要求请求映射所匹配的请求必须携带param请求参数但是param!=value
```html
<a th:href="@{/test(username='admin',password=123456)">
测试@RequestMapping的params属性>/test</a><br>
```
```java
@RequestMapping(
value = {"/testRequestMapping", "/test"}
,method = {RequestMethod.GET, RequestMethod.POST}
,params = {"username","password!=123456"}
)
public String testRequestMapping(){
return "success";
}
注意的是:这里请求参数当中我们使用()进行传参,它最后的是上下文路径/test?username=admit,password=123456 ,和我们直接使用 ?+所要传的参数 这两种方式是一样的。
6.SpringMVC支持ant风格的路径
?:表示任意的单个字符
*:表示任意的0个或多个字符
\**:表示任意的一层或多层目录 ,注意:在使用\**时,只能使用/**/xxx的方式
7.SpringMVC支持路径中的占位符(重点)
原始方式:/deleteUser?id=1
rest方式:/deleteUser/1
SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参
例子:
```html
<a th:href="@{/testRest/1/admin}">测试路径中的占位符-->/testRest</a><br>
```
```java
@RequestMapping("/testRest/{id}/{username}")
public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){
System.out.println("id:"+id+",username:"+username);
return "success";
}
//最终输出的内容为-->id:1,username:admin
```
三.SpringMVC获取请求参数 springMVC-HttpservletRequest
1.通过ServletAPI获取
将HttpServletRequest作为控制器方法的形参,此时HttpServletRequest类型的参数表示封装了当前请求的请求报文的对象
···html
<a th:href="@{/servletAPI(username='xsh',password=20011128)}">
测试使用servletAPI获取请求参数 </a>
```java
@RequestMapping("/servletAPI")
public String testParam(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:"+username+",password:"+password);
return "success";
}
```
2.通过控制器的形参获取参数
若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串数组或者字符串类型的形参接收此请求参数
* 若使用字符串数组类型的形参,此参数的数组中包含了每一个数据
*若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果
***xml
<form th:action="@{/testParam}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
爱好:<input type="checkbox" name="hobby" value="a">a
<input type="checkbox" name="hobby" value="b">b
<input type="checkbox" name="hobby" value="c">c<br>
<input type="submit" value="测试使用控制器形参获取参数">
</form>
***java
//使用控制器形参获取参数
@RequestMapping("/testParam")
public String testparam(String username,String password,String[] hobby){ //记住这里的参数名要和你提交表单当中的参数名一致
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobby));
return "test_param";
}
值得注意的是,你形参要和你提交表单当中的name名字一致才能获取到,否则为空
3.请求参数与控制器形参之间的映射@RequestParam
@RequestParam有三个属性
***:value:指定为形参赋值的请求参数的参数名
***:required:设置是否必须传输此请求参数,默认值为true
若设置为true时,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置defaultValue属性,则页面报错400:Required String parameter 'xxx' is not present;若设置为false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为null
***:deaultValue:不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值
***xml
<a th:href="@{/testRequestParam(user_name='xsh',password=123456)}">
测试请求参数与形参不一样</a>
***java
//测试请求参数与形参不一样
@RequestMapping("/testRequestParam")
public String testRequestParam(
@RequestParam(value = "user_name",required = false,defaultValue = "heheh")String
username,
String password){
//上面@RequestParam的设定是将请求参数user_name的值赋给username,
//user_name不是必须要传入的数据,如果没有传入值,就赋值"heheh"
System.out.println(username+"***"+password);
return "test_param";
}
4.@RequestHeader将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
5.@CookieValue将cookie数据和控制器方法的形参创建映射关系
注解一样三个属性,和@RequestPrama用法相同
6.使用pojo类获取请求参数
可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值
```html
<form th:action="@{/testpojo}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
性别:<input type="radio" name="sex" value="男">男<input type="radio" name="sex" value="女">女<br>
年龄:<input type="text" name="age"><br>
邮箱:<input type="text" name="email"><br>
<input type="submit">
</form>
```
```java
@RequestMapping("/testpojo")
public String testPOJO(User user){
System.out.println(user);
return "success";
}
最终结果-->User{id=null, username='张三', password='123', age=23, sex='男', email='123@qq.com'}
7、解决获取请求参数的乱码问题
解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是必须在web.xml中进行注册
这个是过滤器源码当中的encoding赋值条件。
web.xml文件当中的配置
<!--过滤器CharacterEncodingFilter配置乱码问题-->
<filter>
<filter-name>CharacterEncodingFilter</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>
<!--配置响应报文乱码,响应的只要设置为true,就会把前面我们配置的encoding值配置给响应体-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
四.域对象共享数据
1.使用servletAPI向request域当中传入数据
、、、html(index)
<a th:href="@{/testRequestServletAPI}">使用servletAPI向我们request域当中传输数据</a><br>
、、、java
@RequestMapping("/testRequestServletAPI")
public String testRequestServletAPI(HttpServletRequest request) {
//使用servletAPI向request域当中传输数据
request.setAttribute("testRequestScope", "hello testRequestServletAPI!");
return "success";
}
、、、html(success)
<h2>测试显示</h2><br>
<p th:text="${testRequestScope}"></p><br>
2.使用ModelAndView向request域对象共享数据
取数据的方法和servletApi当中的方法一致
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
//使用ModelAndView向request域当中共享数据
/**
* ModelAndView有Model和View的功能
* Model主要用于向请求域共享数据
* View主要用于设置视图,实现页面跳转
*/
ModelAndView modelAndView = new ModelAndView();
//Model向域当中存数据
modelAndView.addObject("testRequestScope", "hello testModelAndView");
//设置视图名称,实现页面跳转
modelAndView.setViewName("success");
return modelAndView;
}
注意:: 如果使用的是ModelAndView方法,返回值就一定得是ModelAndView。
3.使用Model向request域当中共享数据
@RequestMapping("/testModel")
public String testModel(Model model) {
//使用Model向域当中共享数据
model.addAttribute("testRequestScope", "Hello testModel");
return "success";
}
4.使用Map集合向request域当中共享数据
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map) {
//使用map集合向域当中传输数据
map.put("testRequestScope","hello testmap");
return "success";
}
5.使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
//使用ModelMap向域当中传输数据
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testRequestScope","hello testModelMap");
return "success";
}
6、Model、ModelMap、Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
7、向session域共享数据
、、、java
@RequestMapping("/testSession")
public String testSession(HttpSession session){
//向session域当中传输数据
session.setAttribute("testsessionscope","hello testsession");
return "success";
}
、、、html(success)调取域共享数据
<p th:text="${session.testsessionscope}"></p>
8、向application域共享数据
、、、java
@RequestMapping("/testApplication")
public String testapplication(HttpSession session){
//向application域当中传输数据
ServletContext application = session.getServletContext();
application.setAttribute("testapplicationscope","hello testapplication");
return "success";
}
、、、html(success)调取域共享数据
<p th:text="${application.testapplicationscope}"></p>
五、springMVC中的视图
案例也在前面Domain当中
1、ThymeleafView
当控制器方法中所设置的视图名称没有任何前缀时(就是返回的值没有前缀),此时的视图名称会被SpringMVC配置文件中所配置的视图解析器解析,视图名称拼接视图前缀和视图后缀所得到的最终路径,会通过转发的方式实现跳转
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
return "success";
}
上面这种方式生成的就是ThymeleafView视图
2、转发视图 forward:
springMVC默认的转发 InternalResourceView
SpringMVC中创建转发视图的情况:
当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,
此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将缀"forward:"去掉,剩余部分作为最终路径通过转发的方式实现跳转
//转发视图Internal
@RequestMapping("/testInternal")
public String testInternal(){
return "forward:/testThymeleafView";
}
3、重定向视图 redirect:
SpringMVC中默认的重定向视图是RedirectView
当控制器方法中所设置的视图名称以"redirect:"为前缀时,创建RedirectView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"redirect:"去掉,剩余部分作为最终路径通过重定向的方式实现跳转
注意::>重定向视图在解析时,会先将redirect:前缀去掉,然后会判断剩余部分是否以 / 开头,若是则会自动拼接上下文路径
//重定向视图RedirectView
@RequestMapping("/testRedirect")
public String testRedirect(){
//因为重定向不会被视图解析器解析,所以访问不到templates下的html页面,所以我在webapp下创建了一个jsp页面来实验
return "redirect:/hello.jsp";
/*
* 也可以使用下面的方法在内部将请求转换为我们的templates下的html页面
* return "redirect:/testThymeleafView";
* */
}
这里的hello.jsp页面直接创建在webapp页面下
4、视图控制器view-controller
当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用 view-controller标签进行表示,在springMVC.xml文件当中配置
```xml
<!--
path:设置处理的请求地址
view-name:设置请求地址所对应的视图名称
-->
<mvc:view-controller path="/testView" view-name="success"></mvc:view-controller>
```
注意::当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签:
开启SpringMVC注解驱动: <mvc:annotation-driven />
六、RESTful
1.RESTful简介
REST:**Re**presentational **S**tate **T**ransfer,表现层资源状态转移。
##### a>资源
资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。
##### b>资源的表述
资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。
##### c>状态转移
状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。
2、RESTful的实现
具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:
GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。
例子::
| 操作 | 传统方式 | REST风格 |
| -------- | ---------------- | ----------------------- |
| 查询操作 | getUserById?id=1 | user/1-->get请求方式 |
| 保存操作 | saveUser | user-->post请求方式 |
| 删除操作 | deleteUser?id=1 | user/1-->delete请求方式 |
| 更新操作 | updateUser | user-->put请求方式 |
****get请求
、、、html
<a th:href="@{/user/1}">根据id查询信息</a><br>
、、、java
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String selectById(@PathVariable("id")String id){
System.out.println("根据id查询数据 id:"+id);
return "success";
}
***post
、、、html
<form th:action="@{/user}" method="post">
id:<input type="text" name="id"><br>
用户名:<input type="text" name="username"><br>
<input type="submit" value="保存数据">
</form><br>
、、、java
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String save(String id,String username){
System.out.println("保存数据id:"+id+",username:"+username);
return "success";
}
3、HiddenHttpMethodFilter
由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?
SpringMVC 提供了 **HiddenHttpMethodFilter** 帮助我们**将 POST 请求转换为 DELETE 或 PUT 请求**
**HiddenHttpMethodFilter** 处理put和delete请求的条件:
a>当前请求的请求方式必须为post
b>当前请求必须传输请求参数_method (_method的值为你最终的请求方式)
满足以上条件,**HiddenHttpMethodFilter** 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数\_method的值才是最终的请求方式,所以我们就可以在表单当中添加<input type="hidden" name="_method" value="put">,hidden属性,隐藏的,不会再页面当中显示,但是会传参
在web.xml中注册**HiddenHttpMethodFilter**
<!--配置HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern><!--这里是所有路径经过该过滤器-->
</filter-mapping>
、、、html
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="put">这里的put最终会转换为大写,所以我们这里大小写都可以
id:<input type="text" name="id"><br>
用户名:<input type="text" name="username"><br>
<input type="submit" value="修改数据">
</form><br>
、、、java
@RequestMapping(value = "/user" ,method = RequestMethod.PUT)
public String updateById(String id,String username){
System.out.println("修改数据id:"+id+",username:"+username);
return "success";
}
注意:::
> 目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter(字符响应)和HiddenHttpMethodFilter(put请求,delete请求修改过滤器)
> 在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter
> 原因:
> 在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集的
> - request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作
> - 而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:
> String paramValue = request.getParameter(this.methodParam);
4、rest案例
一般是先进行html页面书写,再进行控制器方法的写,由前端到后端
我们这里没有连接数据库,是所以我们dao里面的方法都是模拟方法
(1)依赖文件
打包方式使用war,jdk使用的1.8
<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
(2).配置web.xml文件
<!--配置编码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</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>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--HiddenHttpMethodFilter这个让我们浏览器可以发送put,delete请求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springmvc。xml文件位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.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>
(3).配置springMVC.xml文件
记住:使用context,mvc要导入命名空间
<!--扫描组件-->
<context:component-scan base-package="com.xsh.springMVCRest"/>
<!--视图控制器-->
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<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/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
<!--配置首页,记住配置了的话需要开启注解配置,否则我们controller当中配置的请求页面失效-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--添加操作表单页面-->
<mvc:view-controller path="/toAdd" view-name="toAdd"/>
<!-- 开放对静态资源的访问-->
<mvc:default-servlet-handler />
<!-- 这个是开启mvc的注解驱动,因为前面使用了mvc:view-controller,所以不开启的话我们的@RequestMapper使用会失效-->
<mvc:annotation-driven/>
(4)创建pojo类
里面有无参有参构造,set,get,tostring方法
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
public Employee() {
}
public Employee(Integer id, String lastName, String email, Integer gender) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
}
(6)创建dao层的方法
因为我们后面控制层的使用需要创建接口对象,所以我们使用将创建对象spring容器ioc去管理
我们没有具体去连接数据库,这里使用的是模拟数据库操作
这里使用@Repository
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
}
private static Integer initId = 1006;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employees.put(employee.getId(), employee);
}
public Collection<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
(7)创建控制层controller
其中有两个链接,一个首页index,一个toadd跳转到增加数据页面我们放在spring.xml文件当中创建,因为这两个链接只包含path路径,和所要跳转的页面
@Controller
public class testController {
@Autowired
private EmployeeDao employeeDao;
//查看所有信息
@RequestMapping(value = "/employee",method = RequestMethod.GET)
public String getAll(Model model){
Collection<Employee> employeeList = employeeDao.getAll();
model.addAttribute("employeeList",employeeList);
return "employee_list";
}
//根据id删除数据
@RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
public String deleteById(@PathVariable("id")Integer id){
employeeDao.delete(id);
return "redirect:/employee"; //通过重定向去访问查询所有界面
}
//添加数据
@RequestMapping(value = "/employee",method = RequestMethod.POST)
public String save(Employee employee){
employeeDao.save(employee);
return "redirect:/employee";
}
//数据修改,我们是先跳转到查询单个数据的界面,然后进行数据的修改
@RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
public String toUpdate(@PathVariable("id")Integer id,Model model){
Employee employeeOne = employeeDao.get(id);
model.addAttribute("employeeOne",employeeOne);
return "toUpdate";
}
@RequestMapping(value = "/employee",method = RequestMethod.PUT)
public String updateById(Employee employee){
employeeDao.save(employee);
return "redirect:/employee";
}
}
(8)创建vue.js文件
再webapp下面创建static包,再创建一个js包,再下面存放js文件
(9)我们所创建的html页面
再WEB-INF下创建一个包templates,在下面存放我们的html页面数据
index.xml首页页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>员工信息操作首页</h1>
<a th:href="@{/employee}">查看员工信息</a><br>
</body>
</html>
employee_list.html数据展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>员工信息展示</title>
<!--将js文件导入进来-->
<script type="text/javascript"th:src="@{/static/js/vue.js}"></script>
</head>
<body>
<table id="dateTable" border="1" cellpadding="0" cellspacing="0" style="text-align: center;">
<tr>
<th colspan="5">Employee Info</th>
</tr>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>操作<a th:href="@{/toAdd}">add</a> </th>
</tr>
<!--th:each 这里是循环map集合,就是查询所有结果的循环-->
<tr th:each="employee : ${employeeList}">
<td th:text="${employee.id}"></td>
<td th:text="${employee.lastName}"></td>
<td th:text="${employee.email}"></td>
<td th:text="${employee.gender}"></td>
<td>
<a @click="deleteEmployee" th:href="@{'/employee/'+${employee.id} }">delete</a>
<a th:href="@{'/employee/'+${employee.id} }">update</a>
</td>
</tr>
</table>
<!--这个是我们的delete方法的表单提交-->
<form id="deleteForm" method="post">
<!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
<input type="hidden" name="_method" value="delete">
</form>
<script type="text/javascript">
var vue = new Vue({
//绑定操作的容器,就是我们点击事件所在的容器
el:dateTable,
methods:{
//event表示当前事件
deleteEmployee:function(event){
//通过id获取form表单标签
var deleteForm = document.getElementById("deleteForm");
//通过当前事件先获取触发事件的元素target(这里就是删除的超链接)
//然后再获取超链接当中的href的值,最后将值赋值给我们的表单action
deleteForm.action = event.target.href;
//提交表单
deleteForm.submit();
//阻止超链接的默认跳转行为
event.preventDefault();
}
}
});
</script>
</body>
</html>
toAdd.html增加数据页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>员工增加页面</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
lastName:<input type="text" name="lastName"><br>
gender:<input type="radio" name="gender" value="1">male
<input type="radio" name="gender" value="0">nv<br>
email:<input type="text" name="email"><br>
<input type="submit" value="保存">
</form>
</body>
</html>
toUpdate.html修改数据页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>员工数据修改</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="id" th:value="${employeeOne.id}">
lastName:<input type="text" name="lastName" th:value="${employeeOne.lastName}"><br>
email:<input type="text" name="email" th:value="${employeeOne.email}"><br>
//th:field="${employeeOne.gender}这个用于单选框的复选
gender:<input type="radio" name="gender" value="1" th:field="${employeeOne.gender}">男
<input type="radio" name="gender" value="0" th:field="${employeeOne.gender}">女 <br>
<input type="submit" value="update">
</form>
</body>
</html>
七、HttpMessageconverter
1、@RequestBody注解
@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值
、、、html
<form th:action="@{/testRequestBody}" method="post">
name:<input type="text" name="name"><br>
password: <input type="password" name="password"><br>
<input type="submit" value="/testRequestBody">
</form>
、、、java
@RequestMapping(value = "/testRequestBody",method = RequestMethod.POST)
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody:"+requestBody);
return "success";
}
//输出结果
requestBody:username=admin&password=123456
2、@Requestentity注解
RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息
、、、html
<form th:action="@{/testRequestEntity}" method="post">
name:<input type="text" name="name"><br>
password: <input type="password" name="password"><br>
<input type="submit" value="/testRequestBody">
</form>
、、、java
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前requestEntity表示整个请求信息
System.out.println("请求头:"+requestEntity.getHeaders());
System.out.println("请求体:"+requestEntity.getBody());
return "success";
}
3、@ResponseBody
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器(控制器方法返回值直接响应到浏览器)
、、、html
<a th:href="@{/testResponseBody}">测试@ResponseBody</a>
、、、java
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
//注意,这里success不是我们的视图名称,而是直接响应到浏览器的字符串
return "success";
}
4、SpringMVC处理json
第一步: 需要添加我们的 jackson 的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
第二步:再xml文件当中开启注解配置
在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串
第三步:再html页面当中写超链接,再到控制器方法接收超链接
、、、html
<a th:href="@{/testResponseBodyUser}">测试浏览器响应ResponseBodyUser</a>
、、、java
@RequestMapping("/testResponseBodyUser")
@ResponseBody
public User testResponseBodyUser(){
return new User(111,"xsh","1234");
}
注释::这里控制器当中的返回值User会转换为json格式的字符串响应到浏览器当中
5、SpringMVC处理ajax
(1) 先把js文件导入进来
(2)html页面
<div id="app">
<a @click="testAxios" th:href="@{/testAxios}">springMVC处理axios</a>
</div>
<script type="text/javascript" th:src="@{/static/js/vue.js}"/>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"/>
<script type="text/javascript">
var vue= new Vue({
el:"#app",
methods:{
testAxios:function (event){
axios({
method:"post",
url:event.target.href,
params:{
username:"admit",
password:"123"
}
}).then(function (response){
alert(response.data);
});
event.preventDefault();
}
}
});
</script>
(3)java控制台
@RequestMapping(value = "//testAxios")
@ResponseBody
public String testAxios(String username,String password){
System.out.println("username:"+username+",password:"+password);
return "hello,ajax";
}
6、@RestController注解
@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解,从而可以将返回值直接响应再浏览器上面
7、ResponseEntity
ResponseEntity用于控制器方法的,该控制器方法的返返回值类型回值就是响应到浏览器的响应报文
例子可以看下面的文件下载
八、文件上传和下载
向web.xml和springMVC.xml大致的配置都可以和创建springMVC框架基本一致。
1、文件的下载
我们首先将需要下载的文件放在webapp下面的文件夹当中
html页面
<head>
<meta charset="UTF-8">
<title>实现下载功能</title>
</head>
<body>
<a th:href="@{/testDown}">下载图片</a>
</body>
</html>
控制台java代码
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testDown(HttpSession httpSession) throws IOException {
//获取ServletContext对象
ServletContext servletContext = httpSession.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/00000.jpg");
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组 is.available()这个是获取输入流的长度
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字 这里我们唯一能改的就是后面file-name的值
headers.add("Content-Disposition", "attachment;filename=xsh.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象 响应体,响应头,响应状态码
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
注意:这个整篇能改动的地方就是你下载文件的文件路径,你下载下来后的文件名字,其他地方展示不会更改。
2、文件的上传
注意::: 文件上传要求form表单的请求方式必须为post,并且添加属性 enctype="multipart/form-data"
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
1.文件上传需要加上 commons-fileupload 依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、因为后面我们在控制器形参当中传入了MultipartFile对象,我们需要将上传的文件转换为MultipartFile类型,所以需要创建一个上传解析器
<!--使用上传功能需要加上我们的上传解析器
必须通过文件解析器的解析才能将文件转换为MultipartFile对象
这个上传解析器的id我们不能进行更改-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.html页面
需要注意的是文件上传必须是post请求,而且表单当中需要添加 enctype="multipart/form-data"属性
<form th:action="@{/testup}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
4、控制器方面xuya
@RequestMapping(value = "/testup",method = RequestMethod.POST)
@ResponseBody
public String testup(MultipartFile photo,HttpSession session) throws IOException {
//获取上传的文件名字
String filename = photo.getOriginalFilename();
//先获取服务器当中photo目录的路径
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath对应的路径是否存在
if(!file.exists()){
file.mkdir(); //没有救将photoPath路径创建下来
}
//File.separator文件分割符号
String finalPath= photoPath + File.separator + filename;
photo.transferTo(new File(finalPath));//文件上传
return "上传成功";
}
System.out.println("filename::"+filename);
System.out.println("servletContext::"+servletContext);
System.out.println("photoPath::"+photoPath);
System.out.println("finalPath::"+finalPath);
filename::许石豪.jpg
servletContext::org.apache.catalina.core.ApplicationContextFacade@18e89ada
photoPath::D:\java\springMvc学习笔记\springMVC\springMVC-HttpMessageConverter\target\springMVC-HttpMessageConverter-1.0-SNAPSHOT\photo
finalPath::D:\java\springMvc学习笔记\springMVC\springMVC-HttpMessageConverter\target\springMVC-HttpMessageConverter-1.0-SNAPSHOT\photo\许石豪.jpg
如果需要解决上传文件重名问题,我们就需要更改文件的保存名字filename
//获取文件后缀名字,因为文件名字当中可能有 “.” ,所以这里我们获取最后一个. 就是后缀
String hzName = filename.substring(filename.lastIndexOf("."));
//将uuid作为文件名字
String uuid = UUID.randomUUID().toString();
//将uuid和我们后缀拼接在一起
filename = uuid+ hzName;
九、拦截器
拦截器和异常处理器见springMVC-Interceptors;
1、拦截器的配置
SpringMVC中的拦截器用于拦截控制器方法的执行
SpringMVC中的拦截器需要实现 HandlerInterceptor
SpringMVC的拦截器必须在SpringMVC的配置文件中进行配置:
```springMVC.xml
//这个是将我们的拦截器类引入进来
<bean class="com.xsh.mvc.interceptors.firstInterceptors"></bean>
<ref bean="firstInterceptor"></ref>
<!-- 以上两种配置方式都是对DispatcherServlet所处理的所有的请求进行拦截 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/testRequestEntity"/>
<ref bean="firstInterceptor"></ref>
</mvc:interceptor>
<!--
以上配置方式可以通过ref或bean标签设置拦截器,
通过mvc:mapping设置需要拦截的请求,
通过mvc:exclude-mapping设置需要排除的请求,即不需要拦截的请求
-->
```
所以实现拦截器的步骤就是我们拦截器继承HandlerInterceptor,重写里面的方法,然后再搭配springMVC.xml文件当中进行配置,
2、拦截器的三个抽象方法
SpringMVC中的拦截器有三个抽象方法:
preHandle:控制器方法执行之前执行preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法;返回false表示拦截,即不调用控制器方法
postHandle:控制器方法执行之后执行postHandle()
afterComplation:处理完视图和模型数据,渲染视图完毕之后执行afterComplation()
3、多个拦截器
a>若每个拦截器的preHandle()都返回true
此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关:
preHandle()会按照配置的顺序执行,而postHandle()和afterComplation()会按照配置的反序执行
b>若某个拦截器的preHandle()返回了false
preHandle()返回false和它之前的拦截器的preHandle()都会执行,postHandle()都不执行,返回false的拦截器之前的拦截器的afterComplation()会执行
十、异常处理器
1、基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver
使用方式::再springMVC.xml文件当中配置
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--
properties的键表示处理器方法执行过程中出现的异常
properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
然后我们就可以通过请求域获取“ex”的值拿到异常信息-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
当我们程序发生上面的计算异常的时候,就会跳转error页面
出现异常
<!--因为我们再springMVC.xml文件当中配置了处理异常的键值对,
所以我们可以再这个页面输出我们的异常信息-->
<p th:text="${ex}"></p>
2、基于注解的异常处理
这个就是使用类代替springMVC.xml文件当中的异常配置
//@ControllerAdvice表示为异常处理器
@ControllerAdvice
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(ArithmeticException.class)
public String handleArithmeticException(Exception ex, Model model){
//ex表示当前请求处理中出现的异常对象
model.addAttribute("ex",ex);
return "error";
}
}
十一、注解配置SpringMVC
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
1、创建初始化类,代替web.xml
在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。
Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。
package com.xsh.mvc.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
//这个就是web.xml文件
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 指定spring的配置类,就是一些普通的servlet,还有一些bean对象放在这里面
* @return
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
/**
* 指定SpringMVC的配置类,一般就是我们的视图解析器啊,注解配置啊,拦截器那些
* @return
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
/**
* 指定DispatcherServlet的映射规则,即url-pattern,
* 就是web。xml文件当中的DispatcherServlet前端控制器
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
/**
* 这个是配置我们的过滤器,注册过滤器
* */
@Override
protected Filter[] getServletFilters() {
//配置乱码过滤器
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceResponseEncoding(true);
//配置put和delete请求过滤器
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
//将我们两个过滤器返回
return new Filter[]{encodingFilter,hiddenHttpMethodFilter};
}
//配置文件上传的对象
@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
//设置文件上传的编码格式
multipartResolver.setDefaultEncoding("utf-8");
//设置文件上传的大小 单位:字节
multipartResolver.setMaxUploadSize(1024*1024*2);
return multipartResolver;
}
}
2.创建拦截器类
//拦截器
public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器成功运行");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
3.创建前端控制器类
@Controller
public class TestController {
@RequestMapping("/")
public String toIndex(){
return "index";
}
//测试异常类
@RequestMapping("/textException")
public String textException(){
//设置计算输出异常,让我们配置的异常处理器跳转异常界面
System.out.println(1/0);
return "hello";
}
}
4.将我们的webConfig和SpringConfig创建出来
webConfig里面的方法就是springMVC.XML文件的注解配置
package com.xsh.mvc.config;
/*除去属于springmvc的配置之外,其他的都配置在这里*/
@Configuration
@ComponentScan(basePackages = {"com.xsh"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {EnableWebMvc.class, Controller.class})
}) //扫描组件,将springmvc扫描过的组件排除出去,避免重复扫描
public class SpringConfig {
}
package com.xsh.mvc.config;
/*
* 用来代替springMVC.xml的配置文件
扫描组件 ,视图解析器,view-controller,default-servlet-handler,mvc注解驱动,文件上传解析器,拦截器,异常处理器
* */
//.如果书注解式的话需要加上一个这个
@Configuration
//1.扫描组件
@ComponentScan("com.xsh.mvc.controller")
//2.开启mvc注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
//使用默认的servlet处理静态资源就是mvc的default-servlet-handler
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//配置拦截器,拦截器里创建的对象是我们写的拦截类实现了HandlerInterceptor接口
@Override
public void addInterceptors(InterceptorRegistry registry) {
TestInterceptor testInterceptor = new TestInterceptor();
registry.addInterceptor(testInterceptor).addPathPatterns("/**");
}
//view-controller,先是路径,在是跳转的页面
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}
//配置异常处理器
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties prop = new Properties();
//若出现指定异常时,设置一个新的视图名称,跳转到指定页面
prop.setProperty("java.lang.ArithmeticException","error");
//将异常添加进去,设置异常映射
exceptionResolver.setExceptionMappings(prop);
//设置共享异常信息的键
exceptionResolver.setExceptionAttribute("ex");
resolvers.add(exceptionResolver);
}
/*
*下面的都是视图解析器
*/
//配置生成模板解析器
@Bean
public ITemplateResolver templateResolver() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
// ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext 的方法获得
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
webApplicationContext.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
//生成模板引擎并为模板引擎注入模板解析器
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
//生成视图解析器并未解析器注入模板引擎
@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
}
十二、springMVC.xml文件里面的配置
<!--配置视图控制器-->
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<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/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
//配置controller,没有其他操作的时候可以直接这样配置,配置了需要开启注解配置
<mvc:view-controller path="/" view-name="index"/>
<mvc:default-servlet-handler/>
<!--开启注解配置-->
<mvc:annotation-driven/>
<!--使用上传功能需要加上我们的上传解析器
必须通过文件解析器的解析才能将文件转换为MultipartFile对象
这个上传解析器的id我们不能进行更改-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
、、、依赖文件
<!--这个是上传功能的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
//拦截器的配置
//这个是将我们的拦截器类引入进来
<bean class="com.xsh.mvc.interceptors.firstInterceptors"></bean>
<ref bean="firstInterceptor"></ref>
<!-- 以上两种配置方式都是对DispatcherServlet所处理的所有的请求进行拦截 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/testRequestEntity"/>
<ref bean="firstInterceptor"></ref>
</mvc:interceptor>
<!--
以上配置方式可以通过ref或bean标签设置拦截器,
通过mvc:mapping设置需要拦截的请求,
通过mvc:exclude-mapping设置需要排除的请求,即不需要拦截的请求
-->
```