SpringMVC @Valid表单验证

1.首先是pom文件, 只列出了验证一块的,springmvc版本是:4.3.10

<!--验证注解-->
    <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-core</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1.1</version>
    </dependency>


    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.2.4.Final</version>
    </dependency>
    <!--验证注解-->

2.springmvc-servlet.xml

<bean id="message" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>    <!-- 错误提示的配置文件-->
                <value>classpath:jmessage</value>
            </list>
        </property>
         <!--这个好像不是必须的,处理编码的吧-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 我不清楚这个有什么用-->
        <property name="cacheSeconds" value="120"/>
          
    </bean>
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        <property name="validationMessageSource" ref="message"/>
    </bean>

     <mvc:annotation-driven validator="validator"  />
         

jmessage.properties

error.notnull="不能为空"
error.password="长度请在6~16之间"
error.birthday="生日必须是过去的时间"
error.email="请把保持邮箱格式!"
error.number="你输入的含有非数字!"

3.user类

public class user {
    @NotNull(message = "{error.notnull}")   ===>notnull用在int上
    private  int id;
    @NotBlank(message = "{error.notnull}") ==> notblank 用在string上
    private  String name;
    @NotBlank
    @Size(min = 6,max = 16,message = "{error.password}")
    private String password;
   // @NotNull(message = "{error.notnull}")
    @Past(message = "{error.birthday}")
    @DateTimeFormat(pattern = "YYYY-MM-dd") ==>如果你没有定义时间转换器的话,请加上此注解,输入格式为你在这规定的!最好是用时间转换吧,因为它是全局的,
    private Date birthday;
    @NotBlank(message = "{error.notnull}")
    @Email(message = "{error.email}")
    private  String email;

   // get --set
    }

4.Controller

package controller;

import jObject.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
public class formcontroller {


     @RequestMapping("form")
     public ModelAndView form(){  ====>这个的作用是显示表单页面
         System.out.println("----form---------");
         ModelAndView modelAndView=new ModelAndView();
          modelAndView.setViewName("1");==>那个页面
         modelAndView.addObject("user",new user());==>表单要绑定的对象
         return  modelAndView;
     }
     @RequestMapping("save")===>表单提交,到这里
                               不能用Requestparam注解
     public String save(@Valid @ModelAttribute("user")user user, BindingResult result, Model model){
         System.out.println("----save---------");
         if (result.hasErrors()){ ==>如果有错误
             System.out.println("错误:"+result.getFieldError());打印
             model.addAttribute ("errors",result.getFieldError());==>错误信息返回到页面
             model.addAttribute("user",user);//不至于表单被清空!
             return "1";
         }else{
             return "3";==>没有错误的做法
         }
     
     }
}

5. JSP页面

<mvc:form action="save" modelAttribute="user" >
 <mvc:label path="id">id</mvc:label>
 <mvc:input path="id"/>
 <mvc:errors path="id"></mvc:errors>
 <br>
    <mvc:label path="name">name</mvc:label>
    <mvc:input path="name"/>
    <mvc:errors path="name"></mvc:errors>
    <br>
    <mvc:label path="password">password</mvc:label>
    <mvc:input path="password"/>
    <mvc:errors path="password"></mvc:errors>
    <br>
    <mvc:label path="birthday">birthday</mvc:label>
    <mvc:input path="birthday"/>
    <mvc:errors path="birthday"></mvc:errors>
    <br>
    <mvc:label path="email">email</mvc:label>
    <mvc:input path="email"/>
    <mvc:errors path="email"></mvc:errors>
    <br>
    <input type="submit">
    <br>
</mvc:form>

如果出现中文乱码请加上过滤器

1.处理 前台传给我们的中文乱码

web.xml内
<!--处理,前台传给我们的中文乱码-->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--针对request-->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!--针对response,这个我不清楚-->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

2.处理我们传给前台的@ResponseBody中文乱码

<mvc:annotation-driven>
          <mvc:message-converters>
              <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                  <constructor-arg value="UTF-8"/>
                  <!--@ResponseBody中文乱码-->
              </bean>
          </mvc:message-converters>
     </mvc:annotation-driven>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值