0


SSM整合(超详细)

SSM整合

步骤

  1. 创建工程
  2. SSM整合- Spring- SpringConfig- MyBatis- MybatisConfig- JdbcConfig- jdbc.properties- SpringMVC- ServletConfig- SpringMvcConfig``````3.功能模块- 表和实体类- Dao(接口+自动代理)- service(接口+测试类)- 业务层接口(整合Junit)- Controller- 表现层接口测试(PostMan)

一:导入相关依赖

<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>

二:创建相应包和类

在这里插入图片描述

三:编写相应配置类

3.1:Spring配置类

@Configuration@Import({JdbcConfig.class,MybatisConfig.class})@ComponentScan("com.ysj.service")@PropertySource("classpath:jdbc.properties")publicclassSpringConfig{}

3.2:MyBatis配置类

3.2.1:Mybatis

publicclassMybatisConfig{@BeanpublicSqlSessionFactoryBeansqlSessionFactoryBean(DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean =newSqlSessionFactoryBean();
       sqlSessionFactoryBean.setTypeAliasesPackage("com.ysj.Domain");
        sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean;}@BeanpublicMapperScannerConfigurermapperScannerConfigurer(){MapperScannerConfigurer mapperScannerConfigurer =newMapperScannerConfigurer();

        mapperScannerConfigurer.setBasePackage("com.ysj.Dao");return mapperScannerConfigurer;}}

3.2.2:Jdbc配置类

publicclassJdbcConfig{//    jdbc.driver=com.mysql.jdbc.Driver//    jdbc.url=jdbc:mysql://localhost:3308/mybatis//    jdbc.username=root//    jdbc.password=yangshijie@Value("${jdbc.driver}")privateString driver;@Value("${jdbc.url}")privateString url;@Value("${jdbc.username}")privateString username;@Value("${jdbc.password}")privateString password;@BeanpublicDataSourcedataSource(){DruidDataSource dataSource =newDruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);return dataSource;}}

3.2.3:Jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

4:SpringMVC配置类

  • 控制表现层(这个配置类如果导入SpringConfig中,SpringMVC控制的bean也会被Spring控制)@Configuration@ComponentScan("com.ysj.Controller")@EnableWebMvcpublicclassSpringMvcConfig{}
  • web配置类//web配置类publicclassServletConfigextendsAbstractAnnotationConfigDispatcherServletInitializer{protectedClass<?>[]getRootConfigClasses(){returnnewClass[]{SpringConfig.class};}protectedClass<?>[]getServletConfigClasses(){returnnewClass[]{SpringMvcConfig.class};}protectedString[]getServletMappings(){returnnewString[]{"/"};}}

5:Junit测试

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes =SpringConfig.class)//上下文配置类publicclassBookServiceTest{@AutowiredprivateBookService bookService;@TestpublicvoidtestGetById(){Book book = bookService.getById(1);System.out.println(book);}@TestpublicvoidtestGetAll(){List<Book> all = bookService.getAll();System.out.println(all);}}

6:事务管理器

6.1:注册驱动

  • ​ 在Spring配置类中注册事务管理驱动@EnableTransactionManagement

6.2:配置平台事务管理容器

  • 可在Jdbc配置类中直接配置
