创建工程
SSM整合
Spring
SpringConfig
MyBatis
MybatisConfig
JdbcConfig
jdbc.properties
SpringMVC
ServletConfig
SpringMvcConfig
3.功能模块
表和实体类
Dao(接口+自动代理)
service(接口+测试类)
业务层接口(整合Junit)
Controller
表现层接口测试(PostMan)
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.16version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.1version>
<configuration>
<port>80port>
<path>/path>
configuration>
plugin>
plugins>
build>
@Configuration
@Import({JdbcConfig.class,MybatisConfig.class})
@ComponentScan("com.ysj.service")
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setTypeAliasesPackage("com.ysj.Domain");
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.ysj.Dao");
return mapperScannerConfigurer;
}
}
public class JdbcConfig {
// jdbc.driver=com.mysql.jdbc.Driver
// jdbc.url=jdbc:mysql://localhost:3308/mybatis
// jdbc.username=root
// jdbc.password=yangshijie
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
控制表现层(这个配置类如果导入SpringConfig中,SpringMVC控制的bean也会被Spring控制)
@Configuration
@ComponentScan("com.ysj.Controller")
@EnableWebMvc
public class SpringMvcConfig {
}
web配置类
//web配置类
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[]{"/"};
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class) //上下文配置类
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById(){
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List<Book> all = bookService.getAll();
System.out.println(all);
}
}
在Spring配置类中注册事务管理驱动
@EnableTransactionManagement
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource); //别用方法调用,否则就变成了java语言管理,而不是Speing容器管理了
return ds;
}
直接在service接口类上加@Transactional
后续有更多需求再加(事务传播行为等)
@Transactional
public class Result {
//描述统一格式中的数据
private Object data;
//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
private Integer code;
//描述统一格式中的消息,可选属性
private String msg;
public Result() {
}
public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}
public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
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 getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
编写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 SYSTEM_UNKNOW_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
//@ExceptionHandler用于设置当前处理器类对应的异常类型
@ExceptionHandler(SystemException.class)
public Result TestExcepition(TestExcepition ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}
//继承RuntimeException类
public class TestExcepition extends RuntimeException {
private Integer code; //区别自定义异常类的编码
public TestExcepition(Integer code) {
this.code = code;
}
public TestExcepition(String message, Integer code) {
super(message);
this.code = code;
}
public TestExcepition(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public void setCode(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
以下信息来源于html中文网
//继承HandlerInterceptor接口
//注意当前类必须受Spring容器控制
@Component
public class TestProjectInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//中间可以加上所需业务逻辑
return false;//这个返回值决定了后续的原生方法等是否会执行
}
//原始方法调用后执行的内容
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
//原始方法调用完成后执行的内容
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
将其加入SpringMvc控制中
方法:
新建一个类,继承WebMvcConfigurationSupport
类
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private TestProjectInterceptor testProjectInterceptor;
// * 匹配单个字符,如 /user/* 匹配的是 /user/aa,/user/bb 等,又如 /user/*/ab 匹配到 /user/p/ab;
// ** 匹配任意多字符(包括多级路径),如:/user/** 匹配到 /user/aa、/user/p/bb 等;
//配置相应的静态资源放行
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("pages/**").addResourceLocations("pages/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(testProjectInterceptor).addPathPatterns("books/","books/*");
}
}
直接在SpringMvc配置类中进行
WebMvcConfigurer
接口@Configuration
@ComponentScan({"com.ysj.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
}
}
request:请求对象
response:响应对象
handler:一个被调用的处理器对象,其本质上是一个方法对象(HandlerMethod),对反射技术中的
Method进行的再包装。
ModelAndView:若处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整
Exception:获取程序运行过程中的异常对象(可通过SpringMvc自定义的异常处理器完美代替)
创建所需的多个拦截器类
配置多拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
}
}
多拦截器执行顺序
的异常处理器完美代替)
创建所需的多个拦截器类
配置多拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
}
}
多拦截器执行顺序
** 好了。SSM整合包含的知识点和步骤到这里已经总结完了,如有不足请指正,欢迎各位来一起交流讨论。
最后,创作不易,给个三连支持下呗。**