MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分
M:Model,模型层,指的是工程中的JavaBean,作用是处理数据
JavaBean分为两类:
V:View,视图层,指工程中的html或者jsp界面,作用是与用户进行交互,展示数据
C:Controller,控制层,指工程中的servlet,作用是接收请请求和响应浏览器
MVC的工作流程:
用户通过视图层发送请求到服务器,在服务器中,请求被Controller接收,Controller调用相应的Model层处理请求,处理完毕将结果返回到Controller,Controller再根据请求处理的结果找到相应的View视图,渲染数据最终响应给浏览器。
SpringMvc是Spring的一个后续产品,是Spring的一个子项目
三层架构分别为表述层、业务逻辑层、数据访问层,表述层表示前台页面和后台servlet
<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>SpringMvcservlet-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>SpringMvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<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 https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wyf.controller">context:component-scan>
<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>
@Controller
public class HelloController {
//当前请求路径"/"--->WEB-INF/templates/index.html
@RequestMapping("/")
public String index(){
//返回视图名称
return "index";
}
}
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>
body>
html>
@RequestMapping("/target")
public String toTarget(){
return "target";
}
流程总结:
浏览器发送请求,若请求地址符合前端控制器的url-pattern(访问路径),该请求就会被前端控制器DispatcherServlet(在web.xml中已经配好)处理。前端控制器会读取SpringMvc的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应界面。
1、@RequestMapping注解的功能
从注解名称上可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器关联起来,建立映射关系。SpringMVC接收到指定的请求,就会找到在映射关系中对应的控制器方法来处理这个请求。
2、@RequestMapping注解的位置
@RequestMapping注解可以标识一个类,也可以标识一个方法
@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
return "success";
}
}
3、@RequestMapping注解的value属性
@RequestMapping注解的value属性通过请求的请求地址匹配请求映射
@RequestMapping注解的value属性是一个字符串类型的数组,标识该请求映射能够匹配多个请求地址所对应的请求,请求满足value属性中String数组中一个就可以。
@RequestMapping注解的value属性必须设置值,至少通过请求地址匹配请求映射
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping
@RequestMapping({"/testRequestMapping","/hello"})
public String testRequestMapping(){
return "success";
}
}
4、@RequestMapping注解的method属性
@RequestMapping注解的method属性通过请求方式(get或post)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求能够匹配多种请求方式的请求
若当前的请求地址满足请求映射的value属性,但是请求方式不满足method属性,浏览器报错405
@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping,请求方式get和post都可以
@RequestMapping(value = {"/testRequestMapping","/hello"},
method = {RequestMethod.GET,RequestMethod.POST})
public String testRequestMapping(){
return "success";
}
}
5、SpringMVC提供的@RequestMapping派生注解
处理get请求的映射—>@GetMapping
处理post请求的映射—>@PostMapping
处理put请求的映射—>@PutMapping
处理delete请求的映射—>@DeleteMapping
6、@RequestMapping注解的params属性
@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置参数和请求映射的匹配关系
“param”:要求请求映射所匹配的请求必须携带param请求参数
params = {“username”}
“!param”:要求请求映射所匹配的请求必须不能携带param请求参数
params = {“!username”}
“param”:要求请求映射所匹配的请求必须携带param请求参数且参数值param=value
params = {“username=admin”}
“param!=value”:要求请求映射所匹配的请求必须携带param请求参数且参数值param=!value
params = {“username=!admin”}
?:表示任意的单个字符
@RequestMapping(“/a?a/testAnt”)
*:表示任意的0个或多个字符
@RequestMapping(“/a*a/testAnt”)
**:表示任意的一层或多层目录
@RequestMapping(“/a/**/a/testAnt”)
注意:在使用 * * 时,只能使用/ * * /xxx的方式
原始方式:/deleteUser?id=1
rest方式:/deleteUser/1
SpringMVC路径中的占位符常用于restful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参
@RequestMapping("/rest/{id}/{username}")
public String rest(@PathVariable("id") String id,
@PathVariable("username") String username){
System.out.println("id:" + id + ",username:" + username);
return "success";
}
<h1>测试请求参数h1>
<a th:href="@{/testServletAPI(username='admin',password=123456)}">测试使用ServletAPI获取请求参数a>
@Controller
public class ParamController {
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:" + username + ",password:" + password);
return "success";
}
}
<form th:action="@{/testParam}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" 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>
@RequestMapping("/testParam")
public String testParam(String username,String password,String[] hobby){
//多请求参数中出现多个同名的请求参数,http://localhost:8080/testParam? username=admin&password=123&hobby=a&hobby=b
//可以在控制器方法的形参中设置字符串或者字符串数组类型的形参来接收请求参数
System.out.println(username + password + Arrays.toString(hobby));
return "success";
}
@RequestParam是将请求参数和控制器方法的形参创建映射关系
该注解一共有三个属性:
value:指定为形参赋值的请求参数的参数名
required:设置是否必须传输此参数,默认值为true
defaultValue:不管required的属性值为true或false,当value指定的请求参数没有传输或传输值为空时,使用默认值为形参赋值
@RequestMapping("/testParam")
public String testParam(@RequestParam(value = "user_name",required = false,
defaultValue = "hello") String username, String password, String[] hobby){
return "success";
}
@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@RequestMapping("/testParam")
public String testParam(@RequestHeader("Host") String host){
System.out.println(host);//localhost:8080
return "success";
}
@CookieValue是将cookie数据和控制器方法的形参创建映射关系
@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@RequestMapping("/testParam")
public String testParam(@CookieValue("JSESSIONID") String JSESSIONID){
//request.getSession();需要获取Session,JSESSIONID才能够存在
System.out.println(JSESSIONID);
return "success";
}
<form th:action="@{testPOJO}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
年龄:<input type="text" name="age"><br>
邮箱:<input type="text" name="email"><br>
<input type="submit" value="实体类接收请求参数">
form>
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String email;
}
@RequestMapping("/testPOJO")
public String testPOJO(User user){
System.out.println(user);
//User{id=null, username='admin', password='123456', age=18, email='[email protected]'}
return "success";
}
<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>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){
request.setAttribute("testRequestScope","wyf");
Object attribute = request.getAttribute("testRequestScope");
System.out.println(attribute);//wyf
return "success";
}
<p th:text="${testRequestScope}">p>//显示request域中对应的值wyf
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/*
* ModelAndView有Model和View功能
* Model主要用于向请求域中共享数据
* View主要用于设置视图,实现页面跳转
* 方法的返回值必须是ModelAndView
* */
ModelAndView modelAndView = new ModelAndView();
//向请求域中共享数据
modelAndView.addObject("testModelAndView","wyf");
//设置视图,实现页面跳转
modelAndView.setViewName("success");
return modelAndView;
}
<p th:text="${testModelAndView}">p>//显示request域中对应的值wyf
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testModel","wyf");
return "success";
}
<p th:text="${testModel}">p>//显示request域中对应的值wyf
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("testMap","wyf");
return "success";
}
<p th:text="${testMap}">p>//显示request域中对应的值wyf
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testModelMap","csq");
return "success";
}
<p th:text="${testModelMap}">p>//显示request域中对应的值csq
Model、ModelMap、Map类型的参数其实本质上都是BindingAwareModelMap类型的
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSession","hello session");
return "success";
}
<p th:text="${session.testSession}">p>显示session域中对应的值hello session
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplication","hello application");
return "success";
}
<p th:text="${application.testApplication}">p>显示application域中对应的值hello application
SpringMVC中的视图是View接口,视图的作用是渲染数据,将模型Model中的数据展示给用户
SpringMVC视图种类有很多,默认有转发视图InternalResourceView和重定向视图RedirectView
@Controller
public class ViewController {
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
return "success";
}
@RequestMapping("/testForward")
public String testForward(){
return "forward:/testThymeleafView";
}
}
@Controller
public class ViewController {
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
return "success";
}
@RequestMapping("/testRedirect")
public String testForward(){
return "redirect:/testThymeleafView";
}
}
当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用view-controller标签进行表示
<mvc:view-controller path="/" view-name="index">mvc:view-controller>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
public String getUserById(@PathVariable("userId") Integer userId ){
System.out.println("根据" + userId + "查询用户信息");
return "success";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String insertUser(String username,String password){
System.out.println("添加用户信息:" + username + password);
return "success";
}
<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>
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="PUT">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="修改"><br>
form>
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponeEntity
@RequestBody可以获取请求体,需要在控制方法中设置一个形参,使用@RequestBody进行标识。当前请求的请求体就会为当前注解所标识的形参赋值
<form th:action="@{/testRequestBody}" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="测试RequestBody">
form>
@RequestMapping("/testRequestBody")//注意@RequestParam的变量名要和前端input标签的name属性一致
public String testRequestBody(@RequestBody String requestBody ,@RequestParam String username,@RequestParam String password){
System.out.println("requestBody:" + requestBody);//username=admin&password=123456
System.out.println(username);//admin
System.out.println(password);//123456
return "success";
}
<form th:action="@{/testRequestEntity}" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="测试RequestEntity">
form>
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前RequestEntity表示的是整个请求报文的信息
System.out.println(requestEntity.getHeaders());
//[host:"localhost:8080", connection:"keep-alive", content-length:"30"...
System.out.println(requestEntity.getBody());
//username=admin&password=123123
return "success";
}
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
加上@ResponseBody注解之后,return “success”;不在作为视图被解析,而是响应给浏览器的数据字符串 “success”
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "success";
}
ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
ResponseEntity实现文件下载
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContest对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.jpg");
//创建输入流
FileInputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String,String> headers = new HttpHeaders();
//设置下载方式以及下载文件的名字
headers.add("Content-Disposition","attachment;filename=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
用在控制器(Controller)的类上,相当于@Controller和@ResponseBody的合体,给控制器类中的所有方法都加上了@ResponseBody,所以方法返回的对象可以转换为响应浏览器数据的响应体传到前端。
@ResponseBody处理json的步骤
导入jackson的依赖
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.2.2version>
dependency>
开启mvc的注解驱动
<mvc:annotation-driven/>
在处理器方法上使用@ResponseBody注解进行标识
将Java对象直接作为方法的返回值返回,就会自动转换为json格式的字符串,JavaScript会把json格式字符串转换为json对象
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1,"wyf",18);
}
浏览器结果
{"id":1,"userName":"wyf","age":18}//json对象
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>
@RequestMapping("/testUp")
public String testUp(MultipartFile photo,HttpSession session) throws IOException {
String originalFilename = photo.getOriginalFilename();
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath所对应路径是否存在
if (!file.exists()){
//若不存在,则创建目录
file.mkdir();
}
String finalPath = photoPath + File.separator + originalFilename;
photo.transferTo(new File(finalPath));
return "success";
}
//获取上传文件的文件名
String originalFilename = photo.getOriginalFilename();
//获取上传文件的文件名,并截取后缀
String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
//将UUID作为文件名
String uuid = UUID.randomUUID().toString();
//将uuid和后缀名拼接后的结果作为最终的文件名
originalFilename = uuid + suffixName;
public class FirstInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("-------preHandle-------------");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("--------postHandle-----------");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("-----------afterCompletion---------");
}
}
<bean class="com.wyf.Interceptor.FirstInterceptor">bean>
<ref bean="firstInterceptor">ref>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/testHello"/>
<ref bean="firstInterceptor">ref>
mvc:interceptor>
SpringMVC中的拦截器有三个抽象方法:
preHandler:控制器方法执行之前执行,返回值为boolean,返回true表示放行,返回false表示拦截
postHandler:控制器方法执行之后执行
afterComplation:处理完视图和模型数据,渲染视图完毕后执行
此时多个拦截器的执行顺序和拦截器在SpringMVC配置文件的顺序有关:
preHandler()会按照配置的顺序执行,而postHandler()和afterComplation会按照配置的反序执行
preHandler()返回false和它之前的拦截器的preHandler()都会执行,postHandler()都不执行,返回false的拦截器之前的拦截器的afterComplation()都会执行
//执行控制器方法制造异常
@RequestMapping("/testControllerAdvice")
public String testControllerAdvice(){
System.out.println(1/0);
return "success";
}
@ControllerAdvice//将当前类标识为异常处理的组件
public class ExceptionController {
// @ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
public String testException(Exception ex, Model model){
//ex标识当前请求处理中出现的异常对象
model.addAttribute("ex",ex);
return "error";
}
}
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
编写WebInit继承AbstractAnnotationConfigDispatcherServletInitializer代替web.xml
//web工程的初始化类,用来代替web.xml
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定spring的配置类
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//指定springMVC的配置类
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
//指定DispatcherServlet的映射规则,即url-pattern
protected String[] getServletMappings() {
return new String[]{"/"};
}
//注册过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceResponseEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
}
//spring的配置类
@Configuration
public class SpringConfig {
//没有进行具体配置
}
//代替springMvc的配置文件
/* 1.扫描组件
2.视图解析器
3.view-controller
4.default-servlet-handler
5.mvc注解驱动
6.文件上传解析器
7.异常处理
8.拦截器
*/
//将当前类标识为配置类
@Configuration
//1.扫描组件
@ComponentScan("com.wyf")
//5.注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
//4.default-servlet-handler
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}