SpringMVC-2022

MVC

  • 什么是MVC?

    它是一种开发模式,它是模型视图控制器的简称。所有的web 应用都是基于MVC 开发的

  • M: 模型层,它是模型视图控制器的简称。所有的web 应用都是基于MVC 开发

  • V: 视图层,html、javascript、vue 等都是视图层,用来显示数据

  • C: 控制器,它是用来接受客户端的请求,并返回响应到客户端的组件,Servlet 就是组件

SpringMVC 框架的有点

  • 轻量级,基于MVC 的框架
  • 易于上手,容易理解,功能强大
  • 它具备IoC AOP
  • 完全基于注解开发

基于注解的 SpringMVC 框架开发的步骤

  1. 新建maven 项目,选择模板webapp

    创建项目
  2. 修改目录,添加缺失目录,并修改目录属性

    添加java目录...webapp 目录配置
  3. 修改pom.xml,添加SpringMVC、Servlet 的依赖

    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>

    <artifactId>springmvc-001</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <!-- 编译环境 -->
    <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
    <!-- 测试 -->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
    </dependency>
    <!-- springmvc -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.23</version>
    </dependency>
    <!-- servlet -->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
    </dependency>

    </dependencies>
    <build>
    <!-- 打包后的名称 -->
    <finalName>springmvc-001</finalName>
    <!-- 资源文件扫描的配置 -->
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.xml</include>
    <include>**/*.properties</include>
    </includes>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.xml</include>
    <include>**/*.properties</include>
    </includes>
    </resource>
    </resources>
    </build>
    </project>

  4. 添加springmvc.xml 配置文件,指定包扫描,添加视图解析器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <!-- xml 文件就是 spring 的 xml 文件约束  xml 不允许首行注释, 配置名称: resources/springmvc.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置包扫描 -->
    <context:component-scan base-package="com.example"/>
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 配置前缀 -->
    <property name="prefix" value="/admin/"/>
    <!-- 配置后缀 -->
    <property name="suffix" value=".jsp"/>
    </bean>
    </beans>
  5. 删除wen.xml 文件(版本过低),新建web.xml

    web.xml
  6. web.xml 文件中注册springmvc 框架(所有的web 请求都是基于servlet 的)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">
    <!-- 注册 springwvc -->
    <servlet>
    <servlet-name>springmvc</servlet-name>
    <!-- 交给谁处理 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 引入 springmvc 配置 -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 映射 -->
    <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 拦截什么样的请求 -->
    <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    </web-app>
  7. 删除index.jsp,并新建,发送请求给服务器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!-- index.jsp -->
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    <a href="${pageContext.request.contextPath}/main.action">访问 main
    </body>
    </html>

  8. webapp 目录下新建admin 目录(根据配置文件中的需要添加),admin/admin.jsp,删除index.jsp,并新建

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!-- /admin/admin.jsp -->
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Admin-Page</title>
    </head>
    <body>
    <h1>show admin.............................</h1>
    </body>
    </html>

  9. 开发控制器(Servlet),它是一个普通的类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class MainController {
    @RequestMapping("/main.action")
    public String main() {
    return "admin";
    }
    }

  10. Tomcat 启动测试

    测试请求
    • 注意点

      在这些步骤的前提下,如果访问出现404,那么进行IDEA 缓存清除,重新构建,再次启动测试

  • 项目目录结构

    当前目录结构

