5、spring+springmvc+mybatis整合
5.1、项目技术需求分析
1.使用ssm+layui技术开发 对用户表数据实现增删改查
采用前后端分离架构模式
5.2、SSM环境的整合之提供增删改查
整合数据库表结构
CREATE TABLE `mayikt_users` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`age` int DEFAULT NULL,
`addres` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8mb3;
整合maven依赖
spring/springmvc/mybatis
<?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>com.mayikt</groupId>
<artifactId>mayikt-ssm02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mayikt-ssm02 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--整合springmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--使用alibaba数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--使用@ResponseBody 能够响应数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
实体类层
com.mayikt.entity
数据库访问层
com.mayikt.mapper
业务逻辑层
com.mayikt.service
控制层
com.mayikt.controller
5.3、SSM环境的整合之配置整合
JdbcConfig
package com.mayikt.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class JdbcConfig {
/**
* 定义数据源配置
*
* @return
*/
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/mayikt?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT");
druidDataSource.setUsername("root");
druidDataSource.setPassword("root");
return druidDataSource;
}
/**
* 整合事务
*
* @param dataSource
* @return
*/
@Bean
public PlatformTransactionManager platformTransactionManager(@Autowired DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager =
new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
MybatisConfig
package com.mayikt.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatisConfig {
/**
* mybatis相关配置
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactory(@Autowired DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean =
new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 实体层包
sqlSessionFactoryBean.setTypeAliasesPackage("com.mayikt.entity");
return sqlSessionFactoryBean;
}
}
SpringConfig
package com.mayikt.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({"com.mayikt.service"})
//开启事务
@EnableTransactionManagement
@Import({MybatisConfig.class, JdbcConfig.class})
@MapperScan("com.mayikt.mapper")
public class SpringConfig {
}
SpringMVCConfig
package com.mayikt.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@Configuration
@ComponentScan("com.mayikt.controller")
public class SpringMVCConfig {
}
ServletConfig
package com.mayikt.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMVCConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
5.4、接口响应状态码
统一规范返回数据的格式,此处以json格式为例。返回数据应包含:返回状态码、返回状态信息、具体数据。
格式规范如下:
{
"code":"200",
"msg":"ok",
"data": {
//json格式的具体数据
}
}
查询到数据
{
"code":"200",
"msg":"ok",
"data": {
"userName":"mayikt",
"age":22
}
}
前端 ajax技术
if(code==200){
"data": {
"userName":"mayikt",
"age":22
}
}
没有查询到数据
{
"code":"500",
"msg":"fail",
"data": {
}
}
新增数据
{
"code":"500",
"msg":"插入失败",
"data": {
}
}
前端:
if(code==200){
alert(" "msg":"插入成功"")
}
Api Code状态码
1** | 服务器收到请求,需要请求者继续执行操作 |
2** | 操作被成功接收并处理 |
3** | 重定向,需要进一步的操作以完成请求 |
4** | 客户端错误,请求包含语法错误或无法完成请求 |
5** | 服务器错误,服务器在处理请求的过程中发生了错误 |
如何封装接口响应状态码
package com.mayikt.controller;
import java.util.HashMap;
public class BaseController {
/**
* 提供处理请求响应成功的情况下
*
* @param data
* @return
*/
public HashMap<String, Object> setResultOk(Object data) {
return setResult(200, "ok", data);
}
public HashMap<String, Object> setResultSuccess(String msg) {
return setResult(200, msg, null);
}
/**
* 提供处理请求失败情况下
*
* @param msg
* @return
*/
public HashMap<String, Object> setResultError(String msg) {
return setResult(500, msg, null);
}
/**
* @param code code 200 处理成功 500 处理失败
* @param msg 响应错误内容
* @param data 响应的数据
* @return
*/
public HashMap<String, Object> setResult(Integer code, String msg, Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
result.put("data", data);
return result;
}
}
5.5、整合全局捕获异常
当系统发生错误时,统一将系统错误日志 返回输出
package com.mayikt.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map<String, Object> handleException(HttpServletRequest h, Exception e) {
System.out.println("自定义异常:" + e);
return setResultError("系统发生了错误!");
}
}