HandlerMethodArgumentResolver完美解决 springmvc注入参数多传报错

作为一个后端开发,能友好兼容前端参数传入错误等问题,在前端发布不小心多传一个参数导致系统错误的问题,一个广告系统是零容忍的,所以为了不犯错误,后端接收参数必须摒弃spring 的自动注入@RequestBody,

1、那么我们就要自定义解析器重写HandlerMethodArgumentResolver的两个方法

package com.qlkj.jgt.flow.app.resolver;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.jkzj.common.base.BaseSO;
import com.fqgj.jkzj.common.base.BaseVO;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
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.HttpServletRequest;
import java.io.IOException;

/**
 * @author vampire
 * @date 2019/3/28 4:41 PM
 */
public class CustomArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class paramObjClass = methodParameter.getParameterType();
//这里我定义的是如果入参为继承基类的时候就进入这个自定义参数解析方法中
if (BaseSO.class.isAssignableFrom(paramObjClass)) { return true; } return false; } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { Class paramObjClass = parameter.getParameterType(); String json = getRequestBody(webRequest); Object paramObj = paramObjClass.newInstance(); Object object = JSONObject.parseObject(json, paramObjClass); return object != null ? object : paramObj; } private String getRequestBody(NativeWebRequest webRequest) { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); String jsonBody = (String) webRequest.getAttribute("params", NativeWebRequest.SCOPE_REQUEST); if (jsonBody == null) { try { jsonBody = IOUtils.toString(servletRequest.getInputStream()); webRequest.setAttribute("params", jsonBody, NativeWebRequest.SCOPE_REQUEST); } catch (IOException e) { throw new RuntimeException(e); } } return jsonBody; } }

2、xml加入我们的自定义解析器

   <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="com.qlkj.jgt.flow.app.resolver.CustomArgumentResolver"/>
        </mvc:argument-resolvers>
 </mvc:annotation-driven>

 

3、入参是要注意  入参前不能添加 @RequestBody  否则走的是spring默认的注入参数

 

posted @ 2019-06-03 19:17  挖坑大王  阅读(8035)  评论(0编辑  收藏  举报