五种数据提交方式的优化

  • 单个提交数据

    1
    2
    3
    4
    5
    6
    <%-- 单个提交数据 --%>
    <form action="/user.do" method="post">
    <input type="text" name="myname">
    <input type="number" name="age">
    <input type="submit" value="提交">
    </form>
    1
    2
    3
    4
    5
    @RequestMapping("/user.do")
    public String user(String myname, int age) {
    System.out.println(myname + " " + (age + 10));
    return "admin";
    }
  • 对象封装提交数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 实体类
    package com.example.entity;

    import lombok.Data;

    @Data
    public class User {
    private String username;
    private Integer age;
    }

    1
    2
    3
    4
    5
    @RequestMapping("/pojo.do")
    public String user(User user) {
    System.out.println(user.getUsername() + " " + (user.getAge() + 10));
    return "admin";
    }
    1
    2
    3
    4
    5
    6
    7
    <%-- 2. 对象封装提交 --%>
    <form action="/pojo.do" method="post">
    <input type="text" name="username">
    <input type="number" name="age">
    <input type="submit" value="提交">
    </form>

  • 动态占位符

    1
    <a href="${pageContext.request.contextPath}/test/zs/19.do">占位符
    1
    2
    3
    4
    5
    @RequestMapping("/test/{username}/{age}.do")
    public String TestDo(@PathVariable("username") String username, @PathVariable("age") int age) {
    System.out.println(username + (age));
    return "admin";
    }
  • 映射名称不一致提交

    1
    2
    3
    4
    5
    <form action="/nomapping.do" method="post">
    <input type="text" name="username">
    <input type="number" name="age">
    <input type="submit" value="提交">
    </form>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 通过 @RequestParam 将 username 注给 uname
    @RequestMapping("/nomapping.do")
    public String NoMapping(
    @RequestParam("username")
    String uname,
    @RequestParam("age")
    int ahe
    ) {
    System.out.println(uname + " " + (ahe));
    return "admin";
    }

中文编码配置

  • web.xml 中配置过滤器,建议写在顶部

    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
    <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--
    查看 CharacterEncodingFilter 的源码得知,以下三个属性需要重新设置:
    private String encoding;
    private boolean forceRequestEncoding;
    private boolean forceResponseEncoding;
    -->
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <!-- 请求的编码 -->
    <init-param>
    <param-name>forceRequestEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    <!-- 响应的编码 -->
    <init-param>
    <param-name>forceResponseEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

方法的返回值

  1. String: 客户端资源的地址,自动拼接前缀和后缀,还可以屏蔽自动拼接字符串,可以指定返回的路径
  2. Object: 返回json 格式的对象。自动将对象或集合转为json,使用jackson 工具进行转换,必须要添加jackson 依赖。一般用于ajax 请求
  3. void: 无返回值,一般用于ajax 请求
  4. 基本数据类型,用于ajax 请求
  5. ModelAndView: 返回数据和视图对象,现在用的很少

完成 Ajax 请求访问服务器,返回学生集合

  1. 添加jackson 依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4.2</version>
    </dependency>
  2. webapp 目录下新建js 目录,添加axios 函数库

    1
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  3. index.jsp 页面上导入函数库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    </head>
    <body>
    <script>
    axios({
    method: 'get',
    url: '${pageContext.request.contextPath}/list.do',
    }).then(res => {
    console.log(JSON.stringify(res.data))
    });
    </script>
    </body>
    </html>

  4. action 上添加注解@ResponseBody,用来处理ajax 请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    @Controller
    public class UserController {
    @ResponseBody
    @RequestMapping("/list.do")
    public List<String> list() {
    List<String> list = new ArrayList<>();
    Collections.addAll(list, "aa", "bb", "cc", "dd");
    return list;
    }
    }

  5. springmvc.xml 文件中添加注解驱动<mvc:annotationdriven/>,用它来解析@RespinseBody 注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置包扫描 -->
    <context:component-scan base-package="com.example"/>


    <!-- 要添加 mvc 的 mvc:annotation-driven -->
    <mvc:annotation-driven/>
    </beans>
  6. 访问测试

    控制台输出

