• SpringMVC学习笔记(二)


    五、域对象共享数据

    5.1 使用ServletAPI向request域对象共享数据

    @RequestMapping("/testServletAPI") 
    public String testServletAPI(HttpServletRequest request){ 
    request.setAttribute("testScope", "hello,servletAPI"); 
    return "success"; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.2 使用ModelAndView向request域对象共享数据

    @RequestMapping("/test/mav")
      public ModelAndView testModelAndView(){
        /**
         * ModelAndView有Model和View的功能
         * Model主要用于向请求域共享数据
         * View主要用于设置视图,实现页面跳转
         */
        ModelAndView modelAndView = new ModelAndView();
        //向请求域共享数据
        modelAndView.addObject("testScope","hello,ModelAndView");
        //设置视图,实现页面跳转
        modelAndView.setViewName("success");
        return modelAndView;
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    5.3 使用Model向request域对象共享数据

    @RequestMapping("test/model")
      public String testModel(Model model){
        model.addAttribute("testScope", "hello,Model");
        return "success";
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.4 使用map向request域对象共享数据

    @RequestMapping("test/map")
      public String testMap(Map<String,Object> map){
        map.put("testScope", "hello,Map");
        return "success";
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.5 使用ModelMap向request域对象共享数据

    @RequestMapping("/test/modelMap")
      public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testScope", "hello,ModelMap");
        return "success";
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.6 Model、ModelMap、Map的关系

    Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

    public interface Model{} 
    public class ModelMap extends LinkedHashMap<String, Object> {} 
    public class ExtendedModelMap extends ModelMap implements Model {} 
    public class BindingAwareModelMap extends ExtendedModelMap {}
    
    • 1
    • 2
    • 3
    • 4

    5.7 session域共享数据

    @RequestMapping("/test/session")
      public String testSession(HttpSession session){
        session.setAttribute("testSessionScope", "hello.session");
        return "success";
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.8 application域共享数据

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

    六、SpringMVC 的视图

    ​ SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户;SpringMVC视图的种类很多,默认有转发视图和重定向视图,当工程引入jstl的依赖,转发视图会自动转换为JstlView,若使用的视图技术为Thymeleaf,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解析之后所得到的是ThymeleafView。

    6.1 ThymeleafView

    当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被SpringMVC配置文件中所配置的视图解析器解析,视图名称拼接视图前缀和视图后缀所得到的最终路径,会通过转发的方式实现跳转

    @RequestMapping("/testHello") 
    public String testHello(){ 
    return "hello";
    }
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    6.2 转发视图

    SpringMVC中默认的转发视图是InternalResourceView

    SpringMVC中创建转发视图的情况:

    当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"forward:"去掉,剩余部分作为最终路径通过转发的方式实现跳转,例如"forward:/","forward:/employee"

    @RequestMapping("/testForward") 
    public String testForward(){ 
    return "forward:/testHello";
    }
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    6.3 重定向视图

    SpringMVC中默认的重定向视图是RedirectView;当控制器方法中所设置的视图名称以"redirect:"为前缀时,创建RedirectView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"redirect:"去掉,剩余部分作为最终路径通过重定向的方式实现跳转

    例如"redirect:/",“redirect:/employee”

    @RequestMapping("/testRedirect") 
    public String testRedirect(){ 
    return "redirect:/testHello";
    }
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    注:重定向视图在解析时,会先将redirect:前缀去掉,然后会判断剩余部分是否以/开头,若是则会自动拼接上下文路径

    6.4 视图控制器 view-controller

    当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用viewcontroller标签进行表示

     
    <mvc:view-controller path="/testView" view-name="success">mvc:view-controller>
    
    • 1
    • 2

    注:

    当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需

    要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签:

    七、RESTful

    7.1 RESTful 简介

    REST:Representational State Transfer,表现层资源状态转移。

    • 资源

      资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。

    • 资源的表述

      资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

    • 状态转移

      状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的

    7.2 RESTful 的实现

    具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE用来删除资源。

    REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。

    在这里插入图片描述

    7.3 HiddenHttpMethodFilter

    由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?

    SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们 POST 请求转换为 DELETE PUT 请求

    HiddenHttpMethodFilter 处理put和delete请求的条件:

    • 当前请求的请求方式必须为post
    • 当前请求必须传输请求参数_method

    满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式

    在web.xml中注册HiddenHttpMethodFilter

    
      <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    注:目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter

    在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter原因:

    在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集的request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作

    而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:

    String paramValue = request.getParameter(this.methodParam);

    八、RESTful 案例

    8.1 准备工作

    和传统 CRUD 一样,实现对员工信息的增删改查。

    • 搭建环境

    • 准备实体类

    • public class Employee {
      
          private Integer id;
          private String lastName;
      
          private String email;
          //1 male, 0 female
          private Integer 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;
          }
      
          public Employee(Integer id, String lastName, String email, Integer gender) {
              super();
              this.id = id;
              this.lastName = lastName;
              this.email = email;
              this.gender = gender;
          }
      
          public Employee() {
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
    • 准备dao模拟数据

    • @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);
          }
      
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37

    8.2 功能清单

    在这里插入图片描述

    8.3 具体功能:访问首页

    • 配置 view-controller

      <mvc:view-controller path="/" view-name="index"/>
      
      • 1
    • 创建页面

      <a th:href="@{/employee}">查询所有的员工信息a>
      
      • 1

    8.4 具体功能:查询所有员工数据

    • 控制器方法

      @RequestMapping(value = "/employee",method = RequestMethod.GET)
        public String getEmployeeList(Model model){
          Collection<Employee> employeeList = employeeDao.getAll();
          model.addAttribute("employeeList",employeeList);
          return "employee_list";
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • 创建 employee_list.html

      DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
        <meta charset="UTF-8">
        <title>Employee Infotitle>
      head>
      <body>
      <div id="app">
        <table>
          <tr>
            <th colspan="5">employee listth>
          tr>
          <tr>
            <th>idth>
            <th>lastNameth>
            <th>emailth>
            <th>genderth>
            <th>options(<a th:href="@{/to/add}">adda>th>
          tr>
          <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}}">deletea>
              <a th:href="@{'/employee/'+${employee.id}}">updatea>
            td>
          tr>
        table>
        <form method="post">
          <input type="hidden" name="_method" value="delete">
        form>
      div>
      body>
      html>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36

    8.5 具体功能:删除

    • 创建处理 delete 请求方式的表单

       
      <form id="delete_form" method="post"> 
       
      <input type="hidden" name="_method" value="delete"/> 
      form>
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • 引入vue.js

      <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
      
      • 1
    • 删除超链接

      <a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">deletea>
      
      • 1
    • 通过vue处理点击事件

      
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    • 控制器方法

      @RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
        public String deleteEmployee(@PathVariable("id") Integer id){
          employeeDao.delete(id);
          return "redirect:/employee";
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    8.6 具体功能:跳转到添加数据页面

    • 配置 view-controller

      <mvc:view-controller path="/to/add" view-name="employee_add">mvc:view-controller>
      
      • 1
    • 创建 employee_add.html

      DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
        <meta charset="UTF-8">
        <title>add employeetitle>
        <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
      head>
      <body>
      <form th:action="@{/employee}" method="post">
        <table>
          <tr>
            <th colspan="2">add employeeth>
          tr>
          <tr>
            <td>lastNametd>
            <td>
              <input type="text" name="lastName">
            td>
          tr>
          <tr>
            <td>emailtd>
            <td>
              <input type="text" name="email">
            td>
          tr>
          <tr>
            <td>gendertd>
            <td>
              <input type="radio" name="gender" value="1">male
              <input type="radio" name="gender" value="0">female
            td>
          tr>
          <tr>
            <td colspan="2">
              <input type="submit" value="add">
            td>
          tr>
        table>
      form>
      body>
      html>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41

    8.7 具体功能:执行保存

    • 控制器方法

      @RequestMapping(value = "/employee",method = RequestMethod.POST)
        public String addEmployee(Employee employee){
          employeeDao.save(employee);
          return "redirect:/employee";
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    8.8 具体功能:跳转到更新数据页面

    • 修改超链接

      <a th:href="@{'/employee/'+${employee.id}}">updatea>
      
      • 1
    • 控制器方法

      @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
        public String toUpdate(@PathVariable("id") Integer id,Model model){
          Employee employee = employeeDao.get(id);
          model.addAttribute("employee", employee);
          return "employee_update";
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • 创建 employee_update.html

      DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
        <meta charset="UTF-8">
        <title>update employeetitle>
        <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
      head>
      <body>
      <form th:action="@{/employee}" method="post">
        <input type="hidden" name="_method" value="put">
        <input type="hidden" name="id" th:value="${employee.id}">
        <table>
          <tr>
            <th colspan="2">update employeeth>
          tr>
          <tr>
            <td>lastNametd>
            <td>
              <input type="text" name="lastName" th:value="${employee.lastName}">
            td>
          tr>
          <tr>
            <td>emailtd>
            <td>
              <input type="text" name="email" th:value="${employee.email}">
            td>
          tr>
          <tr>
            <td>gendertd>
            <td>
              <input type="radio" name="gender" value="1" th:field="${employee.gender}">male
              <input type="radio" name="gender" value="0" th:field="${employee.gender}">female
            td>
          tr>
          <tr>
            <td colspan="2">
              <input type="submit" value="update">
            td>
          tr>
        table>
      form>
      body>
      html>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43

    8.9 具体功能:执行更新

    • 控制器方法

      @RequestMapping(value = "/employee",method = RequestMethod.PUT)
        public String updateEmployee(Employee employee){
          employeeDao.save(employee);
          return "redirect:/employee";
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    九、SpringMVC 处理ajax请求

    9.1 @RequestBody

    @RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值。

     
    <form th:action="@{/test/RequestBody}" method="post"> 
    用户名:<input type="text" name="username"><br> 
    密码:<input type="password" name="password"><br> 
    <input type="submit"> 
    form>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    @RequestMapping("/test/RequestBody") 
    public String testRequestBody(@RequestBody String requestBody){ 
    System.out.println("requestBody:"+requestBody); 
    return "success"; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出结果:requestBody:username=admin&password=123456

    9.2 @RequestBody获取json格式的请求参数

    在使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:

    1、name=value&name=value…,此时的请求参数可以通过request.getParameter()获取,对应SpringMVC中,可以直接通过控制器方法的形参获取此类请求参数

    2、{key:value,key:value,…},此时无法通过request.getParameter()获取,之前我们使用操作json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集合。在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将此类请求参数转换为java对象

    使用@RequestBody获取json格式的请求参数的条件:

    • 导入jackson的依赖

      <dependency> 
      <groupId>com.fasterxml.jackson.coregroupId> 
      <artifactId>jackson-databindartifactId> 
      <version>2.12.1version> 
      dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • SpringMVC的配置文件中设置开启mvc的注解驱动

       <mvc:annotation-driven />
      
      • 1
    • 在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参数,并使用@RequestBody注解标识

      var vue = new Vue({
          el:"#app",
          methods:{
            testAjax(){
              axios.post(
                  "/springmvcajax/test/ajax?id=1001",
                  {username:"admin",password:"123456"}
              ).then(response=>{
                console.log(response.data);
              });
            },
            testRequestBody(){
              axios.post(
                  "/springmvcajax/test/RequestBody/json",
                  {username:"admin",password:"123456",age:23,gender:"男"}
              ).then(response=>{
                console.log(response.data);
              });
            }
          }
        });
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • @RequestMapping("/test/RequestBody/json")
        public void testRequestBody(@RequestBody User user, HttpServletResponse response) throws IOException {
          System.out.println("user:"+user);
          response.getWriter().write("hello,RequestBody");
        }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    9.3 @ResponseBody

    @ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

    @RequestMapping("/test/ResponseBody")
      @ResponseBody
      public String testResponseBody(){
        return "success";
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    9.4 @ResponseBody响应浏览器json数据

    服务器处理ajax请求之后,大多数情况都需要向浏览器响应一个java对象,此时必须将java对象转换为json字符串才可以响应到浏览器,之前我们使用操作json数据的jar包gson或jackson将java对象转换为json字符串。在SpringMVC中,我们可以直接使用@ResponseBody注解实现此功能

    @ResponseBody响应浏览器json数据的条件:

    • 导入jackson的依赖

    • SpringMVC的配置文件中设置开启mvc的注解驱动

    • 使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器

    • testResponseBody(){
              axios.post("/springmvcajax/test/ResponseBody/json").then(response=>{
                console.log(response.data);
              });
            }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • @ResponseBody
        public List<User> testResponseBodyJson(){
          System.out.println("11111111111111111111111");
          User user1 = new User(1001, "admin1", "123456", 20, "男");
          User user2 = new User(1002, "admin2", "123456", 20, "男");
          User user3 = new User(1003, "admin3", "123456", 20, "男");
          List<User> list = Arrays.asList(user1, user2, user3);
          return list;
        }
      //响应浏览器实体类对象 
      @RequestMapping("/test/ResponseBody/json") 
      @ResponseBody 
      public User testResponseBody(){ 
          return user; 
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

    9.5 @RestController 注解

    @RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解

    十、文件上传和下载

    10.1 文件下载

    ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文使用ResponseEntity实现下载文件的功能

    @RequestMapping("/test/down")
        public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
            //获取ServletContext对象
            ServletContext servletContext = session.getServletContext();
            //获取服务器中文件的真实路径
            String realPath = servletContext.getRealPath("img");
            realPath = realPath + File.separator + "1.jpg";
            //创建输入流
            InputStream is = new FileInputStream(realPath);
            //创建字节数组,is.available()获取输入流所对应文件的字节数
            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;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    10.2 文件上传

    文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”,SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

    上传步骤:

    ①添加依赖:

    
        <dependency>
          <groupId>commons-fileuploadgroupId>
          <artifactId>commons-fileuploadartifactId>
          <version>1.3.1version>
        dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ②在SpringMVC的配置文件中添加配置:

     
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> bean>
    
    • 1
    • 2

    ③控制器方法:

    @RequestMapping("/test/up")
        public String testUp(MultipartFile photo, HttpSession session) throws IOException {
            //获取上传的文件的文件名
            String fileName = photo.getOriginalFilename();
            //获取上传的文件的后缀名
            String hzName = fileName.substring(fileName.lastIndexOf("."));
            //获取uuid
            String uuid = UUID.randomUUID().toString();
            //拼接一个新的文件名
            fileName = uuid + hzName;
            //获取ServletContext对象
            ServletContext servletContext = session.getServletContext();
            //获取当前工程下photo目录的真实路径
            String photoPath = servletContext.getRealPath("photo");
            //创建photoPath所对应的File对象
            File file = new File(photoPath);
            //判断file所对应目录是否存在
            if(!file.exists()){
                file.mkdir();
            }
            String finalPath = photoPath + File.separator + fileName;
            //上传文件
            photo.transferTo(new File(finalPath));
            return "success";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    十一、拦截器

    11.1 拦截器的配置

    SpringMVC中的拦截器用于拦截控制器方法的执行

    SpringMVC中的拦截器需要实现HandlerInterceptor

    SpringMVC的拦截器必须在SpringMVC的配置文件中进行配置:

    <mvc:interceptors>
            <bean class="com.cgg.Intercepet.FirstIntercept">bean>
        mvc:interceptors>
    
    • 1
    • 2
    • 3

    11.2 拦截器的三个抽象方法

    SpringMVC中的拦截器有三个抽象方法:

    preHandle:控制器方法执行之前执行preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法;返回false表示拦截,即不调用控制器方法

    postHandle:控制器方法执行之后执行postHandle()

    afterCompletion:处理完视图和模型数据,渲染视图完毕之后执行afterCompletion()

    11.3 多个拦截器的执行顺序

    若每个拦截器的preHandle()都返回true

    ​ 此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关:preHandle()会按照配置的顺序执行,而postHandle()和afterCompletion()会按照配置的反序执行

    若某个拦截器的preHandle()返回了false

    ​ preHandle()返回false和它之前的拦截器的preHandle()都会执行,postHandle()都不执行,返回false的拦截器之前的拦截器的afterCompletion()会执行

    十二、异常处理器

    12.1 基于配置的异常处理

    SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver、HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver

    SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
        
                    <prop key="java.lang.ArithmeticException">errorprop>
                props>
            property>
        
            <property name="exceptionAttribute" value="ex">property>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    12.2 基于注解的异常处理

    @ControllerAdvice
    public class ErrorController {
      @ExceptionHandler(ArithmeticException.class)
      public String HandleError(Throwable ex, Model model){
        //ex表示控制器方法所出现的异常
        model.addAttribute("ex", ex);
        return "error";
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    xtrabackup备份 脚本
    Linux下使用Nginx搭建Rtmp流媒体服务器,实现视频直播功能
    SWT/ANR问题--Deadlock
    Celery笔记三之task和task的调用
    Java中使用redis的bitMap实现签到功能
    通过pyserial操作串口
    # 数据结构
    前端入门学习笔记三十六
    windows 查看本地安装证书情况
    MIPI CSI接口调试方法: data rate计算
  • 原文地址:https://blog.csdn.net/weixin_42200347/article/details/126436712