3. SpringMVC

3.1 了解SpringMVC

  • 概述

    • SpringMVC技术与Servlet技术功能等同,均属于web层开发技术
  • 学习路线
    • 请求与响应
    • REST分割
    • SSM整合
    • 拦截器
  • 目标:
    • 掌握基于SpringMVC获取请求参数与响应json数据操作
    • 熟练应用基于REST风格的请求路径设置与参数传递
    • 能够根据实际业务建立前后端开发通信协议并进行实现
    • 基于SSM整合技术开发任意业务模块功能

3.2 SpringMVC简介

3.2.1 SpringMVC概述

  • SpringMVC是一种基于Java实现MVC模型轻量级Web框架
  • 优点
    • 使用简单,开发便捷(相比于Servlet)
    • 灵活性强

3.2.2 SpringMVC入门案例

  • 使用SpringMVC需要先导入SpringMVC坐标与Servlet坐标

    1. <dependencies>
    2. <!--1.导入坐标-->
    3. <!--Servlet-->
    4. <dependency>
    5. <groupId>javax.servlet</groupId>
    6. <artifactId>javax.servlet-api</artifactId>
    7. <version>3.1.0</version>
    8. <!--由于可能会和tomcat插件冲突,添加范围provided-->
    9. <scope>provided</scope>
    10. </dependency>
    11. <!--SpringMVC-->
    12. <dependency>
    13. <groupId>org.springframework</groupId>
    14. <artifactId>spring-webmvc</artifactId>
    15. <version>5.2.10.RELEASE</version>
    16. </dependency>
    17. </dependencies>
  • 创建SpringMVC控制器类(等同于Servlet功能)

    1. //2.定义controller
    2. //2.1 使用@Controller定义bean
    3. @Controller
    4. public class UserController {
    5. //2.2 设置当前操作的访问路径
    6. @RequestMapping("/save")
    7. //2.3 设置当前操作的返回值类型
    8. @ResponseBody
    9. public String save(){
    10. System.out.println("user save..");
    11. return "{'module':'Spring MVC'}";
    12. }
    13. }
  • 初始化SpringMVC环境(同Spring环境),设定SpringMVC加载对应Bean

    1. //3.创建SpringMVC的配置文件,加载Controller对应的bean
    2. @Configuration
    3. @ComponentScan("com.mark.controller")
    4. public class SpringMVC {
    5. }
  • 初始化Servlet容器,加载SpringMVC环境,并设置SpringMVC技术处理的请求

    1. //4.定义一个Servlet容器启动的配置类,在里面加载Spring的配置,告知服务器使用SpringMVC
    2. public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer {
    3. //加载SpringMVC容器配置
    4. @Override
    5. protected WebApplicationContext createServletApplicationContext() {
    6. //原来Spring获取容器:ApplicationContext ctx= new AnnotationConfigApplicationContext()
    7. //获取容器
    8. AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    9. //注册配置
    10. ctx.register(SpringMVCConfig.class);
    11. return ctx;
    12. }
    13. //设置哪些请求归属SpringMVC处理
    14. @Override
    15. protected String[] getServletMappings() {
    16. //所有请求都归SpringMVC处理
    17. return new String[]{"/"};
    18. }
    19. //加载Spring容器配置
    20. @Override
    21. protected WebApplicationContext createRootApplicationContext() {
    22. return null;
    23. }
    24. }

    注意:此时web.xml可以删除,之后配置tomcat服务器

    1. <build>
    2. <plugins>
    3. <plugin>
    4. <groupId>org.apache.tomcat.maven</groupId>
    5. <artifactId>tomcat7-maven-plugin</artifactId>
    6. <version>2.1</version>
    7. <configuration>
    8. <port>80</port>
    9. <path>/</path>
    10. </configuration>
    11. </plugin>
    12. </plugins>
    13. </build>

    这时浏览器访问http://localhost/save 即可看到结果 {'module':'Spring MVC'}

3.2.3 注解介绍

  • @Controller

    • 类型:类注解

    • 位置:SpringMVC控制器类定义上方

    • 作用:设定SpringMVC的核心控制器bean

    • 范例:

      1. @Controller
      2. public class UserController {
      3. }
  • @RequestMapping

    • 类型:方法注解

    • 位置:SpringMVC控制器方法定义上方

    • 作用:设置当前控制器方法请求访问路径

    • 范例:

      1. @RequestMapping("/save")
      2. public void save(){
      3. System.out.println("user save ...");
      4. }
    • 相关属性

      • value(默认):请求访问路径
  • @ResponseBody

    • 类型:方法注解

    • 位置:SpringMVC控制器方法定义上方

    • 作用:设置当前控制器方法响应内容为当前返回值,无需解析

    • 范例

      1. @RequestMapping("/save")
      2. @ResponseBody
      3. public String save(){
      4. System.out.println("user save ...");
      5. return "{'info':'springmvc'}";
      6. }

3.2.4 SpringMVC入门程序开发总结(1+N)

  • 一次性工作

    • 创建工程,设置服务器,加载工程
    • 导入坐标
    • 创建web容器启动类,加载SpringMVC配置,并设置SpringMVC请求拦截路径
    • SpringMVC核心配置类(设置配置类,扫描controller包,加载Controller控制器bean)
  • 多次工作
    • 定义处理请求的控制器类(@Controller)
    • 定义处理请求的控制器方法,并配置映射路径(@RequestMapping)与返回json数据(@ResponseBody)

3.2.5 Servlet配置类详解

  • AbstractDispatcherServletInitializer类是SpringMVC提供的快速初始化Web3.0容器的抽象类

  • AbstractDispatcherServletInitializer提供三个接口方法供用户实现

    • createServletApplicationContext()方法:

      创建Servlet容器时,加载SpringMVC对应的bean并放入WebApplicationContext对象范围中,而WebApplicationContext的作用范围为ServletContext范围,即整个web容器范围

      1. @Override
      2. protected WebApplicationContext createServletApplicationContext() {
      3. //原来Spring获取容器:ApplicationContext ctx= new AnnotationConfigApplicationContext()
      4. //获取容器
      5. AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
      6. //注册配置
      7. ctx.register(SpringMVCConfig.class);
      8. return ctx;
      9. }
    • getServletMappings()方法:

      设定SpringMVC对应的请求映射路径,设置为/表示拦截所有请求,任意请求都将转入到SpringMVC进行处理

      1. @Override
      2. protected String[] getServletMappings() {
      3. //所有请求都归SpringMVC处理
      4. return new String[]{"/"};
      5. }
    • createRootApplicationContext()方法:

      如果创建Servlet容器时需要加载非SpringMVC对应的bean,使用当前方法进行,使用方式同createServletApplicationContext()。如果没有返回null即可

      1. @Override
      2. protected WebApplicationContext createRootApplicationContext() {
      3. AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
      4. ctx.register(SpringConfig.class);
      5. return ctx;
      6. }

3.2.6 入门案例工作流程分析

  • 启动服务器初始化过程

    • 服务器启动,执行ServletContainersInitConfig类,初始化web容器
    • 执行createServletApplicationContext方法,创建了WebApplicationContext对象
    • 加载SpringMvcConfig
    • 执行@ComponentScan加载对应的bean
    • 加载UserController,每个@RequestMapping的名称对应一个具体的方法
    • 执行getServletMappings方法,定义所有的请求都通过SpringMVC

  • 单次请求过程

    • 发送请求localhost/save
    • web容器发现所有请求都经过SpringMVC,将请求交给SpringMVC处理
    • 解析请求路径/save
    • 由/save匹配执行对应的方法save()
    • 执行save()
    • 检测到有@ResponseBody直接将save()方法的返回值作为响应求体返回给请求方

3.2.7 Controller加载控制与业务bena加载控制

  • 不同的bean由不同的容器管理

    • SpringMVC相关的bean:表现层bean
    • Spring控制的bean:
      • 业务bean(Service)
      • 功能bean(DataSource等)
  • 因为功能不同,如何避免Spring错误的加载到SpringMVC的bean?

    • 加载Spring控制的bean的时候排除掉SpringMVC控制的bean
  • 不同bean的加载控制:

    • SpringMVC相关bean加载控制

      • SpringMVC加载的bean对应均在com.mark.controller包内
    • Spring相关bean加载控制

      • 方式一:Spring加载的bean设定扫描范围为com.mark,排除掉controller包内的bean

        1. @Configuration
        2. //@ComponentScan({"com.mark.service","com.mark.dao"})
        3. //扫描com.mark下的所有,但是按照注解排除掉使用了Controller注解的bean
        4. @ComponentScan(value = "com.mark",
        5. excludeFilters = @ComponentScan.Filter(
        6. type = FilterType.ANNOTATION,
        7. classes = Controller.class
        8. )
        9. )
        10. public class SpringConfig {
        11. }
      • 方式二:Spring加载的bean设定扫描范围为精准范围,例如service包、dao包

        1. @Configuration
        2. @ComponentScan({"com.mark.service","com.mark.dao"})
        3. public class SpringConfig {
        4. }
      • 方式三:不区分Spring与SpringMVC的环境,加载到同一个环境

  • 相关注解介绍

    • @ComponentScan

      • 类型:类注解

      • 范例:

        1. @Configuration
        2. @ComponentScan(value = "com.mark",
        3. excludeFilters = @ComponentScan.Filter(
        4. type = FilterType.ANNOTATION,
        5. classes = Controller.class
        6. )
        7. )
        8. public class SpringConfig {
        9. }
      • 属性

        • excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)与具体项(classes)
        • includeFilters:加载指定的bean,需要指定类别(type)与具体项(classes)
  • 配置Web容器启动类改进、简化:继承AbstractAnnotationConfigDispatcherServletInitializer

    1. public class ServletContainerInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    2. @Override
    3. protected Class<?>[] getRootConfigClasses() {
    4. return new Class[]{SpringConfig.class};
    5. }
    6. @Override
    7. protected Class<?>[] getServletConfigClasses() {
    8. return new Class[]{SpringMVCConfig.class};
    9. }
    10. @Override
    11. protected String[] getServletMappings() {
    12. return new String[]{"/"};
    13. }
    14. }

