spring validation 源码分析

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】
免费领取10G资料包与项目实战视频资料

http://www.blogjava.net/syniii/archive/2010/11/24/338906.html

aware解释

aware

EnvironmentCapable

EnvironmentAware

spring-core

spring-bean

spring-web

spring-webmvc

在云盒项目中,后台管理表单数据校验目前都是硬编码,同时这种硬编码跟业务逻辑的处理混在一起,也违背编码单一职责原则,有没有好点办法方法将这数据校验与业务处理分离开呢?我研究了一下spring mvc ,确实有个叫做spring validation,这个还有规范,Bean Validation 1.0(JSR-303)最新都1.1了,hibernate validation 对它进行了很好实现。下面介绍一下怎么使用以及实现原理

1.怎么应用

导入如下两个包

配置validation相关spring bean

web 层controller 怎么配置

velocity

2.代码实现

private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,

NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {

Class[] paramTypes = handlerMethod.getParameterTypes();

Object[] args = new Object[paramTypes.length];

for (int i = 0; i < args.length; i++) {

MethodParameter methodParam = new MethodParameter(handlerMethod, i);

methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);

GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());

String paramName = null;

String headerName = null;

booleanrequestBodyFound = false;

String cookieName = null;

String pathVarName = null;

String attrName = null;

booleanrequired = false;

String defaultValue = null;

booleanvalidate = false;

Object[] validationHints = null;

intannotationsFound = 0;

Annotation[] paramAnns = methodParam.getParameterAnnotations();

for (Annotation paramAnn : paramAnns) {

if (RequestParam.class.isInstance(paramAnn)) {

RequestParamrequestParam = (RequestParam) paramAnn;

paramName = requestParam.value();

required = requestParam.required();

defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());

annotationsFound++;

}

else if (RequestHeader.class.isInstance(paramAnn)) {

RequestHeaderrequestHeader = (RequestHeader) paramAnn;

headerName = requestHeader.value();

required = requestHeader.required();

defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());

annotationsFound++;

}

else if (RequestBody.class.isInstance(paramAnn)) {

requestBodyFound = true;

annotationsFound++;

}

else if (CookieValue.class.isInstance(paramAnn)) {

CookieValuecookieValue = (CookieValue) paramAnn;

cookieName = cookieValue.value();

required = cookieValue.required();

defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());

annotationsFound++;

}

else if (PathVariable.class.isInstance(paramAnn)) {

PathVariablepathVar = (PathVariable) paramAnn;

pathVarName = pathVar.value();

annotationsFound++;

}

else if (ModelAttribute.class.isInstance(paramAnn)) {

ModelAttributeattr = (ModelAttribute) paramAnn;

attrName = attr.value();

annotationsFound++;

}

else if (Value.class.isInstance(paramAnn)) {

defaultValue = ((Value) paramAnn).value();

}

else if (paramAnn.annotationType().getSimpleName().startsWith(“Valid”)) {

validate = true;

Object value = AnnotationUtils.getValue(paramAnn);

validationHints = (value instanceof Object[] ? (Object[]) value : new Object[] {value});

}

}

if (annotationsFound > 1) {

thrownew IllegalStateException(“Handler parameter annotations are exclusive choices – “ +

“do not specify more than one such annotation on the same parameter: “ + handlerMethod);

}

if (annotationsFound == 0) {

Object argValue = resolveCommonArgument(methodParam, webRequest);

if (argValue != WebArgumentResolver.UNRESOLVED) {

args[i] = argValue;

}

else if (defaultValue != null) {

args[i] = resolveDefaultValue(defaultValue);

}

else {

Class<?> paramType = methodParam.getParameterType();

if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {

if (!paramType.isAssignableFrom(implicitModel.getClass())) {

throw new IllegalStateException(“Argument [“ + paramType.getSimpleName() + “] is of type “ +

“Model or Map but is not assignable from the actual model. You may need to switch “ +

“newer MVC infrastructure classes to use this argument.”);

}

args[i] = implicitModel;

}

else if (SessionStatus.class.isAssignableFrom(paramType)) {

args[i] = this.sessionStatus;

}

else if (HttpEntity.class.isAssignableFrom(paramType)) {

args[i] = resolveHttpEntityRequest(methodParam, webRequest);

}

else if (Errors.class.isAssignableFrom(paramType)) {

thrownew IllegalStateException(“Errors/BindingResult argument declared “ +

“without preceding model attribute. Check your handler method signature!”);

}

else if (BeanUtils.isSimpleProperty(paramType)) {

paramName = “”;

}

else {

attrName = “”;

}

}

}

if (paramName != null) {

args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);

}

else if (headerName != null) {

args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler);

}

elseif (requestBodyFound) {

args[i] = resolveRequestBody(methodParam, webRequest, handler);

}

else if (cookieName != null) {

args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);

}

else if (pathVarName != null) {

args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);

}

else if (attrName != null) {

WebDataBinder binder =

resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);

boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));

if (binder.getTarget() != null) {

doBind(binder, webRequest, validate, validationHints, !assignBindingResult);

}

args[i] = binder.getTarget();

if (assignBindingResult) {

args[i + 1] = binder.getBindingResult();

i++;

}

implicitModel.putAll(binder.getBindingResult().getModel());

}

}

returnargs;

}

private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate,

Object[] validationHints, boolean failOnErrors) throws Exception {

doBind(binder, webRequest);

if (validate) {

binder.validate(validationHints);

}

if (failOnErrors && binder.getBindingResult().hasErrors()) {

throw new BindException(binder.getBindingResult());

}

}

public void validate(Object… validationHints) {

for (Validator validator : getValidators()) {

if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) {

((SmartValidator) validator).validate(getTarget(), getBindingResult(), validationHints);

}

else if (validator != null) {

validator.validate(getTarget(), getBindingResult());

}

}

}


来源:[]()

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » spring validation 源码分析

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