• Spring MVC(上)


    1、Spring MVC简介:

    MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分

    M:Model,模型层,指工程中的JavaBean,作用是处理数据

    JavaBean分为两类:

    • 一类称为实体类Bean:专门存储业务数据的,如 Student、User 等

    • 一类称为业务处理 Bean:指 Service 或 Dao 对象,专门用于处理业务逻辑和数据访问。

    V:View,视图层,指工程中的html或jsp等页面,作用是与用户进行交互,展示数据

    C:Controller,控制层,指工程中的servlet,作用是接收请求和响应浏览器

             MVC的工作流程: 用户通过视图层发送请求到服务器,在服务器中请求被Controller接收,Controller调用相应的Model层处理请求,处理完毕将结果返回到Controller,Controller再根据请求处理的结果找到相应的View视图,渲染数据后最终响应给浏览器

            实际上Spring MVC 对原生的Servlet进行封装,然后成为一个功能更强大的前端控制器

    特点:

    • Spring 家族原生产品,与 IOC 容器等基础设施无缝对接

    • 基于原生的Servlet,通过了功能强大的前端控制器DispatcherServlet,对请求和响应进行统一处理

    • 表述层各细分领域需要解决的问题全方位覆盖,提供全面解决方案

    • 代码清新简洁,大幅度提升开发效率

    • 内部组件化程度高,可插拔式组件即插即用,想要什么功能配置相应组件即可

    • 性能卓著,尤其适合现代大型、超大型互联网项目要求

    2、Spring MVC配置:

    (1)默认方式配置:

            此配置作用下,SpringMVC的配置文件默认位于WEB-INF下,默认名称为-servlet.xml,例如,以下配置所对应SpringMVC的配置文件位于WEB-INF下,文件名为springMVC-servlet.xml。

    1. <servlet>
    2. <servlet-name>springMVCservlet-name>
    3. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    4. servlet>
    5. <servlet-mapping>
    6. <servlet-name>springMVCservlet-name>
    7. <url-pattern>/url-pattern>
    8. servlet-mapping>

    (2)扩展配置方式

            可通过init-param标签设置SpringMVC配置文件的位置和名称,通过load-on-startup标签设置SpringMVC前端控制器DispatcherServlet的初始化时间。

    1. "1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <servlet>
    7. <servlet-name>SpringMVCservlet-name>
    8. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    9. <init-param>
    10. <param-name>contextConfigLocationparam-name>
    11. <param-value>classpath:springMVC.xmlparam-value>
    12. init-param>
    13. <load-on-startup>1load-on-startup>
    14. servlet>
    15. <servlet-mapping>
    16. <servlet-name>SpringMVCservlet-name>
    17. <url-pattern>/url-pattern>
    18. servlet-mapping>
    19. web-app>

    标签中使用  和  /*  的区别:

            / 所匹配的请求可以是/login或.html或.js或.css方式的请求路径,但是 不能匹配.jsp请求路径的请求,因此就可以避免在访问jsp页面时,该请求被DispatcherServlet处理,从而找不到相应的页面。

            /* 则能够匹配所有请求,例如在使用过滤器时,若需要对所有请求进行过滤,就需要使用 /* 的写法。

    (3)配置视图解析器:

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    7. <context:component-scan base-package="com.songzhishu.MVC"/>
    8. <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    9. <property name="order" value="1"/>
    10. <property name="characterEncoding" value="UTF-8"/>
    11. <property name="templateEngine">
    12. <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
    13. <property name="templateResolver">
    14. <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    15. <property name="prefix" value="/WEB-INF/templates/"/>
    16. <property name="suffix" value=".html"/>
    17. <property name="templateMode" value="HTML5"/>
    18. <property name="characterEncoding" value="UTF-8" />
    19. bean>
    20. property>
    21. bean>
    22. property>
    23. bean>
    24. beans>

    3、@RequestMapping注解

            从注解名称上我们可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求。

    (1)存在的位置:

    @RequestMapping标识一个类:设置映射请求的请求路径的初始信息

    @RequestMapping标识一个方法:设置映射请求请求路径的具体信息

    1. @Controller
    2. @RequestMapping("/test")
    3. public class RequestMappingController {
    4. //此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
    5. @RequestMapping("/testRequestMapping")
    6. public String testRequestMapping(){
    7. return "success";
    8. }
    9. }

    多个控制器,RequestMapppering匹配到的地址是唯一的

    (2)@RequestMapping注解的value属性

    @RequestMapping注解的value属性通过请求的请求地址匹配请求映射

    @RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求

    @RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射

    controller控制器:

    1. @Controller
    2. public class RequestMappingController {
    3. @RequestMapping(value = {"/testRequestMapping","/test"})
    4. public String success(){
    5. return "success";
    6. }
    7. }

    这的意思就是,多个映射匹配的目标的是同一个请求地址。

    (3)@RequestMapping注解的method属性(只满足一个就可以)

    @RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射

    @RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求

    若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错405:Request method 'POST' not supported

    1. @Controller
    2. public class RequestMappingController {
    3. @RequestMapping(value = {"/testRequestMapping","/test"},method = {RequestMethod.POST,RequestMethod.GET})
    4. public String success(){
    5. return "success";
    6. }
    7. }

    这的意思就是,多个映射匹配的目标的是同一个请求地址同时请求的方式是post和get两种

    1、对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解

    处理get请求的映射-->@GetMapping

    处理post请求的映射-->@PostMapping

    处理put请求的映射-->@PutMapping

    处理delete请求的映射-->@DeleteMapping

    相同的请求地址的情况下,可以使用注解表示不同的请求方式! 

    (4)@RequestMapping注解的params属性(必须同时满足)

    @RequestMapping注解的params属性通过请求的请求参数匹配请求映射

    @RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系

    "param":要求请求映射所匹配的请求必须携带param请求参数

    "!param":要求请求映射所匹配的请求必须不能携带param请求参数

    "param=value":要求请求映射所匹配的请求必须携带param请求参数且param=value

    "param!=value":要求请求映射所匹配的请求必须携带param请求参数但是param!=value

    1. @RequestMapping(
    2. value = {"/testParam"}
    3. ,method = {RequestMethod.GET, RequestMethod.POST}
    4. ,params = {"username","password!=123456"}
    5. )
    6. public String testParam(){
    7. return "success";
    8. }

            使用param的话,要所有都满足才可以完成跳转!大概意思就是必须携带这username的参数,然后携带password参数并且携带的值不能是123456。

    (5)@RequestMapping注解的headers属性(同时满足)

    @RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射

    @RequestMapping注解的headers属性是一个字符串类型的数组,可以通过四种表达式设置请求头信息和请求映射的匹配关系

    "header":要求请求映射所匹配的请求必须携带header请求头信息

    "!header":要求请求映射所匹配的请求必须不能携带header请求头信息

    "header=value":要求请求映射所匹配的请求必须携带header请求头信息且header=value

    "header!=value":要求请求映射所匹配的请求必须携带header请求头信息且header!=value

    若当前请求满足@RequestMapping注解的value和method属性,但是不满足headers属性,此时页面显示404错误,即资源未找到

    (6)SpringMVC支持ant风格的路径(模糊匹配)

    ?:表示任意的单个字符

    @RequestMapping(value = "/a?c/testPut" ,method = RequestMethod.PUT)

    表示可以匹配 aac  abc 等等!!!! 

    *:表示任意的0个或多个字符

    @RequestMapping(value = "/a*c/testPut" ,method = RequestMethod.PUT)

     表示可以匹配    ac    aaaaaac     abvvvvvdfwerc 等等!!!! 

    **:表示任意的一层或多层目录

    @RequestMapping(value = "/**/testPut" ,method = RequestMethod.PUT)

     表示可以匹配    ac    a/a/aa/a/a/c     abv/v/v/v/vd/f/w/er/c 等等!!!! 

    注意:在使用**时,只能使用/**/xxx的方式

    (7)SpringMVC支持路径中的占位符(重点)

    原始方式:/deleteUser?id=1

    rest方式:/deleteUser/1

            SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参。

           使用占位符必须传参,不传会报错!

    4、SpringMVC获取请求参数:

    (1)通过ServletAPI获取:

    1. @RequestMapping("/testParam")
    2. public String testParam(HttpServletRequest request){
    3. String username = request.getParameter("username");
    4. String password = request.getParameter("password");
    5. System.out.println("username:"+username+",password:"+password);
    6. return "success";
    7. }

     (2)通过控制器方法的形参获取请求参数:

            在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在DispatcherServlet中就会将请求参数赋值给相应的形参。(直接请求的数据作为匹配时传递的形参)。

    1. @RequestMapping("/testParam")
    2. public String testParam(String username, String password){
    3. System.out.println("username:"+username+",password:"+password);
    4. return "success";
    5. }

    注:

    若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串数组或者字符串类型的形参接收此请求参数

    若使用字符串数组类型的形参,此参数的数组中包含了每一个数据

    若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果

    1. <form th:action="@{/paramtest/testParam}" method="post">
    2. 用户名: <input type="text" name="username"> <br>
    3. 密码: <input type="password" name="password"> <br>
    4. 爱好: <input type="checkbox" name="hobby" value="sing">
    5. <input type="checkbox" name="hobby" value="dance">
    6. <input type="checkbox" name="hobby" value="rap">rap
    7. <input type="checkbox" name="hobby" value="play">打篮球<br>
    8. <input type="submit" value="测试多个参数的形式">
    9. form>
    1. @RequestMapping(value = "/**/testParam",method = RequestMethod.POST)
    2. public String testParam(String username, String password ,String[] hobby){
    3. System.out.println("username:"+username+",password:"+password+",hobby:"+hobby.toString());
    4. return "success";
    5. }

     (3)@RequestParam:

    @RequestParam是将请求参数和控制器方法的形参创建映射关系

    @RequestParam注解一共有三个属性:

    • value:指定为形参赋值的请求参数的参数名
    • required:设置是否必须传输此请求参数,默认值为true,若设置为true时,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置defaultValue属性,则页面报错400:Required String parameter 'xxx' is not present;若设置为false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为null
    • defaultValue:不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值

    这个可以应对请求参数和形参不一致的时候,可以使用!

    1. //@RequestParam
    2. @RequestMapping(value = "/**/testParam",method = RequestMethod.POST)
    3. public String testParam(@RequestParam(value = "user_name") String username,
    4. String password,
    5. @RequestParam(value = "hobby",defaultValue = "rap") String[] hobby){
    6. System.out.println("username:"+username+",password:"+password+",hobby:"+ Arrays.toString(hobby));
    7. return "success";
    8. }

    (4)@RequestHeader:

    @RequestHeader是将请求头信息和控制器方法的形参创建映射关系

    @RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam

    (5)@CookieValue:

    @CookieValue是将cookie数据和控制器方法的形参创建映射关系

    @CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam

    1. //@RequestParam
    2. @RequestMapping(value = "/**/testParam", method = RequestMethod.POST)
    3. public String testParam(@RequestParam(value = "user_name") String username,
    4. String password,
    5. @RequestParam(value = "hobby", defaultValue = "rap") String[] hobby,
    6. @RequestHeader(value = "kk",required = true ,defaultValue = "haha") String host,
    7. @CookieValue(value = "JSESSIONID") String JSESSIONID) {
    8. System.out.println("username:" + username + ",password:" + password + ",hobby:" + Arrays.toString(hobby)+",host:"+host);
    9. System.out.println("JSESSIONID:"+JSESSIONID);
    10. return "success";
    11. }

    (6)通过POJO获取请求参数

             可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值。

    1. <form th:action="@{/paramtest/testpojo}" method="post">
    2. 用户名:<input type="text" name="username"><br>
    3. 密码:<input type="password" name="password"><br>
    4. 性别:<input type="radio" name="sex" value="man"><input type="radio" name="sex" value="woman"><br>
    5. 年龄:<input type="text" name="age"><br>
    6. 邮箱:<input type="text" name="email"><br>
    7. <input type="submit">
    8. form>
    1. @RequestMapping("/**/testpojo")
    2. public String testPOJO(User user){
    3. System.out.println(user);
    4. return "success";
    5. }

    (7)解决获取请求参数的乱码问题:

            关于乱码的问题,都是编码的方式和解码的方式不一致导致的,对于get请求参数中的中文乱

    码的问题,Tomcat8开始都已经解决啦,就是只要是get请求不需要额外的指定编码。但是post没有

    解决方式可以使用过滤器然后经行编码的转变。

    1. <filter>
    2. <filter-name>CharacterEncodingFilterfilter-name>
    3. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    4. <init-param>
    5. <param-name>encodingparam-name>
    6. <param-value>UTF-8param-value>
    7. init-param>
    8. <init-param>
    9. <param-name>forceResponseEncodingparam-name>
    10. <param-value>trueparam-value>
    11. init-param>
    12. filter>
    13. <filter-mapping>
    14. <filter-name>CharacterEncodingFilterfilter-name>
    15. <url-pattern>/*url-pattern>
    16. filter-mapping>

    5、域对象共享数据

    (1)使用ServletAPI向request域对象共享数据

    1. //使用ServletAPI来向request对象共享数据
    2. @RequestMapping(value = ("/**/testRequestByServletAPI"))
    3. public String testRequestByServletAPI(HttpServletRequest request) {
    4. //获取共享数据 request.getAttribute()
    5. //删除共享数据 request.removeAttribute();
    6. //设置共项数据 key value
    7. request.setAttribute("name", "张胜男");
    8. return "success";
    9. }

    (2)使用ModelAndView向request域对象共享数据

    1. //通过ModelAndView向Request域对象共性数据
    2. @RequestMapping("/**/testModelAndView")
    3. public ModelAndView testModelAndView() {
    4. ModelAndView mav = new ModelAndView();
    5. //处理模型数据 共享数据
    6. mav.addObject("username", "李四");
    7. //设置视图名称 跳转页面
    8. mav.setViewName("success");
    9. return mav;
    10. }

    (3)使用Model向request域对象共享数据

    1. //这种方式的话,使用model来向Request域中共享数据,但是不进行视图解析
    2. @RequestMapping("/**/testModel")
    3. public String testModel(Model model) {
    4. model.addAttribute("username", "王五");
    5. return "success";
    6. }

    (4)使用map向request域对象共享数据

    1. //使用map向request域对象共享数据
    2. @RequestMapping("/**/testMap")
    3. public String testMap(Map map) {
    4. map.put("username","孙六");
    5. return "success";
    6. }

    (5)使用ModelMap向request域对象共享数据

    1. //使用ModelMap向request域对象共享数据
    2. @RequestMapping("/**/testModelMap")
    3. public String testModelMap(ModelMap modelMap) {
    4. modelMap.addAttribute("username","赵七");
    5. return "success";
    6. }

    (6)向session域共享数据

    1. @RequestMapping("/testSession")
    2. public String testSession(HttpSession session){
    3. session.setAttribute("username", "小明");
    4. return "success";
    5. }

    (7)向application域共享数据

    1. @RequestMapping("/testApplication")
    2. public String testApplication(HttpSession session){
    3. ServletContext application = session.getServletContext();
    4. application.setAttribute("password", "hello");
    5. return "success";
    6. }

    前端测试页面:

    1. <a th:href="@{/scope/testRequestByServletAPI}">通过ServletAPI向Request共享数据a><br>
    2. <a th:href="@{/scope/testModelAndView}">通过ModelAndView向Request域对象共性数据a><br>
    3. <a th:href="@{/scope/testModel}">使用model来向Request域中共享数据,但是不进行视图解析a><br>
    4. <a th:href="@{/scope/testMap}">使用map来向Request域中共享数据a><br>
    5. <a th:href="@{/scope/testModelMap}">使用ModelMap向request域对象共享数据a><br>
    6. <a th:href="@{/scope/testSession}">通过ServletAPI向session域对象共享数据a><br>
    7. <a th:href="@{/scope/testApplication}">向application域共享数据a><br>

  • 相关阅读:
    大学毕业一年 - 北漂生活
    【1431】java学习网站系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
    Vue核心(MVVM模型,数据代理,数据处理,计算属性-computed,监视属性-watch)
    数据库Day004
    Seata-Saga模式简介与三种模式对比
    AC牛客 BM46 最小的K个数
    【正点原子STM32连载】第三十九章 DS18B20数字温度传感器实验 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
    文心一言 VS 讯飞星火 VS chatgpt (139)-- 算法导论11.4 3题
    Springboot毕设项目儿童医院问诊导诊系统aqy75(java+VUE+Mybatis+Maven+Mysql)
    【Python人工智能】Python全栈体系(二十二)
  • 原文地址:https://blog.csdn.net/keleID/article/details/133920932