3.2.8 PostMan

  • PostMan简介

    • PostMan是一款功能强大的网页调试发送网页HTTP请求的Chrome插件
    • 作用:常用于进行接口测试
    • 特征:
      • 简单
      • 实用
      • 美观
      • 大方
  • PostMan基础操作
    • 注册登录
    • 创建/进入工作空间
    • 发起请求测试结果

3.3 请求与响应

3.3.1 请求映射路径

  • 思考:

    • 团队多人开发,每个人设置不同的请求路径,冲突如何解决?

      • 设置模块名作为请求路径前缀

        1. @Controller
        2. public class BookController {
        3. @RequestMapping("/book/save")
        4. @ResponseBody
        5. public String save(){
        6. System.out.println("book save ...");
        7. return "{'module':'book save'}";
        8. }
        9. }
        1. @Controller
        2. //请求路径前缀
        3. @RequestMapping("/user")
        4. public class UserController {
        5. @RequestMapping("/save")
        6. @ResponseBody
        7. public String save() {
        8. System.out.println("user save ...");
        9. return "{'module':'user save'}";
        10. }
        11. @RequestMapping("/delete")
        12. @ResponseBody
        13. public String delete() {
        14. System.out.println("user delete ...");
        15. return "{'module':'user delete'}";
        16. }
        17. }
  • 注解介绍

    • 名称:@RequestMapping

    • 类型:方法注解 类注解

    • 位置:SpringMVC控制器方法定义上方

    • 作用:设置当前控制器方法请求访问路径,如果设置在类上统一设置当前控制器方法请求访问路径前缀

    • 范例:

      1. @Controller
      2. @RequestMapping("/book")
      3. public class BookController {
      4. @RequestMapping("/save")
      5. @ResponseBody
      6. public String save() {
      7. System.out.println("book save ...");
      8. return "{'module':'book save'}";
      9. }
      10. }
    • 属性

      • value(默认):请求访问路径,或访问路径前缀

3.3.2 各种请求参数传递

  • 请求方式

    • Get请求
    • Post请求
  • Get请求参数

    • 普通参数:url地址传参,地址参数名与形参变量名相同定义形参即可接收参数

      1. @Controller
      2. @RequestMapping("/user")
      3. public class UserController {
      4. //普通参数
      5. @RequestMapping("/commonParam")
      6. @ResponseBody
      7. public String commonParam(String name,int age){
      8. System.out.println("普通参数传递 name ==>"+name);
      9. System.out.println("普通参数传递 age ==>"+age);
      10. return "{'module':'common param'}";
      11. }
      12. }

      请求参数名与形参变量名不同,使用@RequestParam绑定参数关系

      1. @Controller
      2. @RequestMapping("/user")
      3. public class UserController {
      4. //普通参数
      5. @RequestMapping("/commonParam")
      6. @ResponseBody
      7. public String commonParam(@RequestParam("name") String username,int age){
      8. System.out.println("普通参数传递 name ==>"+username);
      9. System.out.println("普通参数传递 age ==>"+age);
      10. return "{'module':'common param'}";
      11. }
      12. }

      这时发送请求的名字为name,username可以接收到name的值

    • POJO参数请求参数名与形参对象属性名相同定义POJO类型形参即可接收参数

      1. //POJO参数
      2. @RequestMapping("/pojoParam")
      3. @ResponseBody
      4. public String pojoParam(User user){
      5. System.out.println("POJO参数传递 user ==>"+user);
      6. return "{'module':'pojo param'}";
      7. }

      嵌套POJO参数:POJO对象中包含POJO对象

      请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套POJO属性参数

      1. public class User {
      2. private String name;
      3. private int age;
      4. private Address address;
      5. }
      1. public class Address {
      2. private String province;
      3. private String city;
      4. }

    • 数组参数:请求参数名与形参数组名相同且请求参数为多个,定义数组类型形参即可接收参数

      1. @RequestMapping("arrayParam")
      2. @ResponseBody
      3. public String arrayParam(String[] hobby){
      4. System.out.println(("数组参数传递 hobby ==> "+ Arrays.toString(hobby)));
      5. return "{'module':'array param'}";
      6. }

    • 集合保存普通参数:请求参数名与形参集合对象名相同且请求参数为多个,@RequestParam绑定参数关系

      1. @RequestMapping("listParam")
      2. @ResponseBody
      3. public String listParam(@RequestParam List<String> hobby){
      4. System.out.println("集合参数传递 hobby ==> "+ hobby);
      5. return "{'module':'list param'}";
      6. }
  • Post请求参数

    • 普通参数:form表单post请求传参,表单参数名与形参变量名相同,定义形参即可接收参数,代码与Get相同。

    • Post请求中文乱码处理

      在Servlet启动类配置中添加过滤器

      1. //乱码处理
      2. @Override
      3. protected Filter[] getServletFilters() {
      4. CharacterEncodingFilter filter = new CharacterEncodingFilter();
      5. filter.setEncoding("UTF-8");
      6. return new Filter[]{filter};
      7. }
    • 其他类型与Get方式规则一样

3.3.3 响应json数据

  • 添加json数据转换相关坐标

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.core</groupId>
    3. <artifactId>jackson-databind</artifactId>
    4. <version>2.9.0</version>
    5. </dependency>
  • 设置发送json数据(请求body中添加json数据)

  • 开启json数据格式的自动转换,在配置类中开启@EnableWebMvc

    1. @Configuration
    2. @ComponentScan("com.mark.controller")
    3. @EnableWebMvc
    4. public class SpringMvcConfig {
    5. }
  • 使用@RequestBody注解将外部传递的json数组数据映射到形参的集合对象中作为数据

    集合类数据:

    1. @RequestMapping("/listParamForJson")
    2. @ResponseBody
    3. public String listParamForJson(@RequestBody List<String> hobby){
    4. System.out.println("list common(json)参数传递 list ==> "+hobby);
    5. return "{'module':'list common for json param'}";
    6. }

    POJO类数据:json数据与形参对象属性名相同,定义POJO类型形参即可接收参数

    1. @RequestMapping("/pojoParamForJson")
    2. @ResponseBody
    3. public String pojoParamForJson(@RequestBody User user){
    4. System.out.println("pojo(json)参数传递 user ==> "+user);
    5. return "{'module':'pojo for json param'}";
    6. }

    POJO集合参数

    1. @RequestMapping("/listPojoParamForJson")
    2. @ResponseBody
    3. public String listPojoParamForJson(@RequestBody List<User> list){
    4. System.out.println("list pojo(json)参数传递 list ==> "+list);
    5. return "{'module':'list pojo for json param'}";
    6. }

3.3.4 日期类型参数传递

  • 日期类型数据基于不同系统 格式也不尽相同

    • 2000-04-18
    • 2000/04/18
    • 04/18/2000
  • 接收形参时,根据不同的日期格式设置不同的接收方式,默认格式:yyyy/MM/dd。实用@DateTimeFormat设定日期时间型数据格式,属性:pattern = 日期时间格式字符串
  1. @RequestMapping("/dataParam")
  2. @ResponseBody
  3. public String dataParam(Date date,
  4. @DateTimeFormat(pattern="yyyy-MM-dd") Date date1,
  5. @DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss") Date date2){
  6. System.out.println("参数传递 date ==> "+date);
  7. System.out.println("参数传递 date1(yyyy-MM-dd) ==> "+date1);
  8. System.out.println("参数传递 date2(yyyy/MM/dd HH:mm:ss) ==> "+date2);
  9. return "{'module':'data param'}";
  10. }
  11. /*
  12. 参数传递 date ==> Tue Apr 18 00:00:00 CST 2000
  13. 参数传递 date1(yyyy-MM-dd) ==> Tue Apr 18 00:00:00 CST 2000
  14. 参数传递 date2(yyyy/MM/dd HH:mm:ss) ==> Tue Apr 18 00:05:20 CST 2000
  15. */

