#javax.validation.valid
controller中的方法经常会变的很长,根据业务不同,经常会对参数做很多校验。比如非空、字段长度、正则表达式...
如果按照普通方式,无非就是垒 if...else...。
所幸,@Valid给我们提供了方便。这里使用Hibernate Validation的实现。
关于JSR-303 Validation的规范、JSR-303原生支持的限制 以及 自定义限制类型。这里不错介绍。
下面看例子。
package com.zl.valid;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zl.result.AjaxResult;
@Controller
@RequestMapping(value = "/banner")
public class ValidController {
@RequestMapping("/list")
@ResponseBody
public AjaxResult list(@Valid BannerListRequest req, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
return AjaxResult.failed(bindingResult.getFieldErrors().get(0).getDefaultMessage());
}
System.out.println("=======获取bannerlist 成功=============");
return AjaxResult.success();
}
}
package com.zl.valid;
import javax.validation.constraints.NotNull;
public class BannerListRequest {
@NotNull(message = "position不可为空")
private Integer position;
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
}
web.xml中配置springmvc的servlet
mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:spring/spring-study.xml
1
spring-study.xml如下
text/plain;charset=utf-8
text/html;charset=utf-8
text/json;charset=utf-8
application/json;charset=utf-8
WriteMapNullValue
WriteNullListAsEmpty
WriteNullStringAsEmpty
WriteNullNumberAsZero
WriteNullBooleanAsFalse
WriteDateUseDateFormat
DisableCircularReferenceDetect
QuoteFieldNames
image/jpeg
image/png
image/jpg
image/gif
application/x-bmp
text/html;charset=UTF-8
text/plain;charset=UTF-8
text/html;charset=UTF-8
json=application/json
xml=application/xml
html=text/html
/WEB-INF/tiles.xml
上面最重要是
到此为止代码结束,看下运行效果。
按照之前我的一片文章中,配置的tomat-embed插件,启动项目
webapp目录:/Users/mac/workplace/study/SpringMVCStudy/src/main/webapp
六月 28, 2017 3:49:32 下午 org.apache.catalina.core.ApplicationContext log
信息: No Spring WebApplicationInitializer types detected on classpath
六月 28, 2017 3:49:32 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
六月 28, 2017 3:49:32 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization started
六月 28, 2017 3:49:32 下午 org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
信息: Refreshing Root WebApplicationContext: startup date [Wed Jun 28 15:49:32 CST 2017]; root of context hierarchy
六月 28, 2017 3:49:32 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from URL [file:/Users/mac/qbao_workplace/study/SpringMVCStudy/target/classes/spring/spring-market.xml]
六月 28, 2017 3:49:32 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7ffb0a21: defining beans [configLoader,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
六月 28, 2017 3:49:32 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization completed in 474 ms
六月 28, 2017 3:49:32 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'mvc'
六月 28, 2017 3:49:32 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
信息: FrameworkServlet 'mvc': initialization started
六月 28, 2017 3:49:32 下午 org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
信息: Refreshing WebApplicationContext for namespace 'mvc-servlet': startup date [Wed Jun 28 15:49:32 CST 2017]; parent: Root WebApplicationContext
六月 28, 2017 3:49:32 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from URL [file:/Users/mac/qbao_workplace/study/SpringMVCStudy/target/classes/spring/spring-study.xml]
六月 28, 2017 3:49:32 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@27a1daf1: defining beans [viewResolver,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,tilesConfigurer,multipartResolver,validator,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#1,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,goController,validController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@7ffb0a21
15:49:33.359 [localhost-startStop-1] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
15:49:33.362 [localhost-startStop-1] INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 4.3.1.Final
15:49:33.374 [localhost-startStop-1] DEBUG o.h.v.i.e.r.DefaultTraversableResolver - Cannot find javax.persistence.Persistence on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.
15:49:33.375 [localhost-startStop-1] DEBUG o.h.v.i.engine.ConfigurationImpl - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
15:49:33.376 [localhost-startStop-1] DEBUG o.h.v.i.engine.ConfigurationImpl - Setting custom ConstraintValidatorFactory of type org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
15:49:33.378 [localhost-startStop-1] DEBUG o.h.v.i.xml.ValidationXmlParser - Trying to load META-INF/validation.xml for XML based Validator configuration.
15:49:33.385 [localhost-startStop-1] DEBUG o.h.v.i.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only.
六月 28, 2017 3:49:33 下午 org.springframework.web.servlet.view.tiles2.TilesConfigurer setDefinitions
信息: TilesConfigurer: adding definitions [/WEB-INF/tiles.xml]
15:49:33.666 [localhost-startStop-1] INFO o.a.t.c.AbstractTilesApplicationContextFactory - Initializing Tiles2 application context. . .
15:49:33.668 [localhost-startStop-1] INFO o.a.t.c.AbstractTilesApplicationContextFactory - Finished initializing Tiles2 application context.
15:49:33.722 [localhost-startStop-1] INFO org.apache.tiles.access.TilesAccess - Publishing TilesContext for context: org.springframework.web.servlet.view.tiles2.SpringTilesApplicationContextFactory$SpringWildcardServletTilesApplicationContext
六月 28, 2017 3:49:33 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping registerHandlerMethod
信息: Mapped "{[/index || /],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.zl.controller.GoController.index(org.springframework.ui.Model) throws java.lang.Exception
六月 28, 2017 3:49:33 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping registerHandlerMethod
信息: Mapped "{[/],methods=[HEAD],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.zl.controller.GoController.head()
六月 28, 2017 3:49:33 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping registerHandlerMethod
信息: Mapped "{[/banner/list],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.zl.result.AjaxResult com.zl.valid.ValidController.list(com.zl.valid.BannerListRequest,org.springframework.validation.BindingResult)
六月 28, 2017 3:49:34 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
信息: FrameworkServlet 'mvc': initialization completed in 1458 ms
********************************************************
启动成功: http://localhost:8100 in:6106ms
********************************************************
打开浏览器,分别输入
http://localhost:8100/banner/list.html
http://localhost:8100/banner/list.html?position=1
返回结果
{
"code": 1,
"data": null,
"message": "position不可为空",
"success": false
}
{
"code": 0,
"data": null,
"message": "",
"success": true
}
转载于:https://my.oschina.net/u/2447594/blog/1057819