现在随着Springboot的流行,我们发现在撰写一个web项目已经变得很简单了,但是好多朋友可能没有学过springmvc,直接学习的springboot,对springmvc的原理,框架的整合思路不是很了解,下来,帮助小伙伴们梳理下。
文章目录关于作者
金山老师:从事Java、大数据、Python职业化培训6年,项目管理、软件开发14年。欢迎添加我的微信号【jshand】,最近建了一些微信交流群,扫描下方二维码添加公众号,回复:进群
部分讲课录屏已经上传到bilibili,欢迎搜索“是金山老师”
- 1. SSM框架整合
- 1.1. 创建webapp骨架的项目
- 1.2. 添加依赖
- 1.3. 整合思路
- 1.4. 搭建SpringMVC框架
- 1.4.1. IOC配置文件(SpringMVC.xml)
- 1.4.2. Web.xml中配置前端控制器
- 1.4.3. 编写Controller进行测试
- 1.4.4. 发布Tomcat使用浏览器访问测试mvc程序
- 1.4.5. 配置日志组件log4j
- 1.4.5.1. 在classpath下添加log4j.properties
- 1.4.5.2. 自定义的的日志调用
- 1.4.6. 全局的异常处理器
- 1.4.7. 全局的数据校验
- 1.5. 搭建Mybatis的程序
- 1.5.1. 添加依赖
- 1.5.2. SqlMapConfig.xml
- 1.5.3. 在dao包下配置Mapper代理
- 1.5.4. 配置Mapper.xml
- 1.5.5. 将Mapper添加到SqlMapConfig.xml中
- 1.5.6. 使用main的形式访问mybatis(单元测试)
- 1.6. 将SQLSessionFactory放到IOC容器中
- 1.6.1. UserService
- 1.6.2. UserController
- 1.6.3. 使用**IOC容器自动的生成Mapper代理对象并使用容器管理
- 1.6.4. 使用mybatis工具生成Mapper接口
- 1.6.4.1. 要求mapper.java和Mapper.xml在同一个包下
- 1.6.5. 使用mybatis工具生成Mapper接口
- 1.6.6. 修改了下UserController和UserService的代码(依赖关系)
- 1.6.6.1. UserController
- 1.6.6.2. UserService
- 1.6.6.3. 测试
- 1.7. 管理事务
- 1.8. 测试的逻辑
- 2. SSM单表增删改查
- 2.1. 查询列表
- 2.1.1. TProductMapper通过工具生成 √
- 2.1.2. ProductService查询功能(依赖dao)
- 2.1.3. ProductController控制器方法查询集合
- 2.1.4. 展示列表的页面
- 2.2. 添加
- 2.2.1. 添加页面
- 2.2.2. Service的添加方法
- 2.2.3. 控制器:
- 2.2.4. 解决中文乱码
- 2.3. 修改
- 2.3.1. product_list.jsp
- 2.3.2. product_edit.jsp
- 2.3.3. Service的根据主键查询
- 2.3.4. Service的修改方法
- 2.3.5. Controller的方法
- 2.4. 删除
- 2.4.1. 在列表页中添加删除按钮,(普通的get删除、ajax删除两种情况都有)
- 2.4.2. 详见修改时的[列表页面]
- 2.4.3. 后端的Controller的删除方法
- 2.4.4. Service的删除方法
-
Spring
-
SpringMVC
-
Mybatis
Spring-容器
Spring-text
Springmvc-模块
Springmvc-jdbc
SpringMVC依赖的Jackson的json库
SpringMVC的校验框架
文件上传下载的类库
Jsp、Servlet API()
Jstl 标签库
Mybatis的类库
Mybatis的分页插件
mybatis-spring 需要使用Spring的IOC容器管理SQLSessionFactory::SQLSessionFactoryBean
数据库驱动:mysql-connector-java 5.4. 1
数据源的类库:(C3p0、DBCP、HikariCP)
事务: Springmvc-事务
事务使用的面向切面aop织入(aspectjweaver)
日志的类库:lo4j的日志
<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.0modelVersion>
<groupId>com.neuedugroupId>
<artifactId>ssmartifactId>
<version>1.0version>
<packaging>warpackaging>
<name>ssm Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.5version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.9version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.9version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.9.1version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.1.0.Finalversion>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.48version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.11version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.2.4.RELEASEversion>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
1.3. 整合思路
由spring管理SQLSessionFactory
Spring和Mybatis整合生成代理对象(通过Spring生成Mapper的代理对象)
1 )搭建Spirng(SpringMVC的程序)
-
搭建Mybatis的程序(控制台程序)
-
将SQLSessionFactory交给Spring容器管理
1) 包扫描
2) 开启mvc:annotation-driven注解驱动
3) 可以配置视图解析器(前缀、后缀)此处默认不进行配置
4) 因为RESTful风格需要mvc:default-servlet-handler 用于处理静态资源
5) 配置文件上传的解析器
<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
https://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">
<context:component-scan base-package="com.neuedu"/>
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="99999999999">property>
bean>
beans>
1.4.2. Web.xml中配置前端控制器
<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_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
1.4.3. 编写Controller进行测试
package com.neuedu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/2 15:50 02
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 第一个控制器的测试程序
* http://127.0.0.1:8080/ssm/index
*/
@RestController
public class IndexController {
@RequestMapping("/index")
public String index(){
return "index";
}
}
1.4.4. 发布Tomcat使用浏览器访问测试mvc程序
1.4.5. 配置日志组件log4j
官网:
http://logging.apache.org/log4j/1.2/manual.html
博客:
https://www.cnblogs.com/wangzhuxing/p/7753420.html
添加组件依赖(开始已经完成).
设置日志组件,
1.4.5.1. 在classpath下添加log4j.properties#配置全局的日志级别和输出方式
log4j.rootLogger=DEBUG, stdout
#单独针对org.springframework包设置级别INFO
#log4j.logger.org.springframework=INFO
#单独针对RequestMappingHandlerMapping类设置级别INFO
#log4j.logger.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=ERROR
#log4j.logger.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=DEBUG
#自定义包(自己写的)
log4j.logger.com.neuedu=NONE
#log4j.logger.com.neuedu.dao=DEBUG
#设置sql输出
#log4j.logger.com.neuedu.framework=DEBUG
#log4j.logger.java.sql.Statement=DEBUG
#log4j.logger.java.sql.PreparedStatement=DEBUG
#log4j.logger.java.sql.ResultSet=DEBUG
#设置外观(如何除数日志)
#外观ConsoleAppender ---向控制台输出,文件
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#设置日志的布局类型
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#设置输出日志的格式
log4j.appender.stdout.layout.ConversionPattern=[%p]\:%d{HH:mm:ss} %c(%L\u884C) %m%n
1.4.5.2. 自定义的的日志调用
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/2 15:50 02
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 第一个控制器的测试程序
* http://127.0.0.1:8080/ssm/index
* setting : ERROR
* DEBUG 比较多
* INFO 级别 重要一点
* ERROR 级别更高一点
*
*/
@RestController
public class IndexController {
Logger logger = Logger.getLogger(IndexController.class);
@RequestMapping("/index")
public String index(){
logger.trace("trace..............");// TRACE DEBUG INFO ERROR FATAL
logger.debug("DEBUG..............");//DEBUG INFO ERROR FATAL
logger.info("info.............."); // INFO ERROR FATAL
logger.error("error..............");//ERROR FATAL
logger.fatal("fatal..............");//FATAL
return "index";
}
}
1.4.6. 全局的异常处理器
1.4.7. 全局的数据校验略
1.5. 搭建Mybatis的程序 1.5.1. 添加依赖略
参考全局的依赖
1.5.2. SqlMapConfig.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="Mapper.xml"/>
mappers>
configuration>
1.5.3. 在dao包下配置Mapper代理
package com.neuedu.dao;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/2 16:38 02
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 测试的第一个代理接口
*/
public interface TestMapper {
public int selectUserCount();
}
1.5.4. 配置Mapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neuedu.dao.TestMapper">
<select id="selectUserCount" resultType="int">
select count(1) from t_user
select>
mapper>
1.5.5. 将Mapper添加到SqlMapConfig.xml中
1.5.6. 使用main的形式访问mybatis(单元测试)
package com.neuedu.dao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import static org.junit.Assert.*;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/2 16:43 02
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 :
*/
public class TestMapperTest {
SqlSessionFactory factory = null;
String config = "SqlMapConfig.xml";
@Before
public void setUp() throws Exception {
InputStream is = Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(is);
}
@Test
public void selectUserCount() {
SqlSession session = factory.openSession();
TestMapper dao = session.getMapper(TestMapper.class);
int count = dao.selectUserCount();
System.out.println("count:"+count);
session.close();
}
}
1.6. 将SQLSessionFactory放到IOC容器中
提前编写Controller、Service并设置依赖关系(UserController依赖UserService,UserService依赖TestMapper)
1.6.1. UserServicepackage com.neuedu.service;
import com.neuedu.dao.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:42 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的逻辑层
*/
@Service
public class UserService {
@Autowired
TestMapper testMapper;
public List queryAll(){
int count = testMapper.selectUserCount();
System.out.println("count :"+count );
return null;
}
}
1.6.2. UserController
package com.neuedu.controller;
import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:39 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的控制器
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/list")
public String list(){
List list = userService.queryAll();
return "user - list ";
}
}
启动的时候会抛出依赖失败的异常
1.6.3. 使用**IOC容器自动的生成Mapper代理对象并使用容器管理1 )配置DataSource 使用的是dbcp
2)配置SQLSessionFactoryBean
3) 配置单个TestMapper(弃用)
4)启动包扫描的形式注册多个Mapper接口的代理对象
<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
https://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">
<context:component-scan base-package="com.neuedu"/>
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="99999999999">property>
bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="maxActive" value="30"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"> property>
<property name="basePackage" value="com.neuedu.dao"/>
bean>
beans>
1.6.4. 使用mybatis工具生成Mapper接口
1.6.4.1. 要求mapper.java和Mapper.xml在同一个包下
同一个包下的xml默认不编译需要添加maven配置使maven编译时复制xml到target
1.6.5. 使用mybatis工具生成Mapper接口 1.6.6. 修改了下UserController和UserService的代码(依赖关系) 1.6.6.1. UserControllerpackage com.neuedu.controller;
import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:39 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的控制器
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/list")
public List list(){
List list = userService.queryAll();
return list;
}
}
1.6.6.2. UserService
package com.neuedu.service;
import com.neuedu.dao.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:42 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的逻辑层
*/
@Service
public class UserService {
// @Autowired
// TestMapper testMapper;
@Autowired
TUserMapper tUserMapper;
public List queryAll(){
// int count = testMapper.selectUserCount();
// System.out.println("count :"+count );
return tUserMapper.selectByExample(null);
}
}
将原来的自己写的TestMapper删掉了,单元测试的TestMapperTest类注释掉了
1.6.6.3. 测试http://127.0.0.1:8080/ssm/user/list
1.7. 管理事务
<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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.neuedu"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="99999999999">property>
bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="maxActive" value="30"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
<property name="basePackage" value="com.neuedu.dao"/>
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdivce" transaction-manager="txManager">
<tx:attributes>
<tx:method name="select*" propagation="SUPPORTS"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="*insert" propagation="REQUIRED"/>
<tx:method name="*update" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="servceMethod" expression="execution(* com.neuedu.service.*.*(..))"/>
<aop:advisor advice-ref="txAdivce" pointcut-ref="servceMethod">aop:advisor>
aop:config>
beans>
在service、Controller的基础上追加save方法
package com.neuedu.controller;
import com.neuedu.entity.TUser;
import com.neuedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:39 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的控制器
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/list")
public List list(){
List list = userService.queryAll();
return list;
}
/**
* http://127.0.0.1:8080/ssm/user/save?userId=50&userName=abcdef&gender=男&status=0
* @param user
* @return
*/
@ResponseBody
@RequestMapping("/save")
public Map save(TUser user) throws Exception {
boolean success = userService.save(user);
Map result = new HashMap();
result.put("success",success);
return result;
}
}
package com.neuedu.service;
import com.neuedu.dao.TUserMapper;
import com.neuedu.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 8:42 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 用户的逻辑层
*/
@Service
public class UserService {
// @Autowired
// TestMapper testMapper;
@Autowired
TUserMapper tUserMapper;
public List queryAll(){
// int count = testMapper.selectUserCount();
// System.out.println("count :"+count );
return tUserMapper.selectByExample(null);
}
/**
* 在service层添加save方法
* @param user
* @return
*/
public boolean save(TUser user) throws Exception {
int count = tUserMapper.insertSelective(user);
if(!"男".equals(user.getGender()) || !"女".equals(user.getGender())){
throw new Exception("性别不正确");
}
return count>0;
}
}
正常的请求
http://127.0.0.1:8080/ssm/user/save?userId=50&userName=abcdef&gender=%E7%94%B7&status=0
有可能产生异常的
http://127.0.0.1:8080/ssm/user/save?userId=50&userName=abcdef&gender=xx&status=0
1.8. 测试的逻辑 2. SSM单表增删改查以t_product为例
2.1. 查询列表 2.1.1. TProductMapper通过工具生成 √ 2.1.2. ProductService查询功能(依赖dao)依赖dao(TProductMapper)
package com.neuedu.service;
import com.neuedu.dao.TProductMapper;
import com.neuedu.entity.TProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 13:44 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 :
*/
@Service
public class ProductService {
@Autowired
TProductMapper productMapper;
public List<TProduct> queryPage(){
return productMapper.selectByExample(null);
}
}
2.1.3. ProductController控制器方法查询集合
让控制器依赖ProductService
分页展示列表
package com.neuedu.controller;
import com.neuedu.entity.TProduct;
import com.neuedu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* 项目 : spring-mvc-java1
* 创建时间 :2020/4/3 13:45 03
* author :jshand-root
* site : http://314649444.iteye.com
* 描述 : 产品的控制器
*/
@Controller
@RequestMapping("/product")
public class ProductControlller {
@Autowired
ProductService productService;
/**
* 分页查询
* http://127.0.0.1:8080/ssm/product/list
* @param model
* @return
*/
@RequestMapping("/list")
public String listPage(Model model){
List<TProduct> list = productService.queryPage();
//将查询集合放到作用域中,并展示到jsp的列表
model.addAttribute("productList",list);
return "/product/product_list.jsp";
}
}
2.1.4. 展示列表的页面
/product/product_list.jsp
<%--
Created by IntelliJ IDEA.
User: root
Date: 2020/4/3
Time: 13:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<script>
function ajaxDelete(pid){
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else {
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","${pageContext.request.contextPath}/product/ajaxDeleteById?id="+pid,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var data = eval('('+xmlhttp.responseText+')');
if(data.success){//刷新
window.location.href = window.location.href;
}else{
alert('出错了'+data.msg)
}
}
}
}
</script>
</head>
<body>
后台管理>产品列表
<table cellspacing="0" cellpadding="0" border="1" width="100%">
<tr>
<td>序号</td>
<td>数据id</td>
<td>产品名称</td>
<td>价格</td>
<td> *** 作</td>
</tr>
<c:forEach items="${productList}" var="product" varStatus="stat">
<tr>
<td>${stat.count}</td>
<td>${product.pid}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>
<a href="${pageContext.request.contextPath}/product/toEdit?id=${product.pid}" >修改</a>
<a href="${pageContext.request.contextPath}/product/deleteById?id=${product.pid}" >删除</a>
<a href="javascript:void(0)" onclick="ajaxDelete('${product.pid}')" >ajax删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.2. 添加
2.2.1. 添加页面
%--
Created by IntelliJ IDEA.
User: root
Date: 2020/4/3
Time: 14:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>产品添加title>
head>
<body>
<form action="${pageContext.request.contextPath}/product/save" method="post">
<table cellpadding="0" cellspacing="0" border="1" width="100%">
<tr>
<td>产品idtd>
<td><input type="text" name="pid">td>
tr>
<tr>
<td>名称td>
<td><input type="text" name="name">td>
tr>
<tr>
<td>单价td>
<td><input type="text" name="price">td>
tr>
<tr>
<td colspan="2"><input type="submit" value="添加产品"/> td>
tr>
table>
form>
body>
html>
2.2.2. Service的添加方法
/**
* 保存
* @param product
* @return
*/
public boolean save(TProduct product){
int count = productMapper.insertSelective(product);
return count>0;
}
2.2.3. 控制器:
1)跳转到添加页
2)保存产品的方法
@RequestMapping("/toAdd")
public String toAdd(Model model){
return "/product/product_add.jsp";
}
/**
* 保存新增的产品信息
* @param product
* @return
*/
@RequestMapping("/save")
public String save(TProduct product){
boolean success = productService.save(product);
if(success){
//跳转到查询列表
return "redirect:/product/list";
}else{
//跳转回添加页 展示错误信息
return "product/product_add.jsp";
}
}
2.2.4. 解决中文乱码
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
2.3. 修改
修改的入口,在列表页中添加一列“修改”按钮,当点击修改按钮跳转到product_edit.jsp,jsp提供展示表单的作用(待修改的 数据展示)。点击页面的保存按钮提交修改的信息到数据库中,并刷新列表。
2.3.1. product_list.jsp<%--
Created by IntelliJ IDEA.
User: root
Date: 2020/4/3
Time: 13:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Title
后台管理>产品列表
序号
数据id
产品名称
价格
*** 作
${stat.count}
${product.pid}
${product.name}
${product.price}
修改
删除
ajax删除
2.3.2. product_edit.jsp
<%--
Created by IntelliJ IDEA.
User: root
Date: 2020/4/3
Time: 14:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
产品添加
2.3.3. Service的根据主键查询
/**
* 根据主键查询出待修改的产品
* @param pid
* @return
*/
public TProduct selectById(String pid){
return productMapper.selectByPrimaryKey(pid);
}
2.3.4. Service的修改方法
/**
* 根据主键更新
* @param product
* @return
*/
public boolean update(TProduct product){
int count = productMapper.updateByPrimaryKeySelective(product);
return count>0;
}
2.3.5. Controller的方法
@RequestMapping("/toEdit")
public String toEdit(Model model,String id){
TProduct product = productService.selectById(id);
model.addAttribute("product",product);
return "/product/product_edit.jsp";
}
@RequestMapping("/edit")
public String edit(TProduct product){
boolean success = productService.update(product);
if(success){
//跳转到查询列表
return "redirect:/product/list";
}else{
//跳转回添加页 展示错误信息
return "product/product_edit.jsp";
}
}
2.4. 删除
2.4.1. 在列表页中添加删除按钮,(普通的get删除、ajax删除两种情况都有)
2.4.2. 详见修改时的[列表页面]
2.4.3. 后端的Controller的删除方法
@RequestMapping("/deleteById")
public String deleteById(String id){
boolean success = productService.deleteBydId(id);
//需要携带异常消息
return "redirect:/product/list";
}
@ResponseBody
@RequestMapping("/ajaxDeleteById")
public Map ajaxDeleteById(String id){
boolean success = productService.deleteBydId(id);
//需要携带异常消息
Map result = new HashMap();
result.put("success",success);
return result;
}
2.4.4. Service的删除方法
public boolean deleteBydId(String id) {
return productMapper.deleteByPrimaryKey(id)>0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)