SSM(Spring+SpringMVC+Mybatis)整合
SSM(Spring+SpringMVC+Mybatis)整合
目录结构
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><parent><groupId>com.itheima</groupId><artifactId>spring</artifactId><version>1.0-SNAPSHOT</version></parent><packaging>war</packaging><artifactId>springmvc_ssm</artifactId><name>springmvc_ssm Maven Webapp</name><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.10.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</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>5.1.47</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><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>
2. config
包下的Spring配置
2.1 springConfig
@Configuration // 配置类
@ComponentScan({"com.itheima.service"}) // 加载该配置类控制哪些bean
@PropertySource("classpath:jdbc.properties") // 配置文件加载属性
@Import({JdbcConfig.class, MybatisConfig.class}) // 导入配置类
@EnableTransactionManagement // 开启注解式事务驱动
public class SpringConfig {}
事务处理步骤:
- 开启注解式事务驱动
- 配置事务管理器 (
JdbcConfig
中添加) - 添加事务 (
@Transactional
添加到接口上)
2.2 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=123456
2.3 jdbcConfig
public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource() {// Druid 数据源DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driver);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}// 事务管理器对象@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource) {DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}
}
2.4 MybatisConfig
public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);factoryBean.setTypeAliasesPackage("com.itheima.domain"); // 类型别名扫描包return factoryBean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {// 扫描映射MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.dao");return msc;}
}
2.5 spring整合SpringMVC配置( ServletConfig
和 SpringMvcConfig
)
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {// 加载 Spring 的核心配置return new Class[]{SpringConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses() {// 加载 SpringMVCreturn new Class[]{SpringMvcConfig.class};}@Overrideprotected String[] getServletMappings() {// 拦截所有请求return new String[]{"/"};}
}
getRootConfigClasses
根配置,getServletConfigClasses
专门应对 Web
请求处理的。两个造出来的容器不一样 ,称为父子容器 (Spring
的容器为父容器,SpringMVC
的容器为子容器),SpringMVC
的容器可以访问 Spring
的容器,但是 Spring
的容器不能访问 SpringMVC
的容器。
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {}
3. 数据库表
create table tbl_book (id int AUTO_INCREMENT PRIMARY KEY,type varchar(20) NOT NULL,name varchar(50) NOT NULL,description varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4. 模块
4.1 domain
public class Book {private Integer id;private String type;private String name;private String description;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Book{" +"id=" + id +", type='" + type + '\'' +", name='" + name + '\'' +", description='" + description + '\'' +'}';}
}
4.2 Dao 接口
public interface BookDao {@Insert("insert into tbl_book (type, name, description) values (#{type}, #{name}, #{description})")public void save(Book book);@Update("update tbl_booke set type = #{type}, name = #{name}, description=#{description} where id = #{id}")public void update(Book book);@Delete("delete from tbl_book where id = #{id}")public void delete(Integer id);@Select("select * from tbl_book where id = #{id}")public Book getById(Integer id);@Select("select * from tbl_book")public List<Book> getAll();
}
4.3 Service
接口
@Transactional // 声明式事务
public interface BookService {/*** 保存* @param book* @return*/public boolean save(Book book);/*** 修改* @param book* @return*/public boolean update(Book book);/*** 删除* @param id* @return*/public boolean delete(Integer id);/*** 根据id查询* @param id* @return*/public Book getById(Integer id);/*** 查询所有* @return*/public List<Book> getAll();
}
4.4 Service
层的实现类
@Service
public class BookServiceImpl implements BookService {@Autowiredprivate BookDao bookDao;public boolean save(Book book) {bookDao.save(book);return true;}public boolean update(Book book) {bookDao.update(book);return true;}public boolean delete(Integer id) {bookDao.delete(id);return true;}public Book getById(Integer id) {if (id == 1) {throw new BusinessException(Code.BUSINESS_ERR, "请不要使用");}return bookDao.getById(id);}public List<Book> getAll() {return bookDao.getAll();}
}
4.5 Controller
类
@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate BookService bookService;@PostMappingpublic Result save(@RequestBody Book book) {boolean flag = bookService.save(book);return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);}@PutMappingpublic Result update(@RequestBody Book book) {boolean flag = bookService.update(book);return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);}@DeleteMapping("/{id}")public Result delete(@PathVariable Integer id) {boolean flag = bookService.delete(id);return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);}@GetMapping("/{id}")public Result getById(@PathVariable Integer id) {Book book = bookService.getById(id);Integer code = book != null ? Code.GET_OK : Code.GET_ERR;String msg = book != null ? "" : "查询失败";return new Result(code, book, msg);}@GetMappingpublic Result getAll() {List<Book> all = bookService.getAll();Integer code = all != null ? Code.GET_OK : Code.GET_ERR;String msg = all != null ? "" : "查询失败,请重试!";return new Result(code, all, msg);}
}
5. 测试业务层
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class bookServiceTest {@Autowiredprivate BookService bookService;@Testpublic void testGetById() {Book book = bookService.getById(1);System.out.println(book);}@Testpublic void testGetAll() {List<Book> all = bookService.getAll();System.out.println(all);}
}
6.定义 Controller
返回结果
6.1 Result
public class Result {private Object data;private Integer code;private String message;public Result() {}public Result(Integer code, Object data) {this.data = data;this.code = code;}public Result(Integer code, Object data, String message) {this.data = data;this.code = code;this.message = message;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}
6.2 Code 状态码
public class Code {public static final Integer SAVE_OK = 20011;public static final Integer DELETE_OK = 20021;public static final Integer UPDATE_OK = 20031;public static final Integer GET_OK = 20041;public static final Integer SAVE_ERR = 20010;public static final Integer DELETE_ERR = 20020;public static final Integer UPDATE_ERR = 20030;public static final Integer GET_ERR = 20040;public static final Integer SYSTEM_ERR = 50001;public static final Integer SYSTEM_TIMEOUT_ERR = 50002;public static final Integer BUSINESS_ERR = 60002;public static final Integer SYSTEM_UNKNOW_ERR = 59999;
}
7. 异常处理器
7.1 @RestControllerAdvice
@RestControllerAdvice
public class ProjectExceptionAdvice {@ExceptionHandler(SystemException.class)public Result doSystemException(SystemException ex) {// 记录日志// 发送消息给运维// 发送邮件给开发人员return new Result(ex.getCode(), null, ex.getMessage());}@ExceptionHandler(BusinessException.class)public Result doBusinessException(BusinessException ex) {System.out.println("嘿嘿");return new Result(ex.getCode(), null, ex.getMessage());}@ExceptionHandler(Exception.class)public Result doException(Exception ex) {// 记录日志// 发送消息给运维// 发送邮件给开发人员return new Result(Code.SYSTEM_UNKNOW_ERR, null, "系统繁忙,稍后再试!");}}
7.2 自定义系统类异常
public class SystemException extends RuntimeException{private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public SystemException(Integer code, String message) {super(message);this.code = code;}public SystemException(Integer code, String message, Throwable cause) {super(message, cause);this.code = code;}
}
7.3 自定义业务类异常
public class BusinessException extends RuntimeException{private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public BusinessException(Integer code, String message) {super(message);this.code = code;}public BusinessException(Integer code, String message, Throwable cause) {super(message, cause);this.code = code;}
}
8. SpringMvcSupport
过滤访问静态资源
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {@Autowiredprivate ProjectInterceptor projectInterceptor;@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/page/**").addResourceLocations("page/");registry.addResourceHandler("/css/**").addResourceLocations("css/");registry.addResourceHandler("/js/**").addResourceLocations("js/");registry.addResourceHandler("/plugins/**").addResourceLocations("plugins/");}@Overrideprotected void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(projectInterceptor).addPathPatterns("/books");}
}
9. 拦截器(Interceptor)
@Component
public class ProjectInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("preHandle");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("afterCompletion");}
}