SpringBoot Initial - Interceptor

Posted by steadyguy on Tue, 13 Aug 2019 10:48:28 +0200

Interceptor can help us to complete some unified checks of user status, request parameters, log records, etc. In SpringBook, we can inherit Handler Interceptor to implement our interceptor, and then simply configure it to make the interceptor effective.

One additional interceptor

We add a login interceptor to simulate the unified processing of whether to login or not.

package com.qinshou.springbootdemo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:Logon interceptor
 * Author: QinHao
 * Date: 2019/8/13 14:45
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Determine whether to log in by using token in the request parameter
        if (request.getParameter("token") == null||request.getParameter("token") .equals("")) {
            System.out.println("token is null");
            return false;
        }
        return true;
    }
}

Then modify the previous Compputer Controller for later demonstrations:

package com.qinshou.springbootdemo.controller;

import com.qinshou.springbootdemo.bean.ComputerBean;
import com.qinshou.springbootdemo.service.IComputerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Description:Controller of Computer Module
 * Author: QinHao
 * Date: 2019/8/1 13:40
 */
@RestController
@RequestMapping(value = "/computer")
public class ComputerController {
    @Autowired
    private IComputerService mComputerService;

    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public List<ComputerBean> selectAll() {
        return mComputerService.selectAll();
    }

    @RequestMapping(value = "/selectAllByBrand", method = RequestMethod.GET)
    public List<ComputerBean> selectLAllByBrand(@RequestParam(name = "brand") String brand) {
        return mComputerService.selectAllByBrand(brand);
    }

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public ComputerBean select(@RequestParam(name = "id") int id) {
        return mComputerService.select(id);
    }
}

 

Two-configuration interceptor

Write the interceptor and it will not automatically take effect. We need to configure it and add some personalized configurations when configuring it.

package com.qinshou.springbootdemo.config;

import com.qinshou.springbootdemo.interceptor.LoginInterceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Description:Interceptor configuration class
 * Author: QinHao
 * Date: 2019/8/13 14:59
 */

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                // url designated for interception
                .addPathPatterns("/computer/**")
                // Specify URLs that are not intercepted
                .excludePathPatterns("/computer/select");
    }
}

Note that this configuration class is different from the previous DruidConfig and FastJson Configuration. In addition to the @Configuration annotation, it inherits the WebMvcConfigurer class and rewrites its addInterceptors method. From the method name, we can see that it is used to add interceptors. We add rigidity to this method. Just login Interceptor, and specify some filtering rules.

 

Four tests

According to the above rules, we will filter all requests at / computer / start, except URLs at / computer/select, which will be intercepted without token parameters. Test selectAll:

You can see that nothing is returned on the page, and the background prints out the error, and then tests select AllByBrand:

The same result is then tested. selectAllByBrand with token parameters and select without token parameters:

The content is returned on the page and SQL is executed in the background printing, which shows that our personalized configuration is effective and the interceptor has completed its mission perfectly. Interceptors are very useful in development, which can help us to complete a lot of work that needs to be handled in a unified way.

Topics: Java SQL