一:拦截器
1.拦截器介绍
- 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
- 作用:
- 在指定的方法调用前后执行预先设定的代码
- 阻止原始方法的执行
- 总结:增强
- 核心原理:AOP思想
工作流程:
二:快速入门
1.编写拦截器类:
package com.lcyy.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProjectInterceptor implements HandlerInterceptor { //原始方法调用前执行的内容 //返回值类型可以拦截控制的执行,true放行,false终止 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("前置拦截"); return true; } //原始方法调用后执行的内容 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("后置拦截"); } //原始方法调用完成后执行的内容 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("最终拦截"); } }
2.配置加载拦截器
第一种方法是继承WebMvcConfigurationSupport
@Configuration public class SpringMvcConfig extends WebMvcConfigurationSupport { @Autowired private ProjectInterceptor projectInterceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { //配置拦截器 registry.addInterceptor(projectInterceptor) .addPathPatterns("/books","/books/*"); } }
第二种方法为实现WebMvcConfigurer
@Configuration @ComponentScan({"com.lcyy.controller"}) @EnableWebMvc//开启json //实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性 public class SpringMvcConfig implements WebMvcConfigurer { @Autowired private ProjectInterceptor projectInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //配置多拦截器 registry.addInterceptor(projectInterceptor) .addPathPatterns("/books","/books/*"); } }
测试结果:
3.SpringMVC工作流程
三:拦截器与过滤器的区别
- 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
- 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强
二:整合SSM
一:导入相关的依赖:
1.导入springmvc依赖
<!-- springmvc依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.31</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.3</version> </dependency>
2.导入数据源依赖
<!-- 数据源依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.18</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency>
3. 导入mybatis依赖
<!-- mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.31</version> </dependency>
4.导入JSON依赖
<!-- 开启JSON--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency>
5.导入单元测试依赖
<!-- 添加单元测试工具JUnit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.31</version> </dependency>
6.编写jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm_db?useSSL=false jdbc.username=root jdbc.password=zhien0516
7.准备数据库
二:编写配置类
1.SpringConfig类
package com.lcyy.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @ComponentScan({"com.lcyy.service"}) @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class, MybatisConfig.class}) @EnableTransactionManagement//开启Spring事务管理 public class SpringConfig { }
2.SpringMVCConfig类
package com.lcyy.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration//表示配置类 @ComponentScan("com.lcyy.controller") @EnableWebMvc//开启JSON public class SpringMVCConfig { }
3.ServletConfig类
package com.lcyy.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter; public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMVCConfig.class}; } //解决中文乱码问题(输入流) @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("utf-8"); return new Filter[]{filter}; } }
4.JdbcConfig类
package com.lcyy.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; 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; @Bean public DataSource dataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } //开启事务,spring提供的事务切面类,里面增强了事务管理功能,里面有事务提交和事务回滚功能 @Bean public PlatformTransactionManager platformTransactionManager(DataSource dataSource){ DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource); return transactionManager; } }
5.MybatisConfig类
package com.lcyy.config; import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.session.Configuration; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MybatisConfig { //创建工厂 @Bean public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource){ SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //封装到的实体类 bean.setTypeAliasesPackage("com.lcyy.pojo"); Configuration configuration = new Configuration(); //设置驼峰命名 configuration.setMapUnderscoreToCamelCase(true); //设置打印日志 configuration.setLogImpl(StdOutImpl.class); bean.setConfiguration(configuration); return bean; } //扫包 @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer configurer = new MapperScannerConfigurer(); configurer.setBasePackage("com.lcyy.dao"); return configurer; } }
三:编写pojo层(实体类)
package com.lcyy.pojo; import org.springframework.stereotype.Component; @Component 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; } @Override public String toString() { return "Book{" + "id=" + id + ", type='" + type + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + '}'; } }
四:编写dao层(持久层)
package com.lcyy.dao; import com.lcyy.pojo.Book; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface BookDao { // //增 // @Insert("insert into tbl_book values (null,#{type},#{name},#{description})") @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})") int save(Book book); //删 @Delete("delete from tbl_book where id=#{id}") int delete(Integer id); //改 @Update("update tbl_book set name=#{name},type=#{type},description=#{description} where id=#{id}") int update(Book book); //查 //根据id查询 @Select("select * from tbl_book where id=#{id}") Book getById(Integer id); //查所有 @Select("select * from tbl_book") List<Book> getAll(); }
五:编写service层(业务层)
1.接口
package com.lcyy.service; import com.lcyy.pojo.Book; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional //表示所有方法进行事务管理 public interface BookService { /** * 保存 * @param book * @return */ public boolean save(Book book); /** * 修改 * @param book * @return */ public boolean update(Book book); /** * 按id删除 * @param id * @return */ public boolean delete(Integer id); /** * 按id查询 * @param id * @return */ public Book getById(Integer id); /** * 查询全部 * @return */ public List<Book> getAll(); }
2.实现类
package com.lcyy.service.impl; import com.lcyy.dao.BookDao; import com.lcyy.pojo.Book; import com.lcyy.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BookServiceImpl implements BookService { @Autowired private 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) { return bookDao.getById(id); } public List<Book> getAll() { return bookDao.getAll(); } }
六:测试类
在test包下建立一个测试类的包
package com.lcyy.BookServiceTest; import com.lcyy.config.SpringMVCConfig; import com.lcyy.pojo.Book; import com.lcyy.service.BookService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringMVCConfig.class) public class BookServiceTset { @Autowired private BookService bookService; @Test public void testGetById(){ Book id = bookService.getById(1); System.out.println("id = " + id); } }
三:总结
SSM是标准的MVC模式,SpringMVC为表示层,Spring为业务层,Mybatis为持久层,同时将系统划分为三层分别是:controller层、service层、dao层
dao层(持久层):主要是做数据持久层的工作,负责与数据库进行联络的一些任务都封装在这。
首先设计dao层的接口;
然后在spring的配置文件中定义此接口的实体类;
然后就可以在模块中调用此接口来进行数据业务的处理,而不用关心此接口的具体实体类是哪个
service层(业务层):Service层主要负责业务模块的逻辑应⽤设计
首先设计接口,在设计实体类
接着在spring的配置文件中配置其实现的关联;
service层的业务实现,具体要调用到以定义的dao层的接口;
封装service层的业务逻辑有利于通用的业务逻辑的独立性和重复利用性,
controller层(表现层):Controller层负责具体的业务模块流程的控制
调用service层的接口来控制业务流程;
控制的配置也同样是在spring的配置文件中进行,针对具体的业务流程,会有不同的控制器,我们具体的设计过程中可以将流程进⾏ 抽象归纳,设计出可以重复利⽤的⼦单元流程模块,这样不仅使程序结构变得清晰,也⼤⼤减少了代码量。