3.3.5 响应

  • 响应页面(了解)

    返回值为String类型,设置返回值为页面名称,即可实现页面跳转

    1. @RequestMapping("/toJumpPage")
    2. public String toJumpPage(){
    3. System.out.println("跳转页面");
    4. return "page.jsp";
    5. }
  • 响应数据

    • 文本数据(了解)

      返回值为String类型,设置返回值为任意字符串信息,即可实现返回指定字符串信息,需要依赖@ResponseBody注解

      1. @RequestMapping("/toText")
      2. @ResponseBody
      3. public String toText(){
      4. System.out.println("返回纯文本数据");
      5. return "response text";
      6. }
    • json数据(重点)

      • 响应POJO对象

        返回值为实体类对象,设置返回值为实体类类型,即可实现返回对应对象的json数据,需要依赖@ResponseBody注解和@EnableWebMvc注解

        1. @RequestMapping("/toJsonPOJO")
        2. @ResponseBody
        3. public User toJsonPOJO(){
        4. System.out.println("返回json对象数据");
        5. User user = new User();
        6. user.setName("itcast");
        7. user.setAge(15);
        8. return user;
        9. }
      • 响应POJO集合对象

        返回值为集合对象,设置返回值为集合类型,即可实现返回对应集合的json数组数据,需要依赖@ResponseBody注解和@EnableWebMvc注解

        1. @RequestMapping("/toJsonList")
        2. @ResponseBody
        3. public List<User> toJsonList(){
        4. System.out.println("返回json集合数据");
        5. User user1 = new User();
        6. user1.setName("传智播客");
        7. user1.setAge(15);
        8. User user2 = new User();
        9. user2.setName("黑马程序员");
        10. user2.setAge(12);
        11. List<User> userList = new ArrayList<User>();
        12. userList.add(user1);
        13. userList.add(user2);
        14. return userList;
        15. }

3.4 REST风格

3.4.1 REST风格简介

3.4.2 RESTful入门案例

  • 步骤:

    • 修改@RequestMapping路径为模块名称复数

      @RequestMapping("/users")

    • 设置请求行为(http请求动作)

      @RequestMapping(value = "/users",method = RequestMethod.POST)

    • 设定请求参数(路径变量)

      1. @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
      2. @ResponseBody
      3. public String delete(@PathVariable Integer id) {
      4. System.out.println("user delete..." + id);
      5. return "{'module':'user delete'}";
      6. }
  • 实现:

    1. @Controller
    2. public class UserController {
    3. //设置当前请求方法为POST,表示REST风格中的添加操作
    4. @RequestMapping(value = "/users",method = RequestMethod.POST)
    5. @ResponseBody
    6. public String save(@RequestBody User user) {
    7. System.out.println("user save..."+user);
    8. return "{'module':'user save'}";
    9. }
    10. //设置当前请求方法为DELETE,表示REST风格中的删除操作
    11. //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
    12. @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    13. @ResponseBody
    14. public String delete(@PathVariable Integer id) {
    15. System.out.println("user delete..." + id);
    16. return "{'module':'user delete'}";
    17. }
    18. //设置当前请求方法为PUT,表示REST风格中的修改操作
    19. @RequestMapping(value = "/users",method = RequestMethod.PUT)
    20. @ResponseBody
    21. public String update(@RequestBody User user) {
    22. System.out.println("user update..." + user);
    23. return "{'module':'user update'}";
    24. }
    25. //设置当前请求方法为GET,表示REST风格中的查询操作
    26. //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
    27. @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    28. @ResponseBody
    29. public String getById(@PathVariable Integer id) {
    30. System.out.println("user getById..." + id);
    31. return "{'module':'user getById'}";
    32. }
    33. //设置当前请求方法为GET,表示REST风格中的查询操作
    34. @RequestMapping( value = "/users",method = RequestMethod.GET)
    35. @ResponseBody
    36. public String getAll() {
    37. System.out.println("user getAll...");
    38. return "{'module':'user getAll'}";
    39. }
    40. }
  • POST、DELETE、PUT、GET分别对应增删改查

  • @PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同

  • 截至目前,见到过的接收参数注解有三种

    • @RequestParam:用于接收url地址传参或表单传参 绑定参数
    • @RequestBody:用于接收json数据映射到形参中作为数据
    • @PathVariable:用于接收路径参数,@RequestMapping中使用{参数名称}描述路径参数
  • 应用

    • 后期开发中,发送请求参数超过1个时,以json格式为主,@RequestBody应用较广
    • 采用RESTful进行开发,当参数数量较少时,例如1个,可以采用@PathVariable接收请求路径变量,通常用于传递id值
    • 如果发送非json格式数据,选用@RequestParam接收请求参数

3.4.3 REST快速开发

在上面的案例中,有很多重复编写的代码

将每个方法的value中的模块名提取到类前

将每个方法的@ResponseBody提取到类前

类的@Controller和@ResponseBody可以合并成@RestController

每个方法@PostMapping中的请求行为设置可以用对应的@xxxMapping注解替换

  1. //@Controller
  2. //@ResponseBody配置在类上可以简化配置,表示设置当前每个方法的返回值都作为响应体
  3. //@ResponseBody
  4. @RestController//使用@RestController注解替换@Controller与@ResponseBody注解,简化书写
  5. @RequestMapping("/books")
  6. public class BookController {
  7. //@RequestMapping( method = RequestMethod.POST)
  8. @PostMapping//使用@PostMapping简化Post请求方法对应的映射配置
  9. public String save(@RequestBody Book book) {
  10. System.out.println("book save..." + book);
  11. return "{'module':'book save'}";
  12. }
  13. //@RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)
  14. @DeleteMapping("/{id}")//使用@DeleteMapping简化DELETE请求方法对应的映射配置
  15. public String delete(@PathVariable Integer id) {
  16. System.out.println("book delete..." + id);
  17. return "{'module':'book delete'}";
  18. }
  19. //@RequestMapping(method = RequestMethod.PUT)
  20. @PutMapping//使用@PutMapping简化Put请求方法对应的映射配置
  21. public String update(@RequestBody Book book) {
  22. System.out.println("book update..." + book);
  23. return "{'module':'book update'}";
  24. }
  25. //@RequestMapping(value = "/{id}" ,method = RequestMethod.GET)
  26. @GetMapping("/{id}")//使用@GetMapping简化GET请求方法对应的映射配置
  27. public String getById(@PathVariable Integer id) {
  28. System.out.println("book getById..." + id);
  29. return "{'module':'book getById'}";
  30. }
  31. //@RequestMapping(method = RequestMethod.GET)
  32. @GetMapping//使用@GetMapping简化GET请求方法对应的映射配置
  33. public String getAll() {
  34. System.out.println("book getAll...");
  35. return "{'module':'book getAll'}";
  36. }
  37. }

3.4.4 案例:基于RESTful页面数据交互

POSTMan实现后台接口开发

  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4. /**
  5. * 保存新增数据
  6. * @param book
  7. * @return
  8. */
  9. @PostMapping
  10. public String save(@RequestBody Book book) {
  11. System.out.println("book save" + book);
  12. return "{'module':'book save success'}";
  13. }
  14. /**
  15. * 获取全部
  16. * @return
  17. */
  18. @GetMapping
  19. public List<Book> getAll() {
  20. Book book1 = new Book();
  21. book1.setType("计算机");
  22. book1.setName("SpringMVC入门");
  23. book1.setDescription("我是小白");
  24. Book book2 = new Book();
  25. book2.setType("计算机");
  26. book2.setName("SpringMVC实战");
  27. book2.setDescription("我是大佬");
  28. List<Book> list = new ArrayList<Book>();
  29. list.add(book1);
  30. list.add(book2);
  31. return list;
  32. }
  33. }

实现页面数据交互:

由于在访问静态资源页面时,SpringMVC的Sevlet容器配置中设置了protected String[] getServletMappings() { return new String[]{"/"};}会拦截所有请求,导致无法打开页面

因此创建SpringMvcSupport配置类,设置对静态资源的访问放行

  1. @Configuration
  2. public class SpringMVCSupport extends WebMvcConfigurationSupport {
  3. @Override
  4. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  5. //当访问/pages/???的时候,不要走MVC,走/pages目录下的内容
  6. registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  7. registry.addResourceHandler("/css/**").addResourceLocations("/css/");
  8. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
  9. registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
  10. }
  11. }

前端页面通过异步提交访问后台控制器

  1. //添加
  2. saveBook() {
  3. axios.post("/books", this.formData).then((res) => {
  4. });
  5. },
  6. //主页列表查询
  7. getAll() {
  8. axios.get("/books").then((res) => {
  9. this.dataList = res.data;
  10. });
  11. },

3.5 SSM整合

