文章目录
一、SSM 整合步骤
1、导入需要使用的jar包
(1)Spring的包,包含了Spring MVC的包
(2)SpringAOP的插件包
(3)响应JSON类型的视图信息
(4)SpringMVC响应JSON数据的依赖包
(5)Mybatis和JDBC
(6)C3P0连接池和依赖包
(7)SpringMVC 后端参数校验的jar包
(8)JDBC连接数据库的jar包
2、加载 Spring
(1)加载Spring需要在web.xml中加载Spring的监听器
<!--加载spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring配置文件的地址-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
(2)根据配置在src目录下新建applicationContext.xml
文件,在文件中定义好schema校验
<?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: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/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</beans>
3、加载 SpringMVC
(1)在web.xml中配置核心控制器
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(2)在web.xml中加载Spring提供的字符编码过滤器
<!--配置字符编码过滤器处理POST方式提交的中文乱码-->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
(3)在web.xml中配置PUT提交方式的参数处理过滤器
<!--PUT提交方式参数处理器-->
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
(4)在src下新建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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--扫包-->
<context:component-scan base-package="com.ssm.controller"></context:component-scan>
<!--开启注解驱动 -->
<mvc:annotation-driven/>
<!--静态资源处理器-->
<mvc:resources location="/WEB-INF/resource/page/" mapping="/page/**"/>
<mvc:resources location="/WEB-INF/resource/js/" mapping="/js/**"/>
<mvc:resources location="/WEB-INF/resource/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/resource/images/" mapping="/images/**"/>
</beans>
(5)如果项目中需要做文件上传,需要在springmvc的配置文件中定义多部件处理器
<!-- 配置多部件解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大字节数 -->
<property name="maxUploadSize" value="20971520"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
4、整合 mybatis
整合 mybatis 就像将原本由 Mybatis 负责创建的数据层代理对象委托给Spring来创建,所以我们必须提供数据源、SqlSessionFactory,以及一些 mybatis 的属性。
(1)配置C3P0数据源
先在src下配置一个jdbc.properties
资源文件,用来描述连接数据库的信息以及c3p0的常用信息
#jdbc 连接信息
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/ebuy?useUnicode=true&characterEncoding=utf-8
jdbc.user = root
jdbc.password =
#c3p0 信息
c3p0.minPoolSize = 10
c3p0.maxPoolSize = 50
c3p0.initialPoolSize = 20
c3p0.maxIdleTime = 60
c3p0.acquireIncrement = 10
c3p0.checkoutTimeout=6000
c3p0.idleConnectionTestPeriod=600
(2)在applicationContext.xml
中配置资源文件解析器
<!--资源文件解析器-->
<context:property-placeholder location="classpath:jdbc.properties" />
使用bean标签,配置数据源对象
<!--配置C3P0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 提供数据库连接信息和连接池的常用信息 -->
<!-- 驱动类 -->
<property name="driverClass" value="${jdbc.driverClass}" />
<!-- 连接数据库的地址 -->
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<!-- 连接数据库的用户名 -->
<property name="user" value="${jdbc.user}" />
<!-- 连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
<!-- 最小连接数 -->
<property name="minPoolSize" value="${c3p0.minPoolSize}"></property>
<!-- 初始化连接数 -->
<property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
<!-- 自增长连接数 -->
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"></property>
<!-- 连接对象空闲时间 超出10分钟销毁 -->
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"></property>
<!-- 连接数据库的等待时间 超出等待时间 抛出异常 -->
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"></property>
<!-- 检查连接的间隔时间 -->
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"></property>
</bean>
(3)使用数据源配置SqlSessionFactoryBean
<!--创建sqlSession工厂对象 -->
<!--在此之前要保证mybatis的包和mybatis给spring提供的插件包都要导入到项目中 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据层查询文件(XxxMapper.xml文件)的地址 -->
<property name="mapperLocations" value="classpath:com/ssm/mapper/*Mapper.xml" />
<!-- 配置实体类的别名 -->
<property name="typeAliasesPackage" value="com.ssm.entity" />
<!--将Spring创建的c3p0连接池对象 注入给工厂对象 -->
<property name="dataSource" ref="dataSource" />
</bean>
(4)定义数据库接口扫描器,Spring 会扫描数据层接口所在包,同时生成该包下的所有数据层接口的实现类代理对象
<!-- 创建查询接口信息配置对象,配置查询接口的包名,
所有这个包下的接口,Spring会生成代理对象(XxxMapper接口的实现类对象) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.mapper" />
</bean>
5、Spring扫描业务层的包创建业务层对象以及声明式事务
(1)扫描业务层的包
<!-- 扫描业务层的注解-->
<context:component-scan base-package="com.ssm.service"></context:component-scan>
(2)配置声明式事务
① 使用bean标签创建事务管理器对象
<!--创建事务管理器对象 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--将Spring创建的数据源对象注入到事务管理器对象中 -->
<property name="dataSource" ref="dataSource" />
</bean>
② 配置通知
<!--事务通知-->
<!--定义在程序执行到切入点以后 具体的切面织入方式(哪些方法需要使用事务管理 哪些不需要)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<!--配置方法名的规则 前缀是insert delete update的所有方法 需要事务控制-->
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<!--其他方法不需要事务控制 read-only为只读 -->
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
③ 配置切面
<!--定义切面-->
<aop:config>
<!--定义切入点-->
<aop:pointcut expression="execution(* com.ssm.service.impl.*.*(..))" id="transactionPoint"/>
<!--织入 在某个切入点执行通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPoint"/>
</aop:config>
二、SSM 框架整合示例
1、新建 maven 工程,导入对应 jar 包结构
2、配置文件
(1)maven 工程的 pom.xml 文件
<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.ssm</groupId>
<artifactId>SSH_Anno</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SSH_Anno Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.1.6.RELEASE</spring.version>
<jackson.version>2.9.8</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- spring -->
<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-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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- mybatis 包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mybatis spring 插件 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Final</version>
</dependency>
</dependencies>
<build>
<finalName>SSM_Anno</finalName>
<plugins>
<!-- 修改maven默认的JRE编译版本,1.8代表JRE编译的版本,根据自己的安装版本选择1.7或1.8 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)web.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!--配置spring配置文件的地址-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--加载spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载SpringMVC配置核心控制器 -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置字符编码过滤器处理POST方式提交的中文乱码-->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!-- RestFul风格设计中PUT、PATCH提交方式参数处理器-->
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
(3)jbdc.properties 文件
#jdbc\u8FDE\u63A5\u4FE1\u606F
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/kunkunstore?useUnicode=true&characterEncoding=utf-8
jdbc.user = root
jdbc.password =admin
#c3p0\u5404\u9879\u5C5E\u6027
c3p0.minPoolSize = 10
c3p0.maxPoolSize = 50
c3p0.initialPoolSize = 20
c3p0.maxIdleTime = 60
c3p0.acquireIncrement = 1
c3p0.checkoutTimeout=6000
c3p0.idleConnectionTestPeriod=600
(4)application.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: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/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!--扫描包的地址 -->
<context:component-scan base-package="com.ssm" />
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置c3p0数据源 -->
<!--配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 提供数据库连接信息和连接池的常用信息 -->
<!-- 驱动类 -->
<property name="driverClass" value="${jdbc.driverClass}" />
<!-- 连接数据库的地址 -->
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<!-- 连接数据库的用户名 -->
<property name="user" value="${jdbc.user}" />
<!-- 连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
<!-- 最小连接数 -->
<property name="minPoolSize" value="${c3p0.minPoolSize}"></property>
<!-- 初始化连接数 -->
<property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
<!-- 自增长连接数 -->
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"></property>
<!-- 连接对象空闲时间 超出10分钟销毁 -->
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"></property>
<!-- 连接数据库的等待时间 超出等待时间 抛出异常 -->
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"></property>
<!-- 检查连接的间隔时间 -->
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"></property>
</bean>
<!--创建sqlSession工厂对象 -->
<!--在此之前要保证mybatis的包和mybatis给spring提供的插件包都要导入到项目中 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据层查询文件(XxxMapper.xml文件)的地址 -->
<property name="mapperLocations" value="classpath:com/ssm/mapper/*Mapper.xml" />
<!-- 配置实体类的别名 -->
<property name="typeAliasesPackage" value="com.ssm.entity" />
<!--将Spring创建的c3p0连接池对象 注入给工厂对象 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置mapper扫描器 spring会扫描数据层接口的包 该包下所有的接口 都会主动生成对应的实现类代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.mapper" />
</bean>
<!--创建事务管理器对象 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--将Spring创建的数据源对象注入到事务管理器对象中 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--事务通知 -->
<!--定义在程序执行到切入点以后 具体的切面织入方式(哪些方法需要使用事务管理 哪些不需要) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置方法名的规则 前缀是insert delete update的所有方法 需要事务控制 -->
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<!--其他方法不需要事务控制 read-only为只读 -->
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!--定义切面 -->
<aop:config>
<!--定义切入点 -->
<aop:pointcut expression="execution(* com.ssm.service.imp.*.*(..))" id="transactionPoint" />
<!--织入 在某个切入点执行通知 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPoint" />
</aop:config>
</beans>
(5)spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.ssm.controller"></context:component-scan>
<mvc:annotation-driven />
<!-- 静态资源处理器 -->
<mvc:resources location="/WEB-INF/resources/page/" mapping="/page/**"/>
<mvc:resources location="/WEB-INF/resources/page/logins" mapping="/page/logins/**"/>
<mvc:resources location="/WEB-INF/resources/page/user" mapping="/page/user/**"/>
<mvc:resources location="/WEB-INF/resources/js/" mapping="/js/**"/>
<mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/resources/img/" mapping="/img/**"/>
<mvc:resources location="/WEB-INF/resources/fonts/" mapping="/fonts/**"/>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大字节数 -->
<property name="maxUploadSize" value="20971520" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
</beans>
3、Java 代码
(1)Controller 层的 ProductsController 类
@RestController
@RequestMapping("products")
public class ProductsController {
@Resource
private ProductsService ps;
@GetMapping
public Result select() throws Exception {
return new Result(ps.select(), null, "success", null);
}
@GetMapping("/{pId}")
public Result selectById(@PathVariable("pId")int pId) throws Exception{
return new Result(null,ps.selectById(pId),"success",null);
}
@PostMapping
public Result insert(@Validated Products products,BindingResult br) throws Exception {
if(br.hasErrors()) {
throw new ParamException();
}
ps.insert(products);
return new Result(null,null,"success",null);
}
@PutMapping
public Result updateById(@Validated Products products,BindingResult br) throws Exception {
System.out.println(products);
if(br.hasErrors()) {
throw new ParamException();
}
ps.updateById(products);
return new Result(null,null,"success",null);
}
@DeleteMapping("/{pId}")
public Result deleteById(@PathVariable("pId")int pId) throws Exception {
ps.deleteById(pId);
return new Result(null,null,"success",null);
}
}
(2)Service 层
① Service 接口层 ProductsService 类
public interface ProductsService {
/**
* <p>Description:业务层查询所有数据的方法 </p>
*/
public List<Products> select() throws Exception;
/**
* <p>Description:业务层根据id查询数据的方法 </p>
*/
public Object selectById(int pId) throws Exception;
/**
* <p>Description: 业务层根据id更新数据的方法</p>
*/
public void updateById(Products products) throws Exception;
/**
* <p>Description: 业务层新增数据的方法</p>
*/
public void insert(Products products) throws Exception;
/**
* <p>Description: 业务层根据id删除数据的方法</p>
*/
public void deleteById(int pId) throws Exception;
}
② Service 实现层 ProductsServiceImp 类
@Service
public class ProductsServiceImp implements ProductsService{
@Resource
private ProductsMapper mapper;
/*
* <p>Description:业务接口层查询所有数据的方法 </p>
*/
@Override
public List<Products> select() throws Exception {
return mapper.selectByExample(null);
}
/*
* <p>Description: 业务接口层根据id查询数据的方法</p>
*/
@Override
public Object selectById(int pId) throws Exception {
return mapper.selectByPrimaryKey(pId);
}
/*
* <p>Description: 业务接口层根据id更新数据的方法</p>
*/
@Override
public void updateById(Products products) throws Exception {
mapper.updateByPrimaryKeySelective(products);
}
/*
* <p>Description: 业务接口层新增数据的方法</p>
*/
@Override
public void insert(Products products) throws Exception {
mapper.insert(products);
}
/*
* <p>Description: 业务接口层根据id删除数据的方法</p>
*/
@Override
public void deleteById(int pId) throws Exception {
mapper.deleteByPrimaryKey(pId);
}
}
(3)实体类层
① Products 类
public class Products {
private Integer pId;
@NonNull
@NotEmpty
private String pName;
@NonNull
private Double pPrice;
@NonNull
private Integer pCount;
@NonNull
@NotEmpty
private String pClass;
@NonNull
@NotEmpty
private String pAttribute;
private Integer pTypeid;
//省略set、get方法
}
② Result 类
public class Result {
private List list; //集合封装
private Object object; //对象封装
private String code; //反馈信息
private String message; //显示错误信息
public Result() {}
public Result(List list, Object object, String code, String message) {
this.list = list;
this.object = object;
this.code = code;
this.message = message;
}
//省略set、get方法
}
(4)ProductsMapper 类,定义相关方法
public interface ProductsMapper {
int deleteByPrimaryKey(Integer pId);
int insert(Products record);
int insertSelective(Products record);
List<Products> selectByExample(ProductsExample example);
Products selectByPrimaryKey(Integer pId);
int updateByPrimaryKeySelective(Products record);
int updateByPrimaryKey(Products record);
}
(5)统一异常处理层
① 自定义异常类
public class ParamException extends Exception{
}
② ExceptionResolver 类
@Component
public class ExceptionResolver implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) {
FastJsonJsonView view = new FastJsonJsonView();
ex.printStackTrace();
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", "error");
if(ex instanceof ParamException) {
map.put("message", "参数错误");
}else {
map.put("message", "服务器异常");
}
view.setAttributesMap(map);
ModelAndView mav = new ModelAndView();
mav.setView(view);
return mav;
}
}
4、前端发送请求页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/SSM_Anno/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="/SSM_Anno/js/jquery.serializejson.js"></script>
</head>
<body>
<a href="javascript:" onclick="selectAll()">查询所有</a>
<table id="table">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>库存</td>
<td>分类</td>
<td>属性</td>
</tr>
</table>
<form id="insert-form">
<input name="pName"><br>
<input name="pPrice"><br>
<input name="pCount"><br>
<input name="pClass"><br>
<input name="pAttribute"><br>
<input type="button" onclick="insert()" value="新增">
</form>
<input id="pId" placeholder="请输入用户id"><input type="button" value="搜索用户" onclick="selectById()">
<form id="update-form">
<input type="hidden" name="pId">
<input name="pName"><br>
<input name="pPrice"><br>
<input name="pCount"><br>
<input name="pClass"><br>
<input name="pAttribute"><br>
<input type="button" onclick="updateById()" value="修改">
</form>
<script type="text/javascript">
function selectAll(){
$.ajax({
url: "/SSM_Anno/products",
type: "get",
dataType: "json",
success:function(data){
console.log(data);
$(".tr").remove();
for(var i=0;i<data.list.length;i++){
$("#table").append("<tr class='tr' id='deleted"+data.list[i].pId+"'>"+
"<td>"+data.list[i].pId+"</td>"+
"<td>"+data.list[i].pName+"</td>"+
"<td>"+data.list[i].pPrice+"</td>"+
"<td>"+data.list[i].pCount+"</td>"+
"<td>"+data.list[i].pClass+"</td>"+
"<td>"+data.list[i].pAttribute+"</td>"+
"<td><a href='javascript:' onclick='deleteById("+data.list[i].pId+")'>删除</a></td>"+
"</tr>");
}
}
});
}
function deleteById(pId){
$.ajax({
url: "/SSM_Anno/products/"+pId,
type: "delete",
dataType: "json",
success:function(data){
console.log(data.code);
$("tr[id=deleted"+pId+"]").remove();
}
});
}
function insert(){
$.ajax({
url: "/SSM_Anno/products",
type: "post",
data: $("#insert-form").serializeJSON(),
dataType: "json",
success:function(data){
console.log(data.code);
selectAll();
}
});
}
function updateById(){
$.ajax({
url:"/SSM_Anno/products",
type:"put",
data:$("#update-form").serializeJSON(),
dataType:"json",
success:function(data){
console.log(data.code);
selectAll();
}
});
}
function selectById(){
$.ajax({
url:"/SSM_Anno/products/"+$("#pId").val(),
type:"get",
dataType:"json",
success:function(data){
$("#update-form input[name=pId]").val(data.object.pId);
$("#update-form input[name=pName]").val(data.object.pName);
$("#update-form input[name=pPrice]").val(data.object.pPrice);
$("#update-form input[name=pCount]").val(data.object.pCount);
$("#update-form input[name=pClass]").val(data.object.pClass);
$("#update-form input[name=pAttribute]").val(data.object.pAttribute);
}
});
}
</script>
</body>
</html>