Hello, in this chapter we add interceptor functionality. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

In the process of Web development, in order to achieve login permission verification, security verification, etc., we often need to add an interceptor in the user’s request to the Controller layer to achieve login verification, so how to add SpringBoot interceptor?

One: Add interceptors

Open the core – configurer – WebConfigurer

Add the following

/** * TODO to change to its own requirements */ private static final String IZATION ="CHUCHEN"; Public void addInterceptors(InterceptorRegistry registry) {registry. AddInterceptor (); / / note that HandlerInterceptorAdapter here can be modified to create new interceptorHandlerInterceptorAdapter() {
                @Override
                public boolean preHandle(HttpServletRequest request,
                                         HttpServletResponse response, Object handler) throws Exception {
                    String ization = request.getHeader("ization");
                    if(IZATION.equals(ization)){
                        return true;
                    }else{
                        RetResult<Object> result = new RetResult<>();
                        result.setCode(RetCode.UNAUTHORIZED).setMsg("Signature authentication failed");
                        responseResult(response, result);
                        return false; }}} // Add the path to intercept /** for all intercepts."/userInfo/selectAlla");
}private void responseResult(HttpServletResponse response, RetResult<Object> result) {
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-type"."application/json; charset=UTF-8"); response.setStatus(200); try { response.getWriter().write(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue)); } catch (IOException ex) { LOGGER.error(ex.getMessage()); }}Copy the code

Test 2:

Enter localhost: 8080 / the userInfo/selectAll



Enter localhost: 8080 / the userInfo/selectAlla



Add a signature to the header



Three: Create your own interceptors

To create the core – interceptor – Interceptor1

package com.example.demo.core.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 Interceptor1 implements HandlerInterceptor {/** * is called before a request is processed (before a Controller method is called) * @param Request * @param response * @param handler * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>> preHandle"); // Only returntrueBefore it continues down and returnsfalseCancel current requestreturn true; } /** * after the request is processed, But before the view is rendered (after the Controller method is called) * @param Request * @Param Response * @Param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(">>>MyInterceptor1>>>>>>> postHandle"); } /** * is called after the entire request ends, * @param Request * @param Response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(">>>MyInterceptor1>>>>>>> afterCompletion"); }}Copy the code

4. Modify the WebConfigurer configuration

Modify the addInterceptors method as follows

@override public void addInterceptors(InterceptorRegistry registry) {registry. AddInterceptor ( HandlerInterceptorAdapter here can be modified to create new interceptorInterceptor1() {
                @Override
                public boolean preHandle(HttpServletRequest request,
                                         HttpServletResponse response, Object handler) throws Exception {
                    String ization = request.getHeader("ization");
                    if(IZATION.equals(ization)){
                        return true;
                    }else{
                        RetResult<Object> result = new RetResult<>();
                        result.setCode(RetCode.UNAUTHORIZED).setMsg("Signature authentication failed");
                        responseResult(response, result);
                        return false; }}} // Add the path to intercept /** for all intercepts."/userInfo/selectAlla");
}Copy the code

5: test

Enter localhost: 8080 / the userInfo/selectAlla



Add a signature to the header



successful

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

The function of adding interceptor has been completed, and the subsequent functions will be updated successively. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.