日期处理

  • 单个日期处理

    要使用注解@DateTimeFormat,此注解必须搭配springmvc.xml 中的<mvc:annotationdriven>

    1
    2
    3
    4
    <form action="${pageContext.request.contextPath}/mydate.do" method="post">
    <input type="date" name="mydate">
    <input type="submit" value="提交">
    </form>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    package com.example.controller;

    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    import java.text.SimpleDateFormat;
    import java.util.Date;

    @Controller
    public class DateController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @RequestMapping("/mydate.do")
    public String myDate(
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    Date mydate) {
    System.out.println(sdf.format(mydate));
    return "admin";
    }
    }

  • 类中全局日期处理

    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
    package com.example.controller;

    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    import org.springframework.web.bind.annotation.RequestMapping;

    import java.text.SimpleDateFormat;
    import java.util.Date;

    @Controller
    public class DateController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    // 注册一个全局的日期处理注解
    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
    dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    @RequestMapping("/mydate.do")
    public String myDate(Date mydate) {
    System.out.println(sdf.format(mydate));
    return "admin";
    }
    }

  • 如果一个类的成员属性是日期格式,可以在类的成员 setXX 添加注解 @DateTimeFormat(pattern = "yyyy-MM-dd")

  • 如果是json 类型,需要在类中的成员变量getXXX 方法上添加注解@JsonFormat(pattern="yyyy-MM-dd")

WEB-INF 资源

  • 此目录下的动态资源,不可以直接访问,只能通过请求转发的方式进行访问

  • 修改springmvc.xml 配置

    1
    2
    3
    4
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    1
    <a href="${pageContext.request.contextPath}/showMain.do">WEB-INF/main</a>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class WebInfController {
    @RequestMapping("/showMain.do")
    public String showMain() {
    return "main";
    }
    }

拦截器

  • 什么是拦截器

    针对请求和响应进行的额外处理。在请求和响应的过程中添加预处理,后处理和最终处理

  • 拦截器的执行时机

    • preHandle: 在请求被处理之前进行操作
    • postHandle: 在请求被处理之后,但结果还没有渲染前进行操作,可以改变响应结果
    • afterCompletion: 所有的请求响应结束后执行善后工作,清理对象,关闭资源
  • 拦截器实现的两种方式

    • 集成HandlerIntercepterAdpater 的父类
    • 实现HandlerInterceptor 接口【推荐使用实现接口的方式】
  • 登录拦截器实现的步骤

    1. 改造登录方法,session 中存储用户信息,用于进行权限验证

      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
      package com.example.controller;

      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;

      import javax.servlet.http.HttpServletRequest;

      @Controller
      public class WebInfController {
      @RequestMapping("/showLogin")
      public String showLogin() {
      return "login";
      }
      @RequestMapping("/main.do")
      public String showMain(String username, String password, HttpServletRequest request) {
      if ("coder-itl".equalsIgnoreCase(username) && "coder-itl".equalsIgnoreCase(password)) {
      request.getSession().setAttribute("username", username);
      return "main";
      } else {
      request.setAttribute("msg", "用户名和密码错误");
      return "login";
      }
      }

      }
    2. 开发拦截器的功能,实现HandlerInterceptor 接口,重写preHandle 方法

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      package com.example.intercepter;

      import org.springframework.web.servlet.HandlerInterceptor;

      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      // TODO: 无法实现跳转
      public class LoginInterceptor implements HandlerInterceptor {
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      if (request.getSession().getAttribute("username") == null) {
      // 没有登陆
      request.setAttribute("msg", "您还未登录,请先登录!");
      request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
      return false;
      }
      // 登录成功放行
      return true;
      }
      }

    3. springmvc.xml 文件中注册拦截器

      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
      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
      <!-- 配置包扫描 -->
      <context:component-scan base-package="com.example"/>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"/>
      <property name="suffix" value=".jsp"/>
      </bean>
      <!-- 要添加 mvc 的 mvc:annotation-driven -->
      <mvc:annotation-driven/>
      <mvc:interceptors>
      <mvc:interceptor>
      <!-- 映射要拦截的请求 -->
      <mvc:mapping path="/**"/>
      <!-- 设置放行资源 -->
      <mvc:exclude-mapping path="/showLogin"/>
      <mvc:exclude-mapping path="/main.do"/>
      <!-- 配置局势的拦截器实现类 -->
      <bean class="com.example.intercepter.LoginInterceptor"/>
      </mvc:interceptor>
      </mvc:interceptors>

      </beans>

