SpringBoot实现HandlerMethodArgumentResolver(自定义参数解析器)

对Controller层请求参数进行处理

自定义注解 

@Documented  
@Target({ElementType.PARAMETER})  
@Retention(RetentionPolicy.RUNTIME)  
public @interface CommonParams {
	
	String[] params() default {};
	
}

自定义参数解析器

/***
 * 自定义注解
 * && CommonParamsArgumentResolver(CommonParamsArgumentResolver.class)
 */
@Component
public class CommonParamsArgumentResolver implements HandlerMethodArgumentResolver {
	
	/** 日志实例 */
	private static final Logger logger = Logger.getLogger(CommonParamsArgumentResolver.class);

	@Override  
	public boolean supportsParameter(MethodParameter parameter) {
		// 如果参数类型是TokenModel则支持
		Class klass = parameter.getParameterType(); 
		Annotation annotations = parameter.getParameterAnnotation(CommonParams.class);  
		if (null!=annotations && klass.isAssignableFrom(CommonParamsModel.class)) { 
			  return true;
	    }  
	    return false;  
	}

	
    @SuppressWarnings("finally")
	@Override  
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    	CommonParamsModel commonParamsModel = new CommonParamsModel();
    	logger.info("CommonParamsArgumentResolver>>resolveArgument start");
    	try {
			//Class klass = parameter.getParameterType(); 
			HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
			
			commonParamsModel.setToken(null==request.getHeader("token")?"":request.getHeader("token").trim());
			commonParamsModel.setRemoteIp(CommonParamsArgumentResolver.getRemoteHostIp(request));
			commonParamsModel.setLocalAddr(request.getLocalAddr());
			commonParamsModel.setLocalPort(request.getLocalPort());
			commonParamsModel.setServletPath(request.getServletPath());
			commonParamsModel.setScheme(request.getScheme());
			commonParamsModel.setServerName(request.getServerName());
			
			//获取注解需要获取的参数
			CommonParams annotations = parameter.getParameterAnnotation(CommonParams.class);
			if(null != annotations){
				String[] params = annotations.params();
				if(null!=params){
					for (String key : params) {
						logger.info("CommonParamsArgumentResolver>>key:"+key);
					}
				}
			} 
			
		} catch (Exception e) {
			commonParamsModel = new CommonParamsModel();
			logger.info("CommonParamsArgumentResolver>>resolveArgument Exception:"+e.getMessage());
			e.printStackTrace();
		}finally{
			logger.info("CommonParamsArgumentResolver>>commonParamsModel:"+commonParamsModel);
			return commonParamsModel;
		}
    	
	}
 
     public static String getRemoteHostIp(HttpServletRequest request){
	   	String hostIp = "";
	   	try{
	   		String forwarded= request.getHeader("X-Forwarded-For");
	   		logger.info("################forwarded forwarded X-Forwarded-For###########:"+forwarded);
	   		if(null!=forwarded && forwarded.trim().length()>0){
	   			String[] forwardedArray = forwarded.split("\\,");
	   			if(null!=forwardedArray && forwardedArray.length>0){
	   				if(null!=forwardedArray[0] && forwardedArray[0].trim().length()>0){
	   					hostIp = null==forwardedArray[0]?"":forwardedArray[0].trim();
	   					logger.info("################hostIp X-Forwarded-For###########:"+hostIp);
	   				} 
	   			}
	   		}
	   		if(null==hostIp || "".equals(hostIp)){
	   			hostIp = null==request.getRemoteHost()?"":request.getRemoteHost();
	   			logger.info("################hostIp getRemoteHost###########:"+hostIp);
	   		}
	   	}catch (Exception e) {
	   		hostIp = "";
	   		logger.info("################hostIp getRemoteHost Exception###########:"+e.getMessage());
		}
	   	return hostIp;
	}

}

在启动类中注入

@Configuration
@ServletComponentScan
@ImportResource(locations = { "classpath:/applicationContext.xml" })
@SpringBootApplication
public class HrHrpRestfulNewApplication extends WebMvcConfigurationSupport {

	@Autowired
	private CommonParamsArgumentResolver commonParamsArgumentResolver;
	
	public static void main(String[] args) {
        SpringApplication.run(HrHrpRestfulNewApplication.class, args);
    }
	
	@Override
	public void addArgumentResolvers(List argumentResolvers){
		argumentResolvers.add(commonParamsArgumentResolver);
		super.addArgumentResolvers(argumentResolvers);
	}
	
}

Controller 

@Controller
public class HomeController extends BaseRestfulController {

	protected final Logger logger = Logger.getLogger(getClass());
	
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/home/info",method = RequestMethod.GET)
	public ResponseEntity getInfo(HomeInfoReqDTO reqDTO,@CommonParams CommonParamsModel commonParamsModel) {
            CommonParamsModel commonParams = commonParamsModel;
}

请求

SpringBoot实现HandlerMethodArgumentResolver(自定义参数解析器)_第1张图片

SpringBoot实现HandlerMethodArgumentResolver(自定义参数解析器)_第2张图片

 

你可能感兴趣的:(Spring)