步骤一:创建 Maven web 项目
步骤二:添加 pom.xml 相关依赖包
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.binge</groupId>
<artifactId>ssmdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<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>8.0.18</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>
</project>
步骤三:在 resources 目录下分别创建 springmvc.xml 和 spring-config.xml 两个 IoC 容器
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.binge"/>
<!-- 配置允许访问静态资源 -->
<mvc:default-servlet-handler />
<!-- 配置全局 CORS -->
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
</beans>
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.binge"/>
<!-- 引入数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${spring.datasource.driver-class-name}"/>
<property name="url" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
</bean>
<!-- MyBatis 扫描 mapper -->
<mybatis:scan base-package="com.binge.dao"/>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--设置entity实体类路径-->
<property name="typeAliasesPackage" value="com.binge.entity" />
<!--设置mapper映射文件路径-->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
</beans>
database.properties
spring.datasource.url=jdbc:mysql://localhost:3306/binge?characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
步骤四:修改 web.xml 文件
<?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>
步骤五:在 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.binge.dao.UserMapper">
<insert id="insert" parameterType="com.binge.entity.UserEntity" keyProperty="id" useGeneratedKeys="true">
<![CDATA[ INSERT INTO `tb_user` (name) VALUES (#{name})]]>
</insert>
<select id="getList" resultType="com.binge.entity.UserEntity">
<![CDATA[
SELECT id,name FROM tb_user
]]>
</select>
</mapper>
步骤六:在 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.binge.util" level="info" />
</configuration>
步骤七:在 src/main 下创建 java 包以及子包
包目录结构如下:
UserController.java
package com.binge.controller;
import com.binge.dto.UserDto;
import com.binge.entity.UserEntity;
import com.binge.service.IUserService;
import com.binge.util.ResultVo;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 binge
* @Description 用户页面控制器
* @date 2023年09月17日 下午 3:38
*/
@RestController
@Slf4j
public class UserController {
@Resource
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);
}
}
UserMapper.java
package com.binge.dao;
import com.binge.dto.UserDto;
import com.binge.entity.UserEntity;
import java.util.List;
/**
* @author binge
* @Description 用户映射器接口
* @date 2023年09月11日 下午 2:31
*/
public interface UserMapper {
void insert(UserDto user);
List<UserEntity> getList();
}
UserDto.java
package com.binge.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author binge
* @Description 用户参数
* @date 2023年09月17日 下午 3:37
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
private Integer id;
private String name;
}
UserEntity.java
package com.binge.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author binge
* @Description 用户实体类
* @date 2023年09月11日 下午 2:29
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {
private Integer id;
private String name;
}
UserServiceImpl.java
package com.binge.service.impl;
import com.binge.dao.UserMapper;
import com.binge.dto.UserDto;
import com.binge.entity.UserEntity;
import com.binge.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* @author binge
* @Description 用户业务实现类
* @date 2023年09月11日 下午 2:38
*/
@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.copyProperties(user,userEntity);
return userEntity;
}
@Transactional
@Override
public List<UserEntity> getList() {
List<UserEntity> list = userMapper.getList();
return list;
}
}
IUserService.java
package com.binge.service;
import com.binge.dto.UserDto;
import com.binge.entity.UserEntity;
import java.util.List;
/**
* @author binge
* @Description 用户业务接口
* @date 2023年09月11日 下午 2:36
*/
public interface IUserService {
UserEntity insert(UserDto user);
List<UserEntity> getList();
}
ResultVo.java
package com.binge.util;
import lombok.Data;
import java.io.Serializable;
/**
* Ajax 请求统一响应工具类
*/
@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;
}
}
步骤八:启动 Tomcat
控制台没有报错,页面显示 Hello,World!
,说明 Tomcat 启动成功
步骤九:启动 Postman 进行接口测试
接口测试成功,SSM 框架集成完成:)
标签:集成,java,框架,binge,springframework,SSM,org,import,com From: https://www.cnblogs.com/binbingg/p/17709167.html