SSM 整合

  1. 创建项目,添加依赖

    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>spring-ssm</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <!-- 集中定义依赖版本号-->
    <properties>
    <!-- 编译环境 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <!-- 测试 -->
    <junit.version>4.12</junit.version>
    <!-- spring -->
    <spring.version>5.1.2.RELEASE</spring.version>
    <!-- mybatis -->
    <mybatis.version>3.2.8</mybatis.version>
    <!-- mybatis-spring -->
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <!-- mybatis-分页 -->
    <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    <!-- mysql -->
    <mysql.version>8.0.22</mysql.version>
    <!-- 日志 -->
    <slf4j.version>1.6.4</slf4j.version>
    <!-- 数据库连接池 -->
    <druid.version>1.0.9</druid.version>
    <!-- github 分页插件 -->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!-- jstl 标签库 -->
    <jstl.version>1.2</jstl.version>
    <!-- servlet -->
    <servlet-api.version>3.0.1</servlet-api.version>
    <!-- jsp -->
    <jsp-api.version>2.0</jsp-api.version>
    <!-- json 转换 -->
    <jackson.version>2.9.6</jackson.version>
    <!-- logback 日志 -->
    <loback.version>1.2.11</loback.version>
    <!-- 简化实体类 -->
    <lombok.version>1.18.24</lombok.version>
    </properties>

    <dependencies>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.11</version>
    </dependency>
    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
    </dependency><!-- spring -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
    </dependency><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>spring-ssm</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <!-- 集中定义依赖版本号-->
    <properties>
    <!-- 编译环境 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <!-- 测试 -->
    <junit.version>4.12</junit.version>
    <!-- spring -->
    <spring.version>5.1.2.RELEASE</spring.version>
    <!-- mybatis -->
    <mybatis.version>3.2.8</mybatis.version>
    <!-- mybatis-spring -->
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <!-- mybatis-分页 -->
    <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    <!-- mysql -->
    <mysql.version>8.0.22</mysql.version>
    <!-- 日志 -->
    <slf4j.version>1.6.4</slf4j.version>
    <!-- 数据库连接池 -->
    <druid.version>1.0.9</druid.version>
    <!-- github 分页插件 -->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!-- jstl 标签库 -->
    <jstl.version>1.2</jstl.version>
    <!-- servlet -->
    <servlet-api.version>3.0.1</servlet-api.version>
    <!-- jsp -->
    <jsp-api.version>2.0</jsp-api.version>
    <!-- json 转换 -->
    <jackson.version>2.9.6</jackson.version>
    <!-- logback 日志 -->
    <loback.version>1.2.11</loback.version>
    <!-- 简化实体类 -->
    <lombok.version>1.18.24</lombok.version>
    </properties>

    <dependencies>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.11</version>
    </dependency>
    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
    </dependency><!-- spring -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
    <groupId>com.github.miemiedev</groupId>
    <artifactId>mybatis-paginator</artifactId>
    <version>${mybatis.paginator.version}</version>
    </dependency>
    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>${pagehelper.version}</version>
    </dependency>
    <!-- MySql -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
    </dependency>
    <!-- 连接池-->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid.version}</version>
    </dependency>
    <!-- junit -->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>${jstl.version}</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <scope>provided</scope>
    <version>${jsp-api.version}</version>
    </dependency>

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
    </dependency>
    <!-- 文件上传用 -->
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
    </dependency>
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
    </dependency>
    <!-- 日志相关 -->
    <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.11</version>
    </dependency>
    <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.2.11</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
    </dependency>
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.3.23</version>
    </dependency>

    </dependencies>

    <!-- 插件配置-->
    <build>
    <plugins>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    </plugin>
    </plugins>
    <!--识别所有的配置文件-->
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    </resources>
    </build>
    </project>

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
    <groupId>com.github.miemiedev</groupId>
    <artifactId>mybatis-paginator</artifactId>
    <version>${mybatis.paginator.version}</version>
    </dependency>
    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>${pagehelper.version}</version>
    </dependency>
    <!-- MySql -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
    </dependency>
    <!-- 连接池-->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid.version}</version>
    </dependency>
    <!-- junit -->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>${jstl.version}</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <scope>provided</scope>
    <version>${jsp-api.version}</version>
    </dependency>

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
    </dependency>
    <!-- 文件上传用 -->
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
    </dependency>
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
    </dependency>

    <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>${loback.version}</version>
    </dependency>
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.3.23</version>
    </dependency>
    </dependencies>

    <!-- 插件配置-->
    <build>
    <plugins>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    </plugin>
    </plugins>
    <!--识别所有的配置文件-->
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
    </resource>
    </resources>
    </build>
    </project>

  2. 添加缺失目录java,resources

  3. 更换高版本的web.xml

  4. resources 目录下创建jsbc.properties

    1
    2
    3
    4
    5
    # 5.7
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmuser?useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=root
    1
    2
    3
    4
    5
    # 8.0
    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssmuser?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true
    jdbc.username=root
    jdbc.password=root
  5. 创建mybatis-config.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    <!-- STDOUT_LOGGING -->
    <settings>
    <setting name="logImpl" value="SLF4J"/>
    </settings>
    <typeAliases>
    <package name="com.example.entity"/>
    </typeAliases>
    <mappers>
    <package name="com.example.mapper"/>
    </mappers>
    </configuration>

  6. 添加spring-service.xml 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置包扫描 -->
    <!-- 加载属性配置文件 -->

    <!-- 配置 SqlSessionFactoryBean 创建 sqlSessionFactory -->

    <!-- 配置事务管理器 -->
    </beans>
    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 包扫描 -->
    <context:component-scan base-package="com.example"/>
    <!-- 添加属性配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置 SqlSessionFactoryBean 创建 SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 配置数据源 -->
    <property name="dataSource" ref="myDataSource"/>
    <!-- 配置 mybatis 主配置文件 -->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <property name="basePackage" value="com.example.mapper"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="myDataSource"/>
    </bean>
    <!-- 配置事务切面 -->
    <tx:advice id="myAdvice" transaction-manager="txManager">
    <tx:attributes>
    <tx:method name="*select*" read-only="true"/>
    <tx:method name="*find*" read-only="true"/>
    <tx:method name="*get*" read-only="true"/>
    <tx:method name="*search*" read-only="true"/>
    <tx:method name="*insert*" propagation="REQUIRED"/>
    <tx:method name="*save*" propagation="REQUIRED"/>
    <tx:method name="*add*" propagation="REQUIRED"/>
    <tx:method name="*delete*" propagation="REQUIRED"/>
    <tx:method name="*remove*" propagation="REQUIRED"/>
    <tx:method name="*clear*" propagation="REQUIRED"/>
    <tx:method name="*update*" propagation="REQUIRED"/>
    <tx:method name="*modify*" propagation="REQUIRED"/>
    <tx:method name="*change*" propagation="REQUIRED"/>
    <tx:method name="*set*" propagation="REQUIRED"/>
    <tx:method name="*" propagation="SUPPORTS"/>
    </tx:attributes>
    </tx:advice>
    <!-- 配置切入点 + 绑定 -->
    <aop:config>

    <aop:pointcut id="myPointCut" expression="execution(* com.example.service.impl.*.*(..))"/>
    <aop:advisor advice-ref="myAdvice" pointcut-ref="myPointCut"/>
    </aop:config>
    </beans>
  7. 配置spring-mvc.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置包扫描 -->
    <context:component-scan base-package="com.example"/>

    <!-- 添加注解驱动 -->
    <mvc:annotation-driven/>
    </beans>
  8. 配置web.xml

    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
    53
    54
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">
    <!-- 过滤器配置 -->
    <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--
    private String encoding;
    private boolean forceRequestEncoding;
    private boolean forceResponseEncoding;
    -->
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceRequestEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    <init-param>
    <param-name>forceResponseEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- servlet -->
    <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring-service.xml</param-value>
    </context-param>
    </web-app>
  9. 添加实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package com.example.entity;

    import lombok.Data;

    import java.io.Serializable;

    @Data
    public class User implements Serializable {
    private String userId;
    private String cardType;
    private String cardNo;
    private String userName;
    private String userSex;
    private String userAge;
    private String userRole;
    }

  10. 添加service,impl

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // service
    package com.example.service;

    import com.example.entity.User;

    import java.util.List;

    public interface UserService {
    List<User> selectUserPage(String userName, String userSex, int startRow);
    int createUser(User user);
    int deleteUserById(String userId);
    int getRowCount(String userName, String userSex);
    }

    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
    // serviceImpl
    package com.example.service.impl;

    import com.example.entity.User;
    import com.example.mapper.UserMapper;
    import com.example.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service("userService")
    public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectUserPage(String userName, String userSex, int startRow) {
    return userMapper.selectUserPage(userName, userSex, startRow);
    }

    @Override
    public int createUser(User user) {
    return userMapper.createUser(user);
    }

    @Override
    public int deleteUserById(String userId) {
    return userMapper.deleteUserById(userId);
    }

    @Override
    public int getRowCount(String userName, String userSex) {
    return userMapper.getRowCount(userName, userSex);
    }
    }

  11. 创建mapper 映射文件

    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.mapper.UserMapper">

    <resultMap id="userMap" type="user">
    <id property="userId" column="user_id"/>
    <result property="cardType" column="card_type"/>
    <result property="cardNo" column="card_no"/>
    <result property="userName" column="user_name"/>
    <result property="userSex" column="user_sex"/>
    <result property="userAge" column="user_age"/>
    <result property="userRole" column="user_role"/>
    </resultMap>
    <!-- 定义全部列名 -->
    <sql id="allColumns">
    user_id
    ,
    card_type,
    card_no,
    user_name,
    user_sex,
    user_age,
    user_role
    </sql>
    <!-- List<User> selectUserPage(@Param("userName") String userName, @Param("userSex") String userSex, @Param("startRow") int startRow);-->
    <select id="selectUserPage" resultMap="userMap">
    select
    <include refid="allColumns"/>
    from user
    <where>
    <if test="userName!=null and userName!=''">
    and user_name like concat('%',#{userName},'%')
    </if>
    <if test="userSex!=null and userSex!=''">
    and user_sex=#{userSex}
    </if>
    </where>
    limit #{startRow},5
    </select>
    <!-- int createUser(User user);-->
    <insert id="createUser" parameterType="user">
    insert into user
    values (#{userId}, #{cardType}, #{cardNo}, #{userSex}, #{userAge}, #{userRole})
    </insert>
    <!-- int deleteUserById(String userId);-->
    <delete id="deleteUserById" parameterType="string">
    delete
    from user
    where userId = #{userId}
    </delete>
    <!-- int getRowCount(@Param("userName") String userName, @Param("userSex") String userSex);-->
    <select id="getRowCount" resultType="integer">
    select count(*)
    from user
    <where>
    <if test="userName!=null and userName!=''">
    and user_name like concat('%',#{userName},'%')
    </if>
    <if test="userSex!=null and userSex!=''">
    and user_sex=#{userSex}
    </if>
    </where>
    </select>
    </mapper>
  12. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // spring-service.xml 是 spring 管理 service,dao 相关的对象
    public class UserServiceTest {
    @Test
    public void selectUserPageTest() {
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-service.xml");
    UserService userService = ac.getBean("userService", UserService.class);
    int rowCount = userService.getRowCount(null, "男");
    System.out.println(rowCount);
    }
    }

    测试整合是否有效