文章目录
- 一、基础配置
- 1. pom
- 2. web.xml
- 二、配置文件
- 2.1.spring-context.xml
- 2.2. spring-datasource.xml
- 2.3. spring-mvc.xml
- 2.4. jdbc.properties
- 2.5. logback.xml
- 三、基础类
- 3.1. 实体类
- 3.2. 接口类
- 3.3. 接口映射xml
- 3.4. service接口
- 3.5. 接口实现类
- 3.6. 控制层
- 四、数据库方面
- 4.1. 创建数据库
- 4.2. 初始化表结构
- 五、浏览器验证
- 5.1. 启动项目
- 5.2. 浏览器测试
- 5.3. 源码地址
一、基础配置
1. pom
<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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.gblfy</groupId><artifactId>ssm-upgrade</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>ssm-upgrade</name><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><maven.compiler.encoding>UTF-8</maven.compiler.encoding><lombok.version>1.18.8</lombok.version><spring.version>4.3.10.RELEASE</spring.version><javax.servlet.version>4.0.1</javax.servlet.version><jstl.version>1.2</jstl.version><org.mybatis.version>3.4.1</org.mybatis.version><org.mybatis.spring.version>1.3.0</org.mybatis.spring.version></properties><dependencies><dependency><groupId>aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.5.4</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${javax.servlet.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><!--spring start--><dependency><groupId>org.springframework</groupId><artifactId>spring-core</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-context</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-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</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-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>${spring.version}</version></dependency><!--spring end--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.2</version></dependency><!--spring myabtisPlus 整合 Start--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.3.1.tmp</version></dependency><!--spring myabtisPlus 整合 End--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.6.11</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version><!--<scope>runtime</scope>--></dependency><!--@Slf4j 日志打印 和lombok注解 Start--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope><version>${lombok.version}</version></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.26</version></dependency><!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version><exclusions><exclusion><artifactId>slf4j-api</artifactId><groupId>org.slf4j</groupId></exclusion></exclusions></dependency><!--@Slf4j 日志打印 和lombok注解 End--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.19</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>20.0</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.5</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><!--<scope>test</scope>--></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.3</version></dependency><!-- ftpclient --><dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.1</version></dependency><!-- file upload --><!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.2.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.0.1</version></dependency></dependencies><build><finalName>ssm-upgrade</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding><compilerArguments><extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib</extdirs></compilerArguments></configuration></plugin><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><configuration><path>/</path><port>8080</port><uriEncoding>UTF-8</uriEncoding><contextReloadable>true</contextReloadable></configuration></plugin></plugins></build><repositories><!-- 代码库 --><repository><id>maven-ali</id><url>http://maven.aliyun.com/nexus/content/groups/public//</url><releases><enabled>true</enabled></releases><snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy><checksumPolicy>fail</checksumPolicy></snapshots></repository></repositories></project>
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>Archetype Created Web Application</display-name><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/spring-*.xml</param-value></context-param><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 配置 SpringMVC需要加载的配置文件 spring-mvc.xml --><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
二、配置文件
企业中的配置文件一般会放在WEB-INF下面,因为外部请求不到
2.1.spring-context.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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><context:component-scan base-package="com.gblfy" annotation-config="true"/><!--<context:annotation-config/>--><aop:aspectj-autoproxy/><import resource="spring-datasource.xml"/></beans>
2.2. spring-datasource.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:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><context:component-scan base-package="com.gblfy" annotation-config="true"/><!--引入数据库配置文件--><context:property-placeholder location="/WEB-INF/config/jdbc.properties"/><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${db.driverClassName}"/><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="maxActive" value="${db.maxActive}"/><!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --><property name="maxIdle" value="${db.maxIdle}"/><!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --><property name="minIdle" value="${db.minIdle}"/><!-- 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制 --><property name="maxWait" value="${db.maxWait}"/><!--#给出一条简单的sql语句进行验证 --><!--<property name="validationQuery" value="select getdate()" />--><property name="defaultAutoCommit" value="${db.defaultAutoCommit}"/><!-- 回收被遗弃的(一般是忘了释放的)数据库连接到连接池中 --><!--<property name="removeAbandoned" value="true" />--><!-- 数据库连接过多长时间不用将被视为被遗弃而收回连接池中 --><!--<property name="removeAbandonedTimeout" value="120" />--><!-- #连接的超时时间,默认为半小时。 --><property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdleTimeMillis}"/><!--# 失效检查线程运行时间间隔,要小于MySQL默认--><property name="timeBetweenEvictionRunsMillis" value="40000"/><!--# 检查连接是否有效--><property name="testWhileIdle" value="true"/><!--# 检查连接有效性的SQL语句--><property name="validationQuery" value="SELECT 1 FROM dual"/></bean><!--更新为 myabtisplus--><bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property></bean><bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.gblfy.dao"/></bean><!-- 使用@Transactional进行声明式事务管理需要声明下面这行 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/><!-- 事务管理 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/><property name="rollbackOnCommitFailure" value="true"/></bean></beans>
2.3. spring-mvc.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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.gblfy" annotation-config="true"/><mvc:annotation-driven></mvc:annotation-driven><!-- 引用静态资源文件映射路径 --><mvc:resources location="/WEB-INF/images/" mapping="/images/**"/><!-- 定义跳转的文件的前后缀 ,视图模式配置 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"/><property name="suffix" value=".jsp"/></bean><!-- 注解扫描 --><mvc:annotation-driven></mvc:annotation-driven><!-- 文件上传 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="10485760"/> <!-- 10m --><property name="maxInMemorySize" value="4096"/><property name="defaultEncoding" value="UTF-8"></property></bean></beans>
2.4. jdbc.properties
#数据库连接
#适用于mysql 6.x及以上
db.driverClassName=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ssm?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT
db.username=root
db.password=rootdb.initialSize = 20
db.maxActive = 50
db.maxIdle = 20
db.minIdle = 10
db.maxWait = 10
db.defaultAutoCommit = true
db.minEvictableIdleTimeMillis = 3600000
2.5. logback.xml
此文件放在resources下面
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false"><!-- 定义参数常量 --><!-- TRACE<DEBUG<INFO<WARN<ERROR --><!-- logger.trace("msg") logger.debug... --><property name="log.level" value="debug"/><property name="log.maxHistory" value="30"/><property name="log.filePath" value="${catalina.base}/logs/webapps"/><property name="log.pattern"value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"/><!-- 控制台输出设置 --><appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>${log.pattern}</pattern></encoder></appender><!-- DEBUG级别文件记录 --><appender name="debugAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- 文件路径 --><file>${log.filePath}/debug.log</file><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!-- 文件名称 --><fileNamePattern>${log.filePath}/debug/debug.%d{yyyy-MM-dd}.log.gz</fileNamePattern><!-- 文件最大保存历史数量 --><maxHistory>${log.maxHistory}</maxHistory></rollingPolicy><encoder><pattern>${log.pattern}</pattern></encoder><filter class="ch.qos.logback.classic.filter.LevelFilter"><level>DEBUG</level><onMatch>ACCEPT</onMatch><onMismatch>DENY</onMismatch></filter></appender><!-- INFO --><appender name="infoAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- 文件路径 --><file>${log.filePath}/info.log</file><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!-- 文件名称 --><fileNamePattern>${log.filePath}/info/info.%d{yyyy-MM-dd}.log.gz</fileNamePattern><!-- 文件最大保存历史数量 --><maxHistory>${log.maxHistory}</maxHistory></rollingPolicy><encoder><pattern>${log.pattern}</pattern></encoder><filter class="ch.qos.logback.classic.filter.LevelFilter"><level>INFO</level><onMatch>ACCEPT</onMatch><onMismatch>DENY</onMismatch></filter></appender><logger name="com.gblfy.order" level="${log.level}" additivity="true"><appender-ref ref="debugAppender"/><appender-ref ref="infoAppender"/></logger><root level="info"><appender-ref ref="consoleAppender"/></root>
</configuration>
三、基础类
3.1. 实体类
package com.gblfy.entity;import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("user")
public class User extends Model<User> {private Long id;private String name;private Integer age;private String email;}
3.2. 接口类
package com.gblfy.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gblfy.entity.User;public interface UserMapper extends BaseMapper<User> {
}
3.3. 接口映射xml
此文件放在resources下面的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.gblfy.dao.UserMapper"><resultMap type="com.gblfy.entity.User" id="UserMap"><result property="id" column="id" jdbcType="INTEGER"/><result property="name" column="name" jdbcType="VARCHAR"/><result property="age" column="age" jdbcType="INTEGER"/><result property="email" column="email" jdbcType="VARCHAR"/></resultMap>
</mapper>
3.4. service接口
package com.gblfy.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.gblfy.entity.User;public interface UserService extends IService<User> {
}
3.5. 接口实现类
package com.gblfy.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblfy.dao.UserMapper;
import com.gblfy.entity.User;
import com.gblfy.service.UserService;
import org.springframework.stereotype.Service;@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
}
3.6. 控制层
package com.gblfy.controller;import com.gblfy.entity.User;
import com.gblfy.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import java.util.List;@RestController
@RequestMapping("user")
public class UserController {/*** 服务对象*/@Resourceprivate UserService userService;/*** 通过主键查询单条数据** @param id 主键* @return 单条数据*/@GetMapping("selectUserById")public User selectUserById(Long id) {return this.userService.getById(id);}/*** 查询用户列表** @return List<User>*/@GetMapping("queryList")public List<User> queryList() {return this.userService.list();}}
四、数据库方面
4.1. 创建数据库
创建ssm数据库 编码格式为utf-8
4.2. 初始化表结构
/*Navicat Premium Data TransferSource Server : 127.0.0.1Source Server Type : MySQLSource Server Version : 50721Source Host : 127.0.0.1:3306Source Schema : ssmTarget Server Type : MySQLTarget Server Version : 50721File Encoding : 65001Date: 14/03/2020 20:23:26
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` bigint(20) NOT NULL COMMENT '主键ID',`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '姓名',`age` int(11) NULL DEFAULT NULL COMMENT '年龄',`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'Jone', 18, 'test1@baomidou.com');
INSERT INTO `user` VALUES (2, 'Jack', 20, 'test2@baomidou.com');
INSERT INTO `user` VALUES (3, 'Tom', 28, 'test3@baomidou.com');
INSERT INTO `user` VALUES (4, '郭轩', 26, 'test4@baomidou.com');
INSERT INTO `user` VALUES (5, '郭振', 26, 'test5@baomidou.com');
INSERT INTO `user` VALUES (1238735228017610754, '郭雨昕', 2, 'gblfy@qq.com');
INSERT INTO `user` VALUES (1238735794525503489, '郭雨泽', 22, 'gblfy@qq.com');SET FOREIGN_KEY_CHECKS = 1;
五、浏览器验证
5.1. 启动项目
5.2. 浏览器测试
http://localhost:8080/user/queryList
5.3. 源码地址
https://gitee.com/gb_90/ssm-upgrade
项目布局: