#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
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring/spring-study.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
spring-study.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!--aop用户请求日志,在springMVC里需要加上这一行aop才能起作用 -->
<!-- <aop:aspectj-autoproxy /> -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator"/>
</bean>
</property>
<property name="messageConverters">
<list>
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
<value>text/json;charset=utf-8</value>
<value>application/json;charset=utf-8</value>
</list>
</property>
<property name="features">
<list>
<value>WriteMapNullValue</value>
<value>WriteNullListAsEmpty</value>
<value>WriteNullStringAsEmpty</value>
<value>WriteNullNumberAsZero</value>
<value>WriteNullBooleanAsFalse</value>
<value>WriteDateUseDateFormat</value>
<value>DisableCircularReferenceDetect</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>image/jpeg</value>
<value>image/png</value>
<value>image/jpg</value>
<value>image/gif</value>
<value>application/x-bmp</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.FormHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="0" />
<property name="contentNegotiationManager">
<bean
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true" />
<property name="favorParameter" value="true" />
<property name="parameterName" value="format" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
html=text/html
</value>
</property>
<property name="defaultContentType" value="text/html" />
</bean>
</property>
<property name="defaultViews">
<list>
<bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView" />
</list>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="resolveLazily" value="true" />
<property name="maxUploadSize" value="5242880" />
</bean>
<!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<!--<property name="validationMessageSource" ref="messageSource"/>-->
</bean>
<mvc:annotation-driven validator="validator"/>
<context:component-scan base-package="com.zl" />
</beans>
上面最重要是
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator"/>
</bean>
</property>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<!--<property name="validationMessageSource" ref="messageSource"/>-->
</bean>
<mvc:annotation-driven validator="validator"/>
到此为止代码结束,看下运行效果。
按照之前我的一片文章中,配置的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
********************************************************
打开浏览器,分别输入
返回结果
{
"code": 1,
"data": null,
"message": "position不可为空",
"success": false
}
{
"code": 0,
"data": null,
"message": "",
"success": true
}