3.5.1 整合配置

  • 创建工程

  • SSM整合

    • Spring

      • SpringConfig

        1. @Configuration
        2. @ComponentScan({"com.mark.service"})
        3. @PropertySource("classpath:jdbc.properties")
        4. @Import({JdbcConfig.class,MybatisConfig.class})
        5. public class SpringConfig {}
    • MyBatis

      • JdbcConfig

        1. public class JdbcConfig {
        2. @Value("${jdbc.driver}")
        3. private String driver;
        4. @Value("${jdbc.url}")
        5. private String url;
        6. @Value("${jdbc.username}")
        7. private String username;
        8. @Value("${jdbc.password}")
        9. private String password;
        10. @Bean
        11. public DataSource dataSource() {
        12. DruidDataSource dataSource = new DruidDataSource();
        13. dataSource.setDriverClassName(driver);
        14. dataSource.setUrl(url);
        15. dataSource.setUsername(username);
        16. dataSource.setPassword(password);
        17. return dataSource;
        18. }
        19. }
      • MyBatisConfig

        1. public class MybatisConfig {
        2. @Bean
        3. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        4. SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        5. factoryBean.setDataSource(dataSource);
        6. factoryBean.setTypeAliasesPackage("com.mark.domain");
        7. return factoryBean;
        8. }
        9. @Bean
        10. public MapperScannerConfigurer mapperScannerConfigurer() {
        11. MapperScannerConfigurer msc = new MapperScannerConfigurer();
        12. msc.setBasePackage("com.mark.dao");
        13. return msc;
        14. }
        15. }
      • jdbc.properties

        1. jdbc.driver=com.mysql.cj.jdbc.Driver
        2. jdbc.url=jdbc:mysql://localhost:3306/ssm_db
        3. jdbc.username=root
        4. jdbc.password=123
    • SpringMVC

      • SpringMVCConfig

        1. @Configuration
        2. @ComponentScan({"com.mark.controller","com.mark.config"})
        3. @EnableWebMvc
        4. public class SpringMvcConfig {}
      • ServletConfig

        1. public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
        2. @Override
        3. protected Class<?>[] getRootConfigClasses() {
        4. return new Class[]{SpringConfig.class};
        5. }
        6. @Override
        7. protected Class<?>[] getServletConfigClasses() {
        8. return new Class[]{SpringMvcConfig.class};
        9. }
        10. @Override
        11. protected String[] getServletMappings() {
        12. return new String[]{"/"};
        13. }
        14. @Override
        15. protected Filter[] getServletFilters() {
        16. CharacterEncodingFilter characterEncodingFilter =new CharacterEncodingFilter();
        17. characterEncodingFilter.setEncoding("UTF-8");
        18. return new Filter[]{characterEncodingFilter};
        19. }
        20. }
      • SpringMVCSupport

        1. @Configuration
        2. public class SpringMvcSupport extends WebMvcConfigurationSupport {
        3. @Override
        4. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        5. registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        6. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        7. registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        8. registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
        9. }
        10. }

