通过重写HandlerMethodArgumentResolve

2020-04-20  本文已影响0人  Quillagua

通过重写HandlerMethodArgumentResolver来定义控制层参数的传递规则

1.先看一段代码

这段代码的参数显得很冗余,而且在控制层间传递pojo类每次需要写这么多参数。

package com.example.miaosha_xdp.controller;
 
import com.alibaba.druid.util.StringUtils;
import com.example.miaosha_xdp.VO.UserVo;
import com.example.miaosha_xdp.entity.User;
import com.example.miaosha_xdp.exception.GlobalException;
import com.example.miaosha_xdp.result.CodeMsg;
import com.example.miaosha_xdp.result.Result;
import com.example.miaosha_xdp.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
 
 
@Controller
@RequestMapping("/goods")
public class GoodsController {
    private static Logger logger = LoggerFactory.getLogger(GoodsController.class);
    @Autowired
    UserService userService;
 
    @RequestMapping("/to_list")
    public String to_login(Model model,HttpServletResponse response,@CookieValue(value =UserService.TOKEN,required = false)String cookieToken,
                                        @RequestParam(value = UserService.TOKEN,required = false) String paramToken) {
        if(StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
            return "login";
        }
        String token = StringUtils.isEmpty(cookieToken) ? paramToken : cookieToken;
        User user=userService.getByToken(response,token);
        logger.info(user.toString());
        model.addAttribute("user",user);
        return "goods_list";
    }
 
 
}

2.重新HandlerMethodArgumentResolver

为了解决这个问题,我们来重新springMVC里面的MethodArgumentResolver

package com.example.miaosha_xdp.config;
 
import com.example.miaosha_xdp.entity.User;
import com.example.miaosha_xdp.redis.MiaoshaUserKey;
import com.example.miaosha_xdp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Period;
 
/**
 * HandlerMethodArgumentResolver是SpringMVC中,给控制层方法的参数赋值的
 * 先根据参数类型寻找参数,如果有该类型,就赋值给这个参数
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    UserService userService;
 
    /**
     * 定义要赋值的参数类型
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz = methodParameter.getParameterType();
        return clazz == User.class;
    }
 
    /**
     * 具体执行赋值的方法
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取request和response
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        //分别在request的参数中和cookie中查询我们的需要的token
        String paramToken = request.getParameter(UserService.TOKEN);
        String cokieToken = getCookieToken(request, UserService.TOKEN);
 
        String token = StringUtils.isEmpty(paramToken) ? cokieToken : paramToken;
        return userService.getByToken(response,token);
    }
 
    private String getCookieToken(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(UserService.TOKEN)) {
                return cookie.getValue();
            }
        }
        return null;
    }
}

3.把我们编写的处理类注册到配置中

package com.example.miaosha_xdp.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import java.util.List;
 
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Autowired
    UserArgumentResolver userArgumentResolver;
 
    /**
     * 添加我们到处理器到配置中
     * @param argumentResolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
       argumentResolvers.add(userArgumentResolver);
    }
}

4.这样我们最开始的代码就变了类下面的

package com.example.miaosha_xdp.controller;


import com.example.miaosha_xdp.entity.User;
import com.example.miaosha_xdp.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/goods")
public class GoodsController {
   private static Logger logger = LoggerFactory.getLogger(GoodsController.class);
   @Autowired
   UserService userService;

   @RequestMapping("/to_list")
   public String to_login(Model model,User user) {
       model.addAttribute("user",user);
       return "goods_list";
   }
   
}
上一篇下一篇

猜你喜欢

热点阅读