ModifyModel modifyModel = new ModifyModel(); modifyModel.setUserId(getCurrentEmployee().getId()); modifyModel.setUserName(getCurrentEmployee().getName()); if (request.getId() == 0) { ModelHelper.buildCreateAndModify(request, modifyModel, true); deptService.insert(request); } else { ModelHelper.buildCreateAndModify(request, modifyModel, false); deptService.updateByPrimaryKey(request); }
我们可以利用参数注入来解决。参数注入的理念就是在spring mvc接收到前台请求的参数后,进一步对接收到的参数做处理以达到预期的效果。我们来创建ManageModelConfigMethodArgumentResolver,它需要实现HandlerMethodArgumentResolver,这个接口看起来比较简单,包含两个核心方法:
@Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(ManageModelConfig.class); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object manageModel =getRequestResponseBodyMethodProcessor().resolveArgument(parameter, mavContainer, webRequest, binderFactory); ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class); Employee currentUser = (Employee) servletRequest.getAttribute(DEFAULT_ATTRIBUTE_GET_USER_FROM_REQUEST); if (null == currentUser) { return manageModel; } ManageModelConfig parameterAnnotation = parameter.getParameterAnnotation(ManageModelConfig.class); ModelHelper.setDefaultAndSystemFieldsValue(manageModel, currentUser,parameterAnnotation.isSetDefaultFieldsValue()); return manageModel; }
这段函数有几处核心逻辑:
private RequestMappingHandlerAdapter requestMappingHandlerAdapter=null; private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor = null; private RequestResponseBodyMethodProcessor getRequestResponseBodyMethodProcessor() { if(null==requestMappingHandlerAdapter) { requestMappingHandlerAdapter=new RequestMappingHandlerAdapter(); } if (null==requestResponseBodyMethodProcessor) { List<HttpMessageConverter<?>> messageConverters = requestMappingHandlerAdapter.getMessageConverters(); messageConverters.add(new MappingJackson2HttpMessageConverter()); requestResponseBodyMethodProcessor = new RequestResponseBodyMethodProcessor(messageConverters); } return requestResponseBodyMethodProcessor; }
通过如下代码就可以取到参数对象了,其实就是让spring mvc重新解析了一遍参数。
Object manageModel =getRequestResponseBodyMethodProcessor().resolveArgument(parameter, mavContainer, webRequest, binderFactory);
ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class); Employee currentUser = (Employee) servletRequest.getAttribute(DEFAULT_ATTRIBUTE_GET_USER_FROM_REQUEST);