3.5.2 功能模块开发

  • 表与实体类

    创建表:

    1. -- ----------------------------
    2. -- Table structure for tbl_book
    3. -- ----------------------------
    4. DROP TABLE IF EXISTS `tbl_book`;
    5. CREATE TABLE `tbl_book` (
    6. `id` int(11) NOT NULL AUTO_INCREMENT,
    7. `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    8. `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    9. `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    10. PRIMARY KEY (`id`) USING BTREE
    11. ) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    12. -- ----------------------------
    13. -- Records of tbl_book
    14. -- ----------------------------
    15. INSERT INTO `tbl_book` VALUES (1, '计算机理论', 'Spring实战 第5版', 'Spring入门经典教程,深入理解Spring原理技术内幕');
    16. INSERT INTO `tbl_book` VALUES (2, '计算机理论', 'Spring 5核心原理与30个类手写实战', '十年沉淀之作,手写Spring精华思想');
    17. INSERT INTO `tbl_book` VALUES (3, '计算机理论', 'Spring 5 设计模式', '深入Spring源码剖析Spring源码中蕴含的10大设计模式');
    18. INSERT INTO `tbl_book` VALUES (4, '计算机理论', 'Spring MVC+MyBatis开发从入门到项目实战', '全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手');
    19. INSERT INTO `tbl_book` VALUES (5, '计算机理论', '轻量级Java Web企业应用实战', '源码级剖析Spring框架,适合已掌握Java基础的读者');
    20. INSERT INTO `tbl_book` VALUES (6, '计算机理论', 'Java核心技术 卷I 基础知识(原书第11版)', 'Core Java 第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新');
    21. INSERT INTO `tbl_book` VALUES (7, '计算机理论', '深入理解Java虚拟机', '5个维度全面剖析JVM,大厂面试知识点全覆盖');
    22. INSERT INTO `tbl_book` VALUES (8, '计算机理论', 'Java编程思想(第4版)', 'Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉');
    23. INSERT INTO `tbl_book` VALUES (9, '计算机理论', '零基础学Java(全彩版)', '零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术');
    24. INSERT INTO `tbl_book` VALUES (10, '市场营销', '直播就该这么做:主播高效沟通实战指南', '李子柒、李佳琦、薇娅成长为网红的秘密都在书中');
    25. INSERT INTO `tbl_book` VALUES (11, '市场营销', '直播销讲实战一本通', '和秋叶一起学系列网络营销书籍');
    26. INSERT INTO `tbl_book` VALUES (12, '市场营销', '直播带货:淘宝、天猫直播从新手到高手', '一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');

    实体类:

    1. @Getter
    2. @Setter
    3. @ToString
    4. public class Book {
    5. private Integer id;
    6. private String type;
    7. private String name;
    8. private String description;
    9. }
  • 创建好所有的接口和实现类

  • dao(接口+自动代理实现)

    1. public interface BookDao {
    2. //@Insert("insert into tbl_book values (null,#{type},#{name},#{description})")
    3. //上面语句中type指的是Book类的属性名,id需要为null
    4. //下面语句中第一个type指的是表里的属性名 第二个type指的是Book类的属性名,不需要为id赋值
    5. /**
    6. * 保存
    7. * @param book
    8. */
    9. @Insert("insert into tbl_book (type, name, description) values (#{type}, #{name}, #{description})")
    10. public void save(Book book);
    11. /**
    12. * 修改/更新
    13. * @param book
    14. */
    15. @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    16. public void update(Book book);
    17. /**
    18. * 删除
    19. * @param id
    20. */
    21. @Delete("delete from tbl_book where id = #{id}")
    22. public void delete(Integer id);
    23. /**
    24. * 根据id获取book
    25. * @param id
    26. * @return
    27. */
    28. @Select("select id, type, name, description from tbl_book where id = #{id}")
    29. public Book getById(Integer id);
    30. /**
    31. * 获取所有book
    32. * @return
    33. */
    34. @Select("select id, type, name, description from tbl_book")
    35. public List<Book> getAll();
    36. }
  • service(接口+实体类)

    1. public interface BookService {
    2. /**
    3. * 保存
    4. * @param book
    5. */
    6. public boolean save(Book book);
    7. /**
    8. * 修改/更新
    9. * @param book
    10. */
    11. public boolean update(Book book);
    12. /**
    13. * 根据id删除
    14. * @param id
    15. */
    16. public boolean delete(Integer id);
    17. /**
    18. * 根据id查询
    19. * @param id
    20. * @return
    21. */
    22. public Book getById(Integer id);
    23. /**
    24. * 获取所有
    25. * @return
    26. */
    27. public List<Book> getAll();
    28. }
    1. @Service
    2. public class BookServiceImpl implements BookService {
    3. @Autowired
    4. private BookDao bookDao;
    5. @Override
    6. public boolean save(Book book) {
    7. bookDao.save(book);
    8. return true;
    9. }
    10. @Override
    11. public boolean update(Book book) {
    12. bookDao.update(book);
    13. return true;
    14. }
    15. @Override
    16. public boolean delete(Integer id) {
    17. bookDao.delete(id);
    18. return true;
    19. }
    20. @Override
    21. public Book getById(Integer id) {
    22. //Book book = bookDao.getById(id);
    23. //return book;
    24. return bookDao.getById(id);
    25. }
    26. @Override
    27. public List<Book> getAll() {
    28. return bookDao.getAll();
    29. }
    30. }
  • controller

    1. @RestController
    2. @RequestMapping("/books")
    3. public class BookController {
    4. @Autowired
    5. private BookService bookService;
    6. /**
    7. * 保存
    8. * @param book
    9. */
    10. @PostMapping
    11. public boolean save(@RequestBody Book book) {
    12. return bookService.save(book);
    13. }
    14. /**
    15. * 修改/更新
    16. * @param book
    17. */
    18. @PutMapping
    19. public boolean update(@RequestBody Book book) {
    20. return bookService.update(book);
    21. }
    22. /**
    23. * 根据id删除
    24. * @param id
    25. */
    26. @DeleteMapping("/{id}")
    27. public boolean delete(@PathVariable Integer id) {
    28. return bookService.delete(id);
    29. }
    30. /**
    31. * 根据id查询
    32. * @param id
    33. * @return
    34. */
    35. @GetMapping("/{id}")
    36. public Book getById(@PathVariable Integer id) {
    37. return bookService.getById(id);
    38. }
    39. /**
    40. * 获取所有
    41. * @return
    42. */
    43. @GetMapping
    44. public List<Book> getAll() {
    45. return bookService.getAll();
    46. }
    47. }

3.5.3 接口测试

  • 业务层接口测试(整合Junit)

    1. @RunWith(SpringJUnit4ClassRunner.class)
    2. @ContextConfiguration(classes = SpringConfig.class)
    3. public class BookServiceTest {
    4. @Autowired
    5. private BookService bookService;
    6. @Test
    7. public void testGetById() {
    8. Book book = bookService.getById(2);
    9. System.out.println(book);
    10. }
    11. @Test
    12. public void testGetAll() {
    13. List<Book> list = bookService.getAll();
    14. System.out.println(list);
    15. }
    16. }
  • 表现层接口测试(PostMan)

3.5.4 添加事务

  • 在Spring配置类中打开使用注解式事务驱动@EnableTransactionManagement

  • 在JDBC配置类中添加事务管理器配置PlatformTransactionManager

    1. @Bean
    2. public PlatformTransactionManager transactionManager(DataSource dataSource){
    3. DataSourceTransactionManager ptm = new DataSourceTransactionManager();
    4. ptm.setDataSource(dataSource);
    5. return ptm;
    6. }
  • 给要添加事务的实现类的接口添加注解@Transactional

3.5.5 表现层数据封装协议

  • 前端接收数据格式

    • 增删改:true

    • 查单条:

      1. {
      2. "id": 1,
      3. "type": "计算机理论",
      4. "name": "Spring实战 第5版",
      5. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
      6. }
    • 查全部:

      1. [
      2. {
      3. "id": 1,
      4. "type": "计算机理论",
      5. "name": "Spring实战 第5版",
      6. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
      7. },
      8. {
      9. "id": 2,
      10. "type": "计算机理论",
      11. "name": "Spring 5核心原理与30个类手写实战",
      12. "description": "十年沉淀之作,手写Spring精华思想"
      13. }
      14. ]
  • 统一格式,前端接收数据格式:封装数据到data属性中,封装操作到code属性中,封装特殊消息到message(msg)属性中

    • 增删改:

      1. {
      2. "code":20031
      3. "data":true
      4. }
    • 查单条:

      1. {
      2. "code":20041
      3. "data":{
      4. "id": 1,
      5. "type": "计算机理论",
      6. "name": "Spring实战 第5版",
      7. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
      8. }
      9. }
    • 查单条数据为空

      1. {
      2. "code":20040
      3. "data":null
      4. "msg":"数据查询失败,请重试!"
      5. }
    • 查全部:

      1. {
      2. "code":20041
      3. "data":[
      4. {
      5. "id": 1,
      6. "type": "计算机理论",
      7. "name": "Spring实战 第5版",
      8. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
      9. },
      10. {
      11. "id": 2,
      12. "type": "计算机理论",
      13. "name": "Spring 5核心原理与30个类手写实战",
      14. "description": "十年沉淀之作,手写Spring精华思想"
      15. }
      16. ]
      17. }
  • 设置统一数据返回结果类

    1. public class Result {
    2. private Object data;
    3. private Integer code;
    4. private String msg;
    5. }
    • Result类中的字段并不是固定的,可以根据需要自行删减
    • 提供若干个构造方法,方便操作

3.5.5 表现层与前端数据传输数据协议实现

  • 添加Result结果数据

    1. @Getter
    2. @Setter
    3. public class Result {
    4. private Object data;
    5. private Integer code;
    6. private String msg;
    7. public Result(Integer code, Object data, String msg) {
    8. this.data = data;
    9. this.code = code;
    10. this.msg = msg;
    11. }
    12. public Result(Integer code, Object data) {
    13. this.data = data;
    14. this.code = code;
    15. }
    16. public Result() {
    17. }
    18. }
  • 修改Controller的return数据

    1. @RestController
    2. @RequestMapping("/books")
    3. public class BookController {
    4. @Autowired
    5. private BookService bookService;
    6. /**
    7. * 保存
    8. * @param book
    9. */
    10. @PostMapping
    11. public Result save(@RequestBody Book book) {
    12. boolean flag = bookService.save(book);
    13. return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    14. }
    15. /**
    16. * 修改/更新
    17. * @param book
    18. */
    19. @PutMapping
    20. public Result update(@RequestBody Book book) {
    21. boolean flag = bookService.update(book);
    22. return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    23. }
    24. /**
    25. * 根据id删除
    26. * @param id
    27. */
    28. @DeleteMapping("/{id}")
    29. public Result delete(@PathVariable Integer id) {
    30. boolean flag = bookService.delete(id);
    31. return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    32. }
    33. /**
    34. * 根据id查询
    35. * @param id
    36. * @return
    37. */
    38. @GetMapping("/{id}")
    39. public Result getById(@PathVariable Integer id) {
    40. Book book = bookService.getById(id);
    41. Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
    42. String msg = book != null ? "" : "数据查询失败,请重试";
    43. return new Result(code, book, msg);
    44. }
    45. /**
    46. * 获取所有
    47. * @return
    48. */
    49. @GetMapping
    50. public Result getAll() {
    51. List<Book> books = bookService.getAll();
    52. Integer code = books.isEmpty() ? Code.GET_OK : Code.GET_ERR;
    53. String msg = books.isEmpty() ? "" : "数据查询失败,请重试";
    54. return new Result(code, books, msg);
    55. }
    56. }

3.5.6 异常处理器

程序开发过程中不可避免的会遇到异常现象

  • 出现异常现象的常见位置与常见诱因如下

    • 框架内部抛出的异常:因使用不合规导致
    • 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
    • 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
    • 表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
    • 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
  • 各个层级都会出现异常,异常处理代码书写在哪一层?

    • 所有的异常均抛出到表现层进行处理
  • 表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决?

    • AOP思想
  • 异常处理器

    • 集中的、统一的处理项目中出现的异常
    1. @RestControllerAdvice
    2. public class ProjectExceptionAdvice {
    3. @ExceptionHandler(Exception.class)
    4. public Result doException(Exception ex){
    5. System.out.println("异常别跑");
    6. return new Result(666,null,"异常别跑");
    7. }
    8. }

    @RestControllerAdvice:声明一个类作为异常处理器

    @ExceptionHandler:定义当前方法处理哪一种异常

  • 项目异常分类

    • 业务异常(BusinessException)

      • 规范的用户行为产生的异常
      • 不规范的用户行为操作产生的异常
    • 系统异常(SystemException)
      • 项目运行过程中可预计且无法避免的异常
    • 其他异常(Exception)
      • 编程人员未预期到的异常
  • 项目异常处理方案

    • 业务异常(BusinessException)

      • 发送对应消息传递给用户,提醒规范操作
    • 系统异常(SystemException)
      • 发送固定消息传递给用户,安抚用户
      • 发送特定消息给运维人员,提醒维护
      • 记录日志
    • 其他异常(Exception)
      • 发送固定消息传递给用户,安抚用户
      • 发送特定消息给编程人员,提醒维护(纳入预期范围内)
      • 记录日志
  • 实现:

    • 新建exception包

    • 创建Exception类,自定义系统、业务级异常

      1. @Getter
      2. @Setter
      3. public class SystemException extends RuntimeException {
      4. private Integer code;
      5. public SystemException(Integer code, String message) {
      6. super(message);
      7. this.code = code;
      8. }
      9. public SystemException(Integer code, String message, Throwable cause) {
      10. super(message, cause);
      11. this.code = code;
      12. }
      13. }
      1. @Getter
      2. @Setter
      3. public class BusinessException extends RuntimeException{
      4. private Integer code;
      5. public BusinessException(Integer code, String message) {
      6. super(message);
      7. this.code = code;
      8. }
      9. public BusinessException(Integer code, String message, Throwable cause) {
      10. super(message, cause);
      11. this.code = code;
      12. }
      13. }
    • 自定义异常编码

      1. public class Code {
      2. public static final Integer SYS_ERR = 50001;
      3. public static final Integer SYS_TIMEOUT_ERR = 50002;
      4. public static final Integer SYS_UNKNOW_ERR = 59999;
      5. public static final Integer Business_ERR = 60002;
      6. }
    • 将可能出现的异常进行包装,转换成自定义异常,触发自定义异常

      1. @Override
      2. public Book getById(Integer id) {
      3. if (id == 1){
      4. throw new BusinessException(Code.Business_ERR,"请不要乱来!");
      5. }
      6. //将可能出现的异常进行包装,转换成自定义异常
      7. try {
      8. int i = 1 / 0;
      9. }catch (Exception e){
      10. throw new SystemException(Code.SYS_TIMEOUT_ERR,"服务器访问超时,请重试",e);
      11. }
      12. return bookDao.getById(id);
      13. }
    • 在异常处理器中分别进行处理

      1. @RestControllerAdvice
      2. public class ProjectExceptionAdvice {
      3. @ExceptionHandler(SystemException.class)
      4. public Result doSystemException(SystemException ex){
      5. //记录日志
      6. //发送消息给运维
      7. //发送邮件给开发文件,ex对象发送给开发人员
      8. return new Result(ex.getCode(),null,ex.getMessage());
      9. }
      10. @ExceptionHandler(BusinessException.class)
      11. public Result doBusinessException(BusinessException ex){
      12. return new Result(ex.getCode(),null,ex.getMessage());
      13. }
      14. @ExceptionHandler(Exception.class)
      15. public Result doException(Exception ex){
      16. //记录日志
      17. //发送消息给运维
      18. //发送邮件给开发文件,ex对象发送给开发人员
      19. return new Result(Code.SYS_UNKNOW_ERR,null,"系统繁忙,请稍后再试");
      20. }
      21. }

3.5.7 前后台协议联调

  • 列表功能

    1. getAll() {
    2. //发送ajax请求
    3. axios.get("/books").then((res)=>{
    4. this.dataList = res.data.data;
    5. })
    6. },
  • 添加功能

    1. //弹出添加窗口
    2. handleCreate() {
    3. this.dialogFormVisible = true;
    4. },
    1. //添加
    2. handleAdd() {
    3. //发送ajax请求
    4. axios.post("/books", this.formData).then((res) => {
    5. //console.log(res.data)
    6. if (res.data.code == 20011){
    7. //如果操作成功,关闭弹窗,显示数据
    8. this.dialogFormVisible = false;
    9. this.$message.success("添加成功")
    10. }else if (res.data.code ==20010){
    11. this.$message.error("添加失败")
    12. }else {
    13. this.$message.error(res.data.msg)
    14. }
    15. }).finally(()=>{
    16. this.getAll();
    17. })
    18. },
    1. //重置表单
    2. resetForm() {
    3. this.formData = {}
    4. },
    1. //弹出添加窗口
    2. handleCreate() {
    3. this.dialogFormVisible = true;
    4. this.resetForm();
    5. },
  • 修改功能

    1. //弹出编辑窗口
    2. handleUpdate(row) {
    3. //查询数据,根据id查询
    4. axios.get("/books/"+row.id).then((res)=>{
    5. if (res.data.code== 20041){
    6. //展示弹层,加载数据
    7. this.formData = res.data.data;
    8. this.dialogFormVisible4Edit = true;
    9. }else{
    10. this.$message.error(res.data.msg)
    11. }
    12. })
    13. },
    1. //编辑
    2. handleEdit() {
    3. //发送ajax请求
    4. axios.put("/books", this.formData).then((res) => {
    5. //如果操作成功,关闭弹层,显示数据
    6. if (res.data.code == 20031){
    7. this.dialogFormVisible4Edit = false;
    8. this.$message.success("修改成功")
    9. }else if (res.data.code ==20030){
    10. this.$message.error("修改失败")
    11. }else {
    12. this.$message.error(res.data.msg)
    13. }
    14. }).finally(()=>{
    15. this.getAll();
    16. })
    17. },
  • 删除功能

    1. // 删除
    2. handleDelete(row) {
    3. //弹出提示框
    4. this.$confirm("此操作不可逆,永久删除数据,是否继续", "提示", {
    5. type: 'info'
    6. }).then(() => {
    7. //删除业务
    8. //查询数据,根据id查询
    9. axios.delete("/books/" + row.id).then((res) => {
    10. if (res.data.code == 20021) {
    11. this.$message.success("删除成功")
    12. } else {
    13. this.$message.error("删除失败")
    14. }
    15. }).finally(() => {
    16. this.getAll();
    17. });
    18. }).catch(() => {
    19. //取消删除
    20. this.$message.info("取消删除操作")
    21. });
    22. }

3.6 拦截器

3.6.1 拦截器概念

  • 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
  • 作用
    • 在指定的方法调用前后执行预先设定的代码
    • 组织原始方法的执行
  • 拦截器和过滤器的区别
    • 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
    • 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强

3.6.2 入门案例

  • 制作拦截器功能类:声明拦截器的bean,并实现HanderInterceptor接口(注意:扫描加载bean)

    1. @Component
    2. public class ProjectInterceptor implements HandlerInterceptor {
    3. //在原始被拦截之前运行的代码
    4. @Override
    5. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    6. System.out.println("preHandle");
    7. //false时,只执行preHandle,终止原始操作的运行
    8. return true;
    9. }
    10. //在原始被拦截之后运行的代码
    11. @Override
    12. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    13. System.out.println("postHandle");
    14. }
    15. //在原始被拦截之后运行的代码并且在post之后
    16. @Override
    17. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    18. System.out.println("afterCompletion");
    19. }
    20. }
  • 配置拦截器的执行位置:定义配置类,继承WebMvcConfigurationSupport,实现addInterceptor方法设定拦截的访问路径(注意:扫描加载配置)

    1. @Configuration
    2. public class SpringMVCSupport extends WebMvcConfigurationSupport {
    3. @Autowired
    4. private ProjectInterceptor projectInterceptor;
    5. @Override
    6. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    7. registry.addResourceHandler("/pages/**").addResourceLocations("/pages");
    8. }
    9. //可以配置多个拦截路径
    10. @Override
    11. protected void addInterceptors(InterceptorRegistry registry) {
    12. registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
    13. }
    14. }
  • 在访问books时输出:

    1. preHandle
    2. book save...Book{书名='haha', 价格=200.0}
    3. postHandle
    4. afterCompletion
  • 简化开发:

    • 不需要SpringMVCSupport类,直接在SpringMvcConfig中实现(侵入式较强)

      1. @Configuration
      2. @ComponentScan({"com.mark.controller"})
      3. @EnableWebMvc
      4. public class SpringMvcConfig implements WebMvcConfigurer {
      5. @Autowired
      6. private ProjectInterceptor projectInterceptor;
      7. @Override
      8. public void addInterceptors(InterceptorRegistry registry) {
      9. registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
      10. }
      11. }

3.6.3 拦截器参数

  • 前置处理

    1. @Override
    2. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    3. String contentType = request.getHeader("Content-Type");
    4. HandlerMethod hm=(HandlerMethod) handler;
    5. hm.getMethod();
    6. System.out.println("preHandle..."+contentType);
    7. return true;
    8. }
    • 参数

      • request:请求对象
      • response:响应对象
      • handler:被调用的处理器对象,本质上是一个方法对象,对反射技术中的Method对象进行了再包装
    • 返回值
      • 返回值为false,被拦截的处理器将不再执行
  • 后置处理

    1. @Override
    2. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    3. System.out.println("postHandle...");
    4. }
    • 参数

      • modelAndView:如果处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整
  • 完成后处理

    1. @Override
    2. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    3. System.out.println("afterCompletion");
    4. }
    • 参数

      • ex:如果处理器执行过程中出现异常对象,可以针对异常情况精选单独处理

3.6.4 拦截器链配置

当配置多个拦截器时,形成拦截器链

  • 配置两个拦截器后运行顺序:

    1. preHandle...
    2. preHandle...222
    3. book getById...1
    4. postHandle...222
    5. postHandle...
    6. afterCompletion...222
    7. afterCompletion

    先进后出

  • 拦截器链的运行顺序参照拦截器添加顺序为准

拦截器运行中断,post都不会执行

4. Maven进阶

4.1 分模块开发与设计

  • 分模块开发意义

    • 将原始模块按照功能拆分成若干个子模块,方便模块间的相互调用,接口共享
  • 分模块开发步骤

    • 创建Maven模块

    • 书写模块代码

      分模块开发需要先针对模块功能进行设计,再进行编码。不会先将工程开发完毕,然后进行拆分

    • 通过maven指令安装模块到本地仓库(install命令)

      团队内部开发需要发布模块到团队内部可共享的仓库中(私服)

    • 在主项目pom中引入各个模块坐标

4.2 依赖管理

依赖指当前项目运行所需的jar,一个项目可以设置多个依赖

格式:

  1. <!--设置当前项目所依赖的所有jar-->
  2. <dependencies>
  3. <!--设置具体的依赖-->
  4. <dependency>
  5. <!--依赖所属群组的id-->
  6. <groupId>com.mark</groupId>
  7. <!--依赖所属项目的id-->
  8. <artifactId>Maven_02_Pojo</artifactId>
  9. <!--依赖版本号-->
  10. <version>1.0-SNAPSHOT</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-webmvc</artifactId>
  15. <version>5.2.10.RELEASE</version>
  16. </dependency>
  17. </dependencies>
  • 依赖传递

    • 依赖具有传递性

      • 直接依赖:在当前项目中通过依赖配置建立的依赖关系
      • 间接依赖:被建立依赖关系的资源如果依赖其他资源,当前项目简介依赖其他资源
  • 依赖传递冲突问题

    • 路径优先:当依赖中出现相同的资源时,层级越深,优先级越低,层级越浅,优先级越高
    • 声明优先:当资源在相同层级被依赖时,配置顺序靠前的覆盖配置顺序靠后的
    • 特殊优先:当同级配置了相同资源的不同版本,后配置的覆盖先配置的

  • 可选依赖optional标签。对外隐藏当前资源。——不透明

    可选依赖是隐藏当前工程所依赖的资源,隐藏后对应资源将不具有依赖传递性

    1. <dependency>
    2. <groupId>com.mark</groupId>
    3. <artifactId>Maven_02_Pojo</artifactId>
    4. <version>1.0-SNAPSHOT</version>
    5. <!--可选依赖是隐藏当前工程所依赖的资源,隐藏后对应资源将不具有依赖传递性-->
    6. <optional>true</optional>
    7. </dependency>
  • 排除依赖:主动端来依赖的资源。——不需要

    在引入其他模块坐标时,该有不需要的依赖可使用排除依赖标签exclusions,被排除的资源无需指定版本

    1. <dependency>
    2. <groupId>com.mark</groupId>
    3. <artifactId>Maven_03_Dao</artifactId>
    4. <version>1.0-SNAPSHOT</version>
    5. <!--隐藏当前资源对应的依赖关系-->
    6. <exclusions>
    7. <exclusion>
    8. <groupId>log4j</groupId>
    9. <artifactId>log4j</artifactId>
    10. </exclusion>
    11. </exclusions>
    12. </dependency>
  • 可选依赖和排除依赖区别:

    • 可选依赖:控制当前模块资源能不能被别人发现
    • 排除依赖:用别人的资源发现不好的资源可以去掉

4.3 聚合与继承

  • 聚合

    • 聚合就是将多个模块组织成一个整体同时进行项目构建的过程称为聚合

    • 聚合工程:通常是一个不具有业务功能的“空”工程(有且仅有一个pom文件)

    • 作用:使用聚合工程可以将多个工程编组,通过对聚合工程进行构建,实现对所包含的模块进行同步构建

      • 当工程中某个模块发生更新(变更)时,必须保障工程中与已更新模块关联的模块同步更新,此时可以使用聚合工程来解决批量模块同步构建的问题
    • 步骤:

      • 创建新的模块

      • 修改打包方式为pom

        1. <groupId>com.mark</groupId>
        2. <artifactId>Maven_00_parent</artifactId>
        3. <version>1.0-SNAPSHOT</version>
        4. <packaging>pom</packaging>
      • 设置管理的模块名称

        1. <!--设置管理的模块名称-->
        2. <modules>
        3. <module>../Maven_01_SSM</module>
        4. <module>../Maven_02_Pojo</module>
        5. <module>../Maven_03_Dao</module>
        6. </modules>
  • 继承

    • 概念:继承描述的是两个工程间的关系,与java中的继承相似,子工程可以继承父工程中的配置信息,常见于依赖关系的继承。简单来说,父工程的依赖子工程可以使用

    • 作用:

      • 简化配置
      • 减少版本冲突
    • 实现:

      • 在父工程的pom中设置打包类型为pom

      • 在父工程的pom文件中配置依赖关系(子工程将沿用父工程的依赖关系)

        1. <dependencies>
        2. <dependency>
        3. <groupId>org.springframework</groupId>
        4. <artifactId>spring-webmvc</artifactId>
        5. <version>5.2.10.RELEASE</version>
        6. </dependency>
        7. <dependency>
        8. <groupId>org.springframework</groupId>
        9. <artifactId>spring-test</artifactId>
        10. <version>5.2.10.RELEASE</version>
        11. </dependency>
        12. ......
        13. </dependencies>
      • 在父工程中配置子工程可以选择的依赖

        1. <!--定义依赖管理-->
        2. <dependencyManagement>
        3. <dependencies>
        4. <dependency>
        5. <groupId>junit</groupId>
        6. <artifactId>junit</artifactId>
        7. <version>4.12</version>
        8. <scope>test</scope>
        9. </dependency>
        10. </dependencies>
        11. </dependencyManagement>
      • 在子工程中配置当前工程所继承的父工程

        1. <parent>
        2. <groupId>com.mark</groupId>
        3. <artifactId>Maven_00_parent</artifactId>
        4. <version>1.0-SNAPSHOT</version>
        5. <!--相对路径,可以快速地找到继承的工程。可以不写-->
        6. <relativePath>../Maven_00_parent/pom.xml</relativePath>
        7. </parent>
      • 子工程这时就可以使用父工程的依赖,同时还可以配置父工程中可选的依赖坐标

        1. <dependencies>
        2. <dependency>
        3. <groupId>junit</groupId>
        4. <artifactId>junit</artifactId>
        5. <scope>test</scope>
        6. </dependency>
        7. </dependencies>

        子工程中使用父工程中的可选依赖时,仅需要提供群组id和项目id,无需提供版本,版本由父工程统一提供,避免版本冲突

        子工程中还可以定义父工程中没有定义的依赖关系

  • 聚合与继承的区别

    • 作用

      • 聚合用于快速构建项目
      • 继承用于快速配置
    • 相同点:
      • 聚合与继承的pom.xml文件打包方式均为pom,可以将两种关系制作到同一个pom文件中
      • 聚合与继承均属于设计型模块,并无实际的模块内容
    • 不同点:
      • 聚合是在当前模块中配置关系,聚合可以感知到参与聚合的模块有哪些
      • 继承是在子模块中配置关系,父模块无法感知哪些子模块继承了自己

4.4 属性管理

  • 属性的配置与使用

    • 定义属性
    1. <properties>
    2. <spring.version>5.2.10.RELEASE</spring.version>
    3. <junit.version>4.12</junit.version>
    4. </properties>
    • 引用属性
    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework</groupId>
    4. <artifactId>spring-webmvc</artifactId>
    5. <version>${spring.version}</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>org.springframework</groupId>
    9. <artifactId>spring-test</artifactId>
    10. <version>${spring.version}</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>org.springframework</groupId>
    14. <artifactId>spring-jdbc</artifactId>
    15. <version>${spring.version}</version>
    16. </dependency>
    17. </dependencies>
    18. <!--定义依赖管理-->
    19. <dependencyManagement>
    20. <dependencies>
    21. <dependency>
    22. <groupId>junit</groupId>
    23. <artifactId>junit</artifactId>
    24. <version>${junit.version}</version>
    25. <scope>test</scope>
    26. </dependency>
    27. </dependencies>
    28. </dependencyManagement>
  • 配置文件加载属性

    • 定义属性

      1. <properties>
      2. <spring.version>5.2.10.RELEASE</spring.version>
      3. <junit.version>4.12</junit.version>
      4. <jdbc.url>jdbc:mysql://127.0.0.1:3306/ssm_db</jdbc.url>
      5. </properties>
    • 配置文件中引用属性

      1. jdbc.driver=com.mysql.cj.jdbc.Driver
      2. jdbc.url=${jdbc.url}
      3. jdbc.username=root
      4. jdbc.password=123
    • 开启资源文件目录加载属性的过滤器

      1. <build>
      2. <!--扩大maven构建范围-->
      3. <resources>
      4. <resource>
      5. <!--使指定的目录里的文件可以解析${}的格式-->
      6. <directory>${project.basedir}/src/main/resources</directory>
      7. <filtering>true</filtering>
      8. </resource>
      9. </resources>
      10. </build>
    • 配置maven打war包时,可以忽略web.xml的检查

      1. <plugins>
      2. <plugin>
      3. <groupId>org.apache.maven.plugins</groupId>
      4. <artifactId>maven-war-plugin</artifactId>
      5. <version>3.2.3</version>
      6. <configuration>
      7. <failOnMissingWebXml>false</failOnMissingWebXml>
      8. </configuration>
      9. </plugin>
      10. </plugins>
  • 其他属性(了解)

    • 属性列表

      • 自定义属性(常用)
      • 内置属性
      • Setting属性
      • Java系统属性
      • 环境变量属性

  • 版本管理

    • 工程版本:

      • SNAPSHOT(快照版本)

        • 项目开发过程中临时输出的版本,称为快照版本
        • 快照版本会随着开发的进展不断更新
      • RELEASE(发布版本)
        • 项目开发到进入阶段里程碑后,向团队外部发布较为稳定的版本,这种版本所对应的构件文件是稳定的,即便进行功能的后续开发,也不会改变当前发布版本内容,这种版本称为发布版本
    • 发布版本
      • alpha版
      • beta版
      • 纯数字版

4.5 多环境配置与应用

  • 多环境开发

    • maven提供配置多种环境的设定,帮助开发者使用过程中快速切换环境
    1. <!--配置多环境开发-->
    2. <profiles>
    3. <!--定义开发环境:生产环境-->
    4. <profile>
    5. <!--定义环境对应的唯一名称-->
    6. <id>env_dep</id>
    7. <!--定义环境中专属的属性值-->
    8. <properties>
    9. <jdbc.url>jdbc:mysql://127.1.1.1:3306/ssm_db</jdbc.url>
    10. </properties>
    11. <!--设定是否为默认启动环境-->
    12. <activation>
    13. <activeByDefault>true</activeByDefault>
    14. </activation>
    15. </profile>
    16. <!--定义开发环境:开发环境-->
    17. <profile>
    18. <id>env_pro</id>
    19. <properties>
    20. <jdbc.url>jdbc:mysql://127.2.2.2:3306/ssm_db</jdbc.url>
    21. </properties>
    22. </profile>
    23. <!--定义开发环境:测试环境-->
    24. <profile>
    25. <id>env_test</id>
    26. <properties>
    27. <jdbc.url>jdbc:mysql://127.3.3.3:3306/ssm_db</jdbc.url>
    28. </properties>
    29. </profile>
    30. </profiles>
    • 使用多环境(构建过程)

      mvn 指令 -P 环境定义id

      范例:

      mvn install -P env_pro

  • 跳过测试

    • 应用场景

      • 功能更新中并且没有开发完毕
      • 快速打包
      • ......
    • 方式一:快速跳过

    • 方式二:配置跳过

      1. <plugins>
      2. <plugin>
      3. <artifactId>maven-surefire-plugin</artifactId>
      4. <version>2.12.4</version>
      5. <configuration>
      6. <!--false:不跳过所有test-->
      7. <skipTests>false</skipTests>
      8. <!--排除掉不参与测试的内容-->
      9. <excludes>**/BookServiceTest.java</excludes>
      10. </configuration>
      11. </plugin>
      12. </plugins>
    • 方式三:命令跳过

      mvn package -D skipTests

4.6 私服

  • 私服简介

    • 私服就是一台独立的服务器,用于解决团队内部的资源共享与资源同步问题

    • Nexus

    • 使用:

      • 启动服务器(命令行启动)

        nexus.exe /run nexus

      • 访问服务器(默认端口8081)

        http://localhost:8081

      • 修改基础配置信息

        • 安装路径下etc目录中nexus-default.properties文件保存有nexus基础配置信息,例如默认访问端口
      • 修改服务器运行配置信息

        • 安装路径下bin目录中nexus.vmoptions文件保存有nexus服务器启动的配置信息,例如默认占用内存空间
  • 私服仓库分类

    仓库组是小组内共享资源用的,宿主仓库是小组内自己用的,代理仓库是所有项目组公用的

  • 资源上传与下载

    • 本地仓库访问私服配置

      • 创建自己的两个仓库

      • 配置本地仓库对私服的访问权限:打开maven的settings.xml文件,找到servers

        1. <!-- 配置访问私服的权限 -->
        2. <server>
        3. <!-- 私服中的服务器id名称 -->
        4. <id>mark-snapshot</id>
        5. <!-- admin -->
        6. <username>admin</username>
        7. <!-- 123 -->
        8. <password>123</password>
        9. </server>
        10. <server>
        11. <!-- 私服中的服务器id名称 -->
        12. <id>mark-release</id>
        13. <!-- admin -->
        14. <username>admin</username>
        15. <!-- 123 -->
        16. <password>123</password>
        17. </server>
      • 设置仓库组管理范围

      • 配置映射关系

        1. <!-- 私服的访问路径 -->
        2. <mirror>
        3. <!-- 仓库组的id -->
        4. <id>maven-public</id>
        5. <mirrorOf>*</mirrorOf>
        6. <url>http://localhost:8081/repository/maven-public/h</url>
        7. </mirror>
    • 私服资源上传与下载

      • 配置工程保存在私服中的位置

        1. <!--配置当前工程保存在私服中的具体位置-->
        2. <distributionManagement>
        3. <repository>
        4. <id>mark-release</id>
        5. <url>http://localhost:8081/repository/mark-release/</url>
        6. </repository>
        7. <snapshotRepository>
        8. <id>mark-snapshot</id>
        9. <url>http://localhost:8081/repository/mark-snapshot/</url>
        10. </snapshotRepository>
        11. </distributionManagement>
      • 上传指令:deploy(在上传前要为所有的模块配置继承关系)

      • 然后接可以在仓库中看到上传的资源了

      • 因为pom.xml中设置了版本为SNAPSHOT,因此只上传到了snapshot仓库,当修改为RELEASE时便可上传到mark-release仓库中

        1. <groupId>com.mark</groupId>
        2. <artifactId>Maven_00_parent</artifactId>
        3. <version>1.0-RELEASE</version>
        4. <packaging>pom</packaging>
    • 可以更换中央仓库

SpringMVC&Maven进阶的更多相关文章

  1. Spirng+SpringMVC+Maven+Mybatis+MySQL项目搭建(转)

    这篇文章主要讲解使用eclipse对Spirng+SpringMVC+Maven+Mybatis+MySQL项目搭建过程,包括里面步骤和里面的配置文件如何配置等等都会详细说明. 如果还没有搭建好环境( ...

  2. eclipse下SpringMVC+Maven+Mybatis+MySQL项目搭建

    这篇文章主要讲解使用eclipse对Spirng+SpringMVC+Maven+Mybatis+MySQL项目搭建过程,包括里面步骤和里面的配置文件如何配置等等都会详细说明. 接下来马上进入项目搭建 ...

  3. JEECG(二) JEECG框架下调用webservice java springmvc maven 调用 webservice

    JEECG系列教程二 如何在JEECG框架下使用webservice 本文所使用的webservice是c#开发的 其实无论是什么语言开发的webservice用法都一样 java springmvc ...

  4. IDEA 搭建 springmvc maven 项目

    前言:将搭建 java springmvc maven 项目的过程及问题记录下来,以及配置文件.这次没有涉及到数据库,后续再写. 目录: 一.首先在 IDEA 中创建 springmvc maven ...

  5. 解决:springmvc maven 项目搭建完后没有src目录,而且maven导入很慢

    前言:在搭建springmvc maven项目中遇到的问题做总结,比如搭建后没有src,同时这里也解决了搭建后maven导入很慢的问题. 问题: 1.发现创建出来的maven项目没有src文件 ,而且 ...

  6. spring+springmvc+maven+mongodb

    1.前言 最近项目开发使用到了spring+springmvc+maven+mongodb,项目中的框架是用springboot进项开发的,对于我们中级开发人员来说,有利有弊,好处呢是springbo ...

  7. SpringMVC+Maven开发项目源码详细介绍

    代码地址如下:http://www.demodashi.com/demo/11638.html Spring MVC概述 Spring MVC框架是一个开源的Java平台,为开发强大的基于Java的W ...

  8. [Java] Spring + SpringMVC + Maven + JUnit 搭建

    示例项目下载: https://github.com/yangyxd/SpringDemo 利用前面 SpringMVC 项目的配置方式,完成初步的项目创建.下面只讲一些不同之处. 传送门: [Jav ...

  9. Mybatis + SpringMVC + Maven实现分页查询

    使用Mybatis + Maven + SpringMVC 运行时,突然被需要分页查询的功能给难住了 这里推荐采用的插件是PageHelper这个插件,使用起来十分方便.该插件支持以下数据库: Ora ...

随机推荐

  1. 超实用在线工具!能将文字加密为Emoji表情

    试想一下,如果你需要将一段比较敏感的内容发送给你的好友. 但如果这段内容不小心外泄,被别人看到了,可能会带来很多麻烦. 那么,有什么方法能够让传输的文本内容不那么容易被"看破"呢? ...

  2. 「学习笔记」斜率优化dp

    目录 算法 例题 任务安排 题意 思路 代码 [SDOI2012]任务安排 题意 思路 代码 任务安排 再改 题意 思路 练习题 [HNOI2008]玩具装箱 思路 代码 [APIO2010]特别行动 ...

  3. 业务流程可视化-让你的流程图"Run"起来(7.运行状态持久化&轻量工作流支持)

    前言 感谢大家阅读本项目系列文章和对项目的支持.分享一下我对这个项目的新的改进. 之前项目做到了流程设计可视化和流程运行结果可视化. 本期发布的版本中实现了中间的运行过程的实时可视化,和流程状态持久化 ...

  4. RabbitMQ 入门系列:8、扩展内容:接收信息时:可否根据RoutingKey过滤监听信息,答案是不能。

    系列目录 RabbitMQ 入门系列:1.MQ的应用场景的选择与RabbitMQ安装. RabbitMQ 入门系列:2.基础含义:链接.通道.队列.交换机. RabbitMQ 入门系列:3.基础含义: ...

  5. 强大多云混合多K8S集群管理平台Rancher入门实战

    @ 目录 概述 定义 为何使用 其他产品 安装 简述 规划 基础环境 Docker安装 Rancher安装 创建用户 创建集群 添加Node节点 配置kubectl 创建项目和名称空间 发布应用 偏好 ...

  6. 关于使用docker volume挂载的注意事项

    Content 在用Docker进行持久化的存储的时候,有两种方式: 使用数据卷(volume) -v 容器绝对路径 或者 -v 已经创建的volume名称:容器绝对路径 2. 使用挂载点(共享宿主目 ...

  7. KingbaseES sys_prewarm 扩展

    Oracle 在查询数据 可以通过cache hint 所访问的数据cache 到数据库buffer,对于KingbaseES,如何将数据加载到cache 了?sys_prewarm 扩展插件可以实现 ...

  8. 使用『jQuery』『原生js』制作一个选项卡盒子 —— { }

    效果 HTML 部分 <body> <div id="main-box"> <div id="left-nav"></ ...

  9. flutter系列之:flutter中常用的container layout详解

    目录 简介 Container的使用 旋转Container Container中的BoxConstraints 总结 简介 在上一篇文章中,我们列举了flutter中的所有layout类,并且详细介 ...

  10. 安装配置docker&maven环境

     原文视频:(https://blog.sechelper.com/20220919/code-review/docker-maven-install-guid/) Docker是什么 Docker ...