SpringBoot MVC 拦截器

SpringBoot MVC

环境搭建

  1. 在pom.xml添加spring-boot-starter-web

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  2. 修改application.yml配置

    
    spring:
     datasource:
      username: system
      password: 123456
      url: jdbc:oracle:thin:@localhost:1521:XE
      driverClassName: oracle.jdbc.OracleDriver
    server:
     port: 8889
    
  3. 编写Controller,使用@RequestMapping和@RestController

    @RestController
    public class BookService {
    
        @Autowired
        private BookDao bookDao;
    
        @RequestMapping(value="/book",method=RequestMethod.GET)
        public List<Book> loadAll(){
            return bookDao.findAll();
        }
    
        @RequestMapping(value="/book/{id}",method=RequestMethod.GET)
        public Book load(@PathVariable("id")int id){
            return bookDao.findById(id);
        }
    
        @RequestMapping(value="/book/{id}",method=RequestMethod.DELETE)
        public boolean delete(@PathVariable("id")int id){
            int row = bookDao.deleteById(id);
            if(row >= 1){
                return true;
            }else{
                return false;
            }
        }
    
        @RequestMapping(value="/book/{id}",method=RequestMethod.PUT)
        public boolean update(@PathVariable("id")int id, @RequestBody Book book){
            book.setId(id);
            int row = bookDao.update(book);
            if(row >= 1){
                return true;
            }else{
                return false;
            }
        }
    
        @RequestMapping(value="/book",method=RequestMethod.POST)
        public boolean add(@RequestBody Book book){
            bookDao.save(book);
            return true;
        }
    }
    
  4. 编写Filter,解决Ajax调用跨域问题

    @WebFilter(servletNames={"dispatcherServlet"})
    public class AjaxDomainFilter implements Filter{
    
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse httpResponse = (HttpServletResponse)response;
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");//设置允许哪些域名应用进行ajax访问
            httpResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
            httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type");
            chain.doFilter(request, response);//调用后续serlvet
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
    
        }
    
    }
    
  5. 配置Filter,使用@WebFilter和@ServletComponentScan

    @SpringBootApplication//开启扫描、自动配置、bean定义
    @MapperScan(basePackages={"cn.xdl.dao"})//开启扫描Mapper接口
    @ServletComponentScan//开启WebFilter、WebServlet、WebListener配置支持
    public class BootApplication {
    
        public static void main(String[] args){
            SpringApplication.run(BootApplication.class, args);
        }
    
    }
    
  6. 修改pc_web前端的common.js,将请求路径改为

    var path = "http://localhost:8889";
    

SpringBoot 热启动

当修改完毕程序代码后,可以自动重新部署。

 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
</dependency>

如果修改了pom.xml定义,要从新启动,修改了java代码可以自动重新启动。

SpringBoot MyBatis分页

<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper-spring-boot-starter</artifactId>
  <version>1.2.3</version>
</dependency>

然后在调用查询代码之前执行PageHelper.startPage方法

Page page = PageHelper.startPage(p, 3);
//分页查询
List list = bookDao.findAll();
//获取总页数
int totalPage = page.getPages();

SpringBoot 拦截器

  1. 编写拦截器类,实现HandlerInterceptor接口,实现PreHandle、PostHandle、afterCompletion方法

    public class AjaxDomainInterceptor implements HandlerInterceptor{
    
        @Override
        public boolean preHandle(
            HttpServletRequest request, 
            HttpServletResponse response, Object handler)
                throws Exception {
            response.setHeader("Access-Control-Allow-Origin", "*");//设置允许哪些域名应用进行ajax访问
            response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type");
            return true;
        }
    
        //...
    }
    
  2. 编写配置类,继承WebMvcConfigurerAdapter,重写addInterceptors方法

    //@Configuration
    @Component
    public class InterceptorConfiguration extends WebMvcConfigurerAdapter{
    
        public void addInterceptors(InterceptorRegistry registry) {
            //配置拦截器
            AjaxDomainInterceptor ajaxDomain = new AjaxDomainInterceptor();
            registry.addInterceptor(ajaxDomain).addPathPatterns("/**");
        }
    
    }
展开阅读全文

没有更多推荐了,返回首页