SpringMVC使用Hibernate Validator进行后台校验

一、导入Hibernate Validator的相关Jar包

SpringMVC使用Hibernate Validator进行后台校验_第1张图片

二、环境搭建

1.配置web.xml


<servlet>
    <servlet-name>springDispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:demo1/springMVC.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
    <servlet-name>springDispatcherServletservlet-name>
    
    <url-pattern>/url-pattern>
servlet-mapping>
  
<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:demo1/springMVC.xmlparam-value>
context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

<filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    
    <init-param>
        <param-name>encodingparam-name>
        <param-value>utf-8param-value>
    init-param>
    
    <init-param>
        <param-name>forceResponseEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
    
    <init-param>
        <param-name>forceRequestEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

2.配置springMVC.xml


<context:component-scan base-package="demo1">context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/">property>
    <property name="suffix" value=".jsp">property>
bean>

3.前端页面

SpringMVC使用Hibernate Validator进行后台校验_第2张图片

4.实体类

public class Person {
	 @NotEmpty
	 private String username;
	 @Length(min = 5,max = 8)
	 private String password;
	 @Email
	 private String email;
 }

5.控制层

SpringMVC使用Hibernate Validator进行后台校验_第3张图片

6.结果

SpringMVC使用Hibernate Validator进行后台校验_第4张图片

你可能感兴趣的:(SSM)