综上所述,SSM集成可以充分发挥各个框架的优势,提供了一种高效、灵活、易于维护的开发方式,使得Java Web开发更加方便和高效。通过SSM的集成,开发者可以快速搭建起一个稳定可靠的Web应用,并且在后续的开发和维护过程中,能够更加方便地处理业务需求和数据库操作。
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
选择File ---> New ---> Project
选择Maven模板
填写项目的基本信息 ---> Next
配置自己的Maven环境 ---> Finish
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring.version>5.3.6</spring.version>
</properties>
<dependencies>
<!-- 添加springmvc依赖 -->
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- JSTL 依赖包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--数据校验依赖包-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<!--文件上传依赖包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- 添加jackson配置 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!-- 数据库驱动依赖(根据你使用的数据库选择) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 日志整合 slf4j门面设计模式与 log4j或log4j2一起使用-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 日志-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
在src/main/resources文件夹下创建 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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<!--开启SpringMVC注解驱动-->
<mvc:annotation-driven />
<!-- springmvc容器(也就是一个spring容器)会扫描指定包中的组件,将其注册到springmvc容器中 -->
<context:component-scan base-package="com.qrj"/>
<!-- 配置允许访问静态资源 -->
<mvc:default-servlet-handler />
<!-- 配置全局 CORS -->
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
</beans>
在src/main/resources文件夹下创建database.properties文件
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/spring_mybatis?useSSL=false
db.username=root
db.password=123456
在src/main/resources文件夹下创建spring-config.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"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
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://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<!-- 自动扫描注解 -->
<context:component-scan base-package="com.qrj"/>
<!-- 引入数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!-- MyBatis 扫描 mapper -->
<mybatis:scan base-package="com.qrj.dao"/>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--设置entity实体类路径-->
<property name="typeAliasesPackage" value="com.qrj.entity" />
<!--设置mapper映射文件路径-->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
</beans>
在src/main/resources文件夹下创建logback.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds">
<contextName>logback</contextName>
<property name="log.path" value="F:\\logback.log" />
<!--日志输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<!-- 日志输出到文件 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
</pattern>
</encoder>
</appender>
<!-- 根日志输出级别-->
<root level="debug">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<!-- 指定包日志输出级别-->
<logger name="com.qrj.util" level="info" />
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置Spring容器加载配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!-- 监听器(spring文件相关的监听器)-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation 用来指定springmvc配置文件的位置,文件名称不一定要叫springmvc,大家可以随意起名 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- load-on-startup:表示web容器启动的时,当前对象创建的顺序,值越小初始化越早,大于等于0 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 设置 CharacterEncodingFilter 过滤器,这个类会对request和response设置字符集编码,解决中文乱码问题(优先级最高) -->
<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>
</web-app>
在src/main/java目录下创建com.qrj.entity包,在包下面创建UserEntity实体类。
package com.qrj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: qrj
* @description 用户实体类
* @Date: 2023/9/19 14:51
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {
private Integer id;
private String name;
private Integer age;
private String gender;
}
在src/main/java目录下创建com.qrj.dto包,在包下面创建UserDto参数类。
package com.qrj.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author: qrj
* @description 用户参数
* @Date: 2023/9/19 14:52
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
private Integer id;
private String name;
private Integer age;
private String gender;
}
在src/main/java目录下创建com.qrj.dao包,在包下面创建UserMapper接口。
package com.qrj.dao;
import com.qrj.dto.UserDto;
import com.qrj.entity.UserEntity;
import java.util.List;
/**
* @author: qrj
* @description 用户映射接口
* @Date: 2023/9/19 14:52
*/
public interface UserMapper {
void insert(UserDto user);
List<UserEntity> getList();
}
注意这里创建的UserMapper映射文件要和之前创建的UserMapper接口文件相对应。
在src/main/resources文件夹下创建mapper文件夹,并在mapper文件夹下创建UserMapper.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.qrj.dao.UserMapper">
<insert id="insert" parameterType="com.qrj.entity.UserEntity" keyProperty="id" useGeneratedKeys="true">
INSERT INTO USER ( name, age, gender )
VALUE
( #{name}, #{age} , #{gender} )
</insert>
<select id="getList" resultType="com.qrj.entity.UserEntity">
SELECT
*
FROM
USER;
</select>
</mapper>
在src/main/java目录下创建com.qrj.vo包,在包下面创建ResultVo工具类。
package com.qrj.vo;
import lombok.Data;
import java.io.Serializable;
/**
* @author: qrj
* @description Ajax 请求统一响应工具类
* @Date: 2023/9/19 14:58
*/
@Data
public class ResultVo<T> implements Serializable {
private static final long serialVersionUID = 1L;
//状态码
private int code;
//状态码描述
private String message;
//数据结果,泛型,可以是列表、单个对象、数字、布尔值等
private T data;
public ResultVo() {
}
public ResultVo(int code, String message) {
this.code = code;
this.message = message;
}
public static <T> ResultVo<T> success(T data) {
ResultVo<T> resultVo = new ResultVo<>();
resultVo.setCode(200);
resultVo.setMessage("ok");
resultVo.setData(data);
return resultVo;
}
}
在src/main/java目录下创建com.qrj.service包,在包中创建IUserService接口
package com.qrj.service;
import com.qrj.dto.UserDto;
import com.qrj.entity.UserEntity;
import java.util.List;
/**
* @author: qrj
* @description 用户业务接口
* @Date: 2023/9/19 14:54
*/
public interface IUserService {
UserEntity insert(UserDto user);
List<UserEntity> getList();
}
在com.qrj.service包下创建Impl包,并创建UserServiceImpl实现类
package com.qrj.service.Impl;
import com.qrj.dao.UserMapper;
import com.qrj.dto.UserDto;
import com.qrj.entity.UserEntity;
import com.qrj.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: qrj
* @description 用户业务实现类
* @Date: 2023/9/19 14:57
*/
@Service //控制反转
public class UserServiceImpl implements IUserService {
@Resource //依赖注入
private UserMapper userMapper;
@Transactional(rollbackFor = Exception.class)
@Override
public UserEntity insert(UserDto user) {
userMapper.insert(user);
UserEntity userEntity = new UserEntity();
//BeanUtils用于拷贝对象 参数1:被拷贝的对象 参数2:拷贝对象
BeanUtils.copyProperties(user,userEntity);
return userEntity;
}
@Transactional
@Override
public List<UserEntity> getList() {
List<UserEntity> list = userMapper.getList();
return list;
}
}
在src/main/java目录下创建com.qrj.controller包,在包下面创建UserController页面控制器。
package com.qrj.controller;
import com.qrj.dto.UserDto;
import com.qrj.entity.UserEntity;
import com.qrj.service.IUserService;
import com.qrj.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: qrj
* @description 用户页面控制器
* @Date: 2023/9/19 14:53
*/
@RestController
@Slf4j //lombok提供的日志注解
public class UserController {
@Resource //使用 @Autowired注解 IDEA不推荐
private IUserService userService;
@PostMapping("/user")
public ResultVo<UserEntity> addUser(@RequestBody UserDto userDto) {
log.debug(userDto.toString()); //打印调试日志(接收参数)
UserEntity result = userService.insert(userDto);
log.debug(result.toString()); //打印调试日志(响应数据)
return ResultVo.success(result);
}
@GetMapping("/users")
public ResultVo<List<UserEntity>> getUsers() {
List<UserEntity> list = userService.getList();
return ResultVo.success(list);
}
}
通过Restful API接口("/user")测试添加用户功能实现
通过Restful API接口("/users")测试查找所有用户功能实现
以上功能测试完成,至此SSM框架集成成功!