ㅤcoderitl

V1

2022/11/19阅读:17主题:兰青

SSM-整合详解

SpringMVC-整合详解

MVC

  • 什么是MVC?

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

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

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

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

SpringMVC 框架的有点

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

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

  1. 新建maven项目,选择模板webapp
创建项目
  1. 修改目录,添加缺失目录,并修改目录属性
添加java目录...webapp目录配置
  1. 修改pom.xml,添加SpringMVC、Servlet的依赖
<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>

  1. 添加springmvc.xml配置文件,指定包扫描,添加视图解析器
<!-- 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>
  1. 删除wen.xml文件(版本过低),新建web.xml
web.xml
  1. web.xml文件中注册springmvc框架(所有的web请求都是基于servlet的)
<?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>
  1. 删除index.jsp,并新建,发送请求给服务器
<!-- 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 </a>
</body>
</html>

  1. webapp目录下新建admin目录(根据配置文件中的需要添加),在admin/admin.jsp,删除index.jsp,并新建
<!-- /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>

  1. 开发控制器(Servlet),它是一个普通的类
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";
    }
}

  1. Tomcat启动测试
测试请求
  • 注意点

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

  • 项目目录结构

当前目录结构

五种数据提交方式的优化

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

import lombok.Data;

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

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

  • 动态占位符
<a href="${pageContext.request.contextPath}/test/zs/19.do">占位符</a>
@RequestMapping("/test/{username}/{age}.do")
public String TestDo(@PathVariable("username") String username, @PathVariable("age") int age) {
    System.out.println(username + (age));
    return "admin";
}
  • 映射名称不一致提交
<form action="/nomapping.do" method="post">
    <input type="text" name="username">
    <input type="number" name="age">
    <input type="submit" value="提交">
</form>
// 通过 @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中配置过滤器,建议写在顶部
<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依赖
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4.2</version>
</dependency>
  1. webapp目录下新建js目录,添加axios函数库
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  1. index.jsp页面上导入函数库
<%@ 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>

  1. action上添加注解@ResponseBody,用来处理ajax请求
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;
    }
}

  1. springmvc.xml文件中添加注解驱动<mvc:annotationdriven/>,用它来解析@RespinseBody注解
<?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"/>
    <!-- 不用添加视图解析器,因为处理的是 ajax 请求 -->

    <!-- 要添加 mvc 的 mvc:annotation-driven -->
    <mvc:annotation-driven/>
</beans>
  1. 访问测试
控制台输出

日期处理

  • 单个日期处理

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

<form action="${pageContext.request.contextPath}/mydate.do" method="post">
    <input type="date" name="mydate">
    <input type="submit" value="提交">
</form>
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";
    }
}

  • 类中全局日期处理
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.classnew CustomDateEditor(sdftrue));
    }

    @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配置

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
</bean>
<a href="${pageContext.request.contextPath}/showMain.do">WEB-INF/main</a>
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中存储用户信息,用于进行权限验证

    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方法

    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文件中注册拦截器

    <?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. 创建项目,添加依赖
<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>
        <!-- JSP相关-->
        <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>
        <!-- Jackson Json处理工具包-->
        <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>
        <!-- JSP相关-->
        <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>
        <!-- Jackson Json处理工具包-->
        <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>

  1. 添加缺失目录java,resources

  2. 更换高版本的web.xml

  3. resources目录下创建jsbc.properties

# 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
# 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
  1. 创建mybatis-config.xml
<?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>

  1. 添加spring-service.xml文件
<?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 -->
    <!-- 声明 mybatis 的扫描器,创建dao对象 -->
   <!-- 配置事务管理器 -->
</beans>
<?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>
    <!-- 声明 mybatis 的扫描器,创建dao对象 -->
    <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>
        <!-- execution(* com.example.service.impl.*.*(..)): 任意权限修饰符 com.example.service.impl.任意类.任意方法(任意参数)-->
        <aop:pointcut id="myPointCut" expression="execution(* com.example.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="myAdvice" pointcut-ref="myPointCut"/>
    </aop:config>
</beans>
  1. 配置spring-mvc.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: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"/>
    <!-- 配置视图解析器(ajax 则不需要)-->
    <!-- 添加注解驱动 -->
    <mvc:annotation-driven/>
</beans>
  1. 配置web.xml
<?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>
    <!-- 注册 Spring 框架,目的就是启动 spring 容器 -->
    <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>
  1. 添加实体类
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;
}

  1. 添加service,impl
// 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)
}

// 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);
    }
}

  1. 创建mapper映射文件
<?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>
  1. 测试
// 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);
    }
}

测试整合是否有效

分类:

后端

标签:

Java

作者介绍

ㅤcoderitl
V1