Parameter verification is completed by implementing WebMvcConfigurer in SpringBoot

The WebMvcConfigurerAdapter class is deprecated in Spring5.0 and SpringBoot2.0.

There are two solutions

1 Directly implement WebMvcConfigurer (official recommendation)

2 Directly inherit WebMvcConfigurationSupport

This article discusses the use of the first method to complete parameter verification.

First attach the code.

@ Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    MiaoshaUserService miaoshaUserService;


//    @GetMapping("/to_list")
//    public String toList(Model model, MiaoshaUser miaoshaUser) {
//        model.addAttribute("miaoshaUser",miaoshaUser);
//        return "list";
//    }


    @GetMapping("/to_list")
    public String toList(Model model,
                         HttpServletResponse response,
                         @CookieValue(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN,required = false)String cookieToken,
                         @RequestParam(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN,required = false)String paramToken) {
        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
            return "login";
        }
        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        MiaoshaUser miaoshaUser = miaoshaUserService.getByToken(response,token);
        model.addAttribute("miaoshaUser",miaoshaUser);
        return "list";
    }

}

The function that toList needs to implement is to obtain the token in the cookie or requestParam, obtain detailed user information from redis through the token, and then display the user information on the page. There are many input parameters in the above traditional methods. The last thing you need is to get the MiaohshaUser object. In the actual writing process of the program, there will be many methods to obtain the object through such a process. How to simplify the code? When the object needs to be obtained, what about getting the token from the cookie and getting the specific object from redis after a series of operations?

The following is achieved by implementing the WebMvcConfigurer interface.

/**
 * @author hsw
 * @Date 10:12 2018/5/8
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    UserArgumentResolver userArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(userArgumentResolver);
    }

}

Create a new WebConfig class to implement the WebMvcConfigurer interface. WebMvcConfigurer is an interceptor with many methods. We use the addArgumentResolvers method. It should be noted that the class header needs to be annotated with @Configuration to hand over the class to spring management.

The specific content of addArgumentResolvers will be mentioned later.


Create a new UserArgumentResolver class to implement the HandlerMethodArgumentResolver interface

Implementing the HandlerMethodArgumentResolver interface requires overriding the supportsParameter method and the resolveArgument method.

In resolveArgument, the token value is obtained from the cookie or requestparam, and the specific MiaoshaUser information is queried from redis and returned.

After the UserArgumentResolver class is written, add an instance of the UserArgumentResolver class to the argumentResolvers parameter in the addArgumentResolvers method in the WebConfig class above.


After these two classes are completed, the toList method in the controller class is shown in the first commented code.

/**
 * @author hsw
 * @Date 10:25 2018/5/8
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    MiaoshaUserService userService;

    /*
     * Miaoshauser class for parameter verification
     * @author hsw
     * @date 2018/5/8 10:49
     * @param [methodParameter]
     * @return boolean
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz = methodParameter.getParameterType();//If it is not the MiaoshaUser class, the next operation will not be performed
        return clazz == MiaoshaUser.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request =nativeWebRequest.getNativeRequest(HttpServletRequest.class);//获取HttpServletRequest
        HttpServletResponse response =nativeWebRequest.getNativeResponse(HttpServletResponse.class);//获取HttpServletResponse  

        String paramToken = request.getParameter(MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN);
        String cookieToken = getCookieValue(request,MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN);
        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
            return null;
        }

        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        return userService.getByToken(response,token);//Query detailed information through token and return, the return class is MiaoshaUser
    }

    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            if(cookie.getName().equals(cookieName)){
                return cookie.getValue();
            }
        }
        return null;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326885894&siteId=291194637