SSM整合案例
V哥官网:http://www.vgxit.com
本文对应视频教程:http://www.vgxit.com/course/24
1,概述
有一些老师喜欢把SSM整合的知识放在最后来讲,但是,我觉得我们本来就学习了Spring和Mybatis的整合了,而SpringMvc和SPring的整合是不是天然的就很简单的就OK,所以,我们现在完全可以尝试一下整合SSM。
2,整合步骤
1,创建一个JavaWeb工程。
2,配置依赖和插件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springmvc</artifactId>
<groupId>com.vgxit.learn</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.vgxit.learn.springmvc</groupId>
<artifactId>02ssm</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
</dependency>
</dependencies>
<build>
<finalName>02ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>10.0.6</version>
<configuration>
<webApp>
<contextPath>/02ssm</contextPath>
</webApp>
<httpConnector>
<!--服务启动的端口号,默认是8080-->
<port>81</port>
</httpConnector>
</configuration>
</plugin>
</plugins>
</build>
</project>
3,配置对应的web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置DispatcherServlet-->
<servlet>
<servlet-name>dispatcherServlet</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>
<!--让服务启动起来的时候就创建DispatcherServlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--所有的请求都会经过dispatcherServlet-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4,druid.properties(配置数据源):
db.class=com.alibaba.druid.pool.DruidDataSource
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis.ktdm?serverTimezone=Asia/Shanghai
db.username=root
db.password=Abc@123456
db.initialSize=5
db.minIdle=5
db.maxActive=20
db.maxWait=3000
db.timeBetweenEvictionRunmillis=60000
db.minEvictableIdelTimeMillis=60000
5,配置对应的springmvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.vgixt.learn.springmvc.ssm"/>
<!--配置视图解析器,就是controller转发页面的解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--所有的视图都在这个目录下找-->
<property name="prefix" value="/jsp/"/>
<!--配置文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean>
<!--数据连接池-->
<!--加载数据源配置文件-->
<context:property-placeholder location="classpath:druid.properties"/>
<!--数据数据库连接池-->
<bean id="dataSource" class="${db.class}">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialSize" value="${db.initialSize}"/>
<property name="minIdle" value="${db.minIdle}"/>
<property name="maxActive" value="${db.maxActive}"/>
<property name="maxWait" value="${db.maxActive}"/>
<property name="timeBetweenEvictionRunsMillis" value="${db.timeBetweenEvictionRunmillis}"/>
<property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdelTimeMillis}"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置Mapper的扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.vgixt.learn.springmvc.ssm.mapper"/>
<!--注入对应的sqlSessionFacotry-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--Mapper对应的注解-->
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启申明式事物-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<mvc:annotation-driven/>
</beans>
6,配置logbak(logback.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<configuration
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="logback.xsd"
scan="true"
scanPeriod="60 seconds"
debug="false">
<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{100} %msg%n"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<!--appender其实是负责统一调度日志的输出工作,而具体的日志的格式化工作和输出的工作会交给encoder-->
<encoder>
<!--定义日志输出的格式-->
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="consoleAppender"/>
</root>
<logger name="org.apache.ibatis" level="DEBUG"/>
<logger name="com.vgixt.learn.springmvc.ssm" level="DEBUG"/>
<logger name="org.springframework" additivity="false" level="WARN">
<appender-ref ref="consoleAppender"/>
</logger>
</configuration>
7,配置mybatis(mybatis-config.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--配置运行的sql在控制台打印输出-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--开启驼峰映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--全局设置主键自动回填-->
<setting name="useGeneratedKeys" value="true"/>
<!--配置默认的执行器,SIMPLE会直接执行sql没有什么特别的。REUSE会重用预处理器,也就是会重用同一个Sql的Statement。BATCH 通过批量操作来优化性能-->
<setting name="defaultExecutorType" value="REUSE"/>
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--设置超时时间,就是sql执行的超时时间,单位秒-->
<setting name="defaultStatementTimeout" value="120"/>
</settings>
<!--配置别名-->
<typeAliases>
<package name="com.vgxit.learn.springmvc.ssm.po"/>
</typeAliases>
<!--配置映射器-->
<mappers>
<package name="om.vgxit.learn.springmvc.ssm.mapper"/>
</mappers>
</configuration>
8,写一个简单的Controller,测试运行
package com.vgixt.learn.springmvc.ssm.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
@GetMapping("/all")
public ModelAndView all() {
log.info("进入了all页面");
ModelAndView mv = new ModelAndView();
mv.setViewName("user/all");
return mv;
}
}
9,编写对应的Po
po对应的表的sql如下:
package com.vgixt.learn.springmvc.ssm.po;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private Short gender;
private Integer age;
private String nickName;
}
10,编写对应的Mapper:
package com.vgixt.learn.springmvc.ssm.mapper;
import com.vgixt.learn.springmvc.ssm.po.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
@Select("select * from user")
List<User> all();
}
11,编写对应的业务逻辑层接口:
package com.vgixt.learn.springmvc.ssm.service.user;
import com.vgixt.learn.springmvc.ssm.po.User;
import java.util.List;
/**
* 定义我们业务逻辑层的标准
*/
public interface IUserService {
List<User> all();
}
12,编写对应的业务逻辑层实现:
package com.vgixt.learn.springmvc.ssm.service.user;
import com.vgixt.learn.springmvc.ssm.mapper.UserMapper;
import com.vgixt.learn.springmvc.ssm.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements IUserService {
@Autowired
private UserMapper userMapper;
public List<User> all() {
return userMapper.all();
}
}
13,使用xml的方式:
在真实线上开发的时候,我们使用xml文件来定义sql的时候是更多的,因为用注解的方式不好维护,并且编写动态Sql非常麻烦。
1,编写对应的Mapper.xml:
<?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.vgixt.learn.springmvc.ssm.mapper.UserMapper">
<select id="all" resultType="com.vgixt.learn.springmvc.ssm.po.User">
select * from user
</select>
</mapper>
2,干掉Mapper的@select注解
3,在pom.xml中加入如下代码:
<build>
<finalName>02ssm</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
14,整合jstl输出内容
对应的Controlelr:
package com.vgixt.learn.springmvc.ssm.controller;
import com.vgixt.learn.springmvc.ssm.po.User;
import com.vgixt.learn.springmvc.ssm.service.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/all")
public ModelAndView all() {
List<User> users = userService.all();
ModelAndView mv = new ModelAndView();
mv.setViewName("user/all");
mv.addObject("users", users);
return mv;
}
}
对应的jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/8/15
Time: 17:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<h1>所有的用户</h1>
<table>
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>昵称</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users }" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.age}</td>
<td>${user.nickName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>