@BeanpublicPlatformTransactionManagertransactionManager(DataSource dataSource){DataSourceTransactionManager ds =newDataSourceTransactionManager();
    ds.setDataSource(dataSource);//别用方法调用,否则就变成了java语言管理,而不是Speing容器管理了return ds;}

6.3:加事务

  • 直接在service接口类上加@Transactional
  • 后续有更多需求再加(事务传播行为等)@Transactional

7:前后端传输协议

7.1:后端返回值

  • 新建一个Result类充当返回值类

  • 需要跟多属性和构造器可以再自行添加

publicclassResult{//描述统一格式中的数据privateObject data;//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败privateInteger code;//描述统一格式中的消息,可选属性privateString msg;publicResult(){}publicResult(Integer code,Object data){this.data = data;this.code = code;}publicResult(Integer code,Object data,String msg){this.data = data;this.code = code;this.msg = msg;}publicObjectgetData(){return data;}publicvoidsetData(Object data){this.data = data;}publicIntegergetCode(){return code;}publicvoidsetCode(Integer code){this.code = code;}publicStringgetMsg(){return msg;}publicvoidsetMsg(String msg){this.msg = msg;}}
  • 编写Code编码类(状态码)publicclassCode{publicstaticfinalInteger SAVE_OK =20011;publicstaticfinalInteger DELETE_OK =20021;publicstaticfinalInteger UPDATE_OK =20031;publicstaticfinalInteger GET_OK =20041;publicstaticfinalInteger SAVE_ERR =20010;publicstaticfinalInteger DELETE_ERR =20020;publicstaticfinalInteger UPDATE_ERR =20030;publicstaticfinalInteger GET_ERR =20040;publicstaticfinalInteger SYSTEM_ERR =50001;publicstaticfinalInteger SYSTEM_TIMEOUT_ERR =50002;publicstaticfinalInteger SYSTEM_UNKNOW_ERR =59999;publicstaticfinalInteger BUSINESS_ERR =60002;}

8:自定义异常处理器

  • 新建一个excepition包
  • 包下创建所需各个异常类

8.1:总的异常处理器

//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器@RestControllerAdvicepublicclassProjectExceptionAdvice{//@ExceptionHandler用于设置当前处理器类对应的异常类型@ExceptionHandler(SystemException.class)publicResultTestExcepition(TestExcepition ex){//记录日志//发送消息给运维//发送邮件给开发人员,ex对象发送给开发人员returnnewResult(ex.getCode(),null,ex.getMessage());}//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常@ExceptionHandler(Exception.class)publicResultdoOtherException(Exception ex){//记录日志//发送消息给运维//发送邮件给开发人员,ex对象发送给开发人员returnnewResult(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");}}

8.2:自定义分类的异常处理器类

  • 记得继承相应的异常父类, - 原因:程序运行时遇到相应异常后可以不处理向上抛- 不继承坏处:以后每个方法都要加上这个类
//继承RuntimeException类publicclassTestExcepitionextendsRuntimeException{privateInteger code;//区别自定义异常类的编码publicTestExcepition(Integer code){this.code = code;}publicTestExcepition(String message,Integer code){super(message);this.code = code;}publicTestExcepition(String message,Throwable cause,Integer code){super(message, cause);this.code = code;}publicvoidsetCode(Integer code){this.code = code;}publicIntegergetCode(){return code;}}

9:拦截器

9.1:拦截器概念

  • 拦截器是是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行(执行的时候类似栈思想)
  • 作用 - 在指定的方法执行前后调用我们预先设定的代码- 阻止原始方法的执行(权限)

在这里插入图片描述

9.2:拦截器和过滤器的区别

9.2.1 精简版

  • 过滤器是Servlet技术,其可以对几乎所有的请求进行增强
  • 拦截器是SpringMVC技术,仅仅对SpringMVC技术进行增强

9.2.2 详细版

以下信息来源于html中文网

在这里插入图片描述

9.3:拦截器入门

  • 拦截器在表现层生效,所以建议在controller包下新建Interceptor包在这里插入图片描述
  • 在该包下新建所需拦截器类(类继承HandlerInterceptor接口)
//继承HandlerInterceptor接口//注意当前类必须受Spring容器控制@ComponentpublicclassTestProjectInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throwsException{//中间可以加上所需业务逻辑returnfalse;//这个返回值决定了后续的原生方法等是否会执行}//原始方法调用后执行的内容@OverridepublicvoidpostHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView)throwsException{}//原始方法调用完成后执行的内容@OverridepublicvoidafterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex)throwsException{}}
  • 将其加入SpringMvc控制中
  • 方法:- 新建一个类,继承WebMvcConfigurationSupport@ConfigurationpublicclassSpringMvcSupportextendsWebMvcConfigurationSupport{@AutowiredprivateTestProjectInterceptor testProjectInterceptor;// * 匹配单个字符,如 /user/* 匹配的是 /user/aa,/user/bb 等,又如 /user/*/ab 匹配到 /user/p/ab;// ** 匹配任意多字符(包括多级路径),如:/user/** 匹配到 /user/aa、/user/p/bb 等;//配置相应的静态资源放行@OverrideprotectedvoidaddResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("pages/**").addResourceLocations("pages/");}@OverrideprotectedvoidaddInterceptors(InterceptorRegistry registry){ registry.addInterceptor(testProjectInterceptor).addPathPatterns("books/","books/*");}}- 直接在SpringMvc配置类中进行- 让SpringMvc配置类继承WebMvcConfigurer接口@Configuration@ComponentScan({"com.ysj.controller"})@EnableWebMvc//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性publicclassSpringMvcConfigimplementsWebMvcConfigurer{@AutowiredprivateProjectInterceptor projectInterceptor;@AutowiredprivateProjectInterceptor2 projectInterceptor2;@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){//配置多拦截器 registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*"); registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");}}

9.4🎃拦截器参数

  • request:请求对象
  • response:响应对象
  • handler:一个被调用的处理器对象,其本质上是一个方法对象(HandlerMethod),对反射技术中的​ Method进行的再包装。
  • ModelAndView:若处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整
  • Exception:获取程序运行过程中的异常对象(可通过SpringMvc自定义的异常处理器完美代替)

9.5🛋拦截器链

  • 创建所需的多个拦截器类在这里插入图片描述
  • 配置多拦截器@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){//配置多拦截器 registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*"); registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");}}
  • 多拦截器执行顺序- 按添加顺序运行- 若其中一个拦截器触发拦截条件,返回值为false,则直接跳到afterCompletion方法处,然后(出栈思想)在这里插入图片描述

** 好了。SSM整合包含的知识点和步骤到这里已经总结完了,如有不足请指正,欢迎各位来一起交流讨论。
最后,创作不易,给个三连支持下呗。**

标签: java mybatis spring

本文转载自: https://blog.csdn.net/qq_54217349/article/details/127164644
版权归原作者 踏风彡 所有, 如有侵权,请联系我们删除。

“SSM整合(超详细)”的评论:

还没有评论