用Spring MVC表单验证

用Spring MVC表单验证_第1张图片

web.xml



<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring.xml,classpath:spring-validate.xmlparam-value>
  context-param>
  
  <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>
  filter>

  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>


  <servlet>
    <servlet-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

spring-mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
    
    <context:component-scan base-package="com.lyf.controller" />
    <mvc:annotation-driven />



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



beans>

spring-validate.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    



    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        
        <property name="validationMessageSource" ref="messageSource" />
    bean>



    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        
        <property name="basename" value="classpath:messages" />
        <property name="fileEncodings" value="utf-8" />
        <property name="cacheSeconds" value="120" />
    bean>




beans>

spring.xml

s
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd         
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <mvc:default-servlet-handler/>

beans>

messages.properties

NotEmpty.userModel.userName=用户名不能为空.
NotNull.userModel.age=年龄不能为空
NotEmpty.userModel.password=密码不能为空

NotEmpty.userModel.xm=真实姓名不能为空
Pattern.userModel.age=必须数字
Range.userModel.age=超范围了

UserModel

package com.lyf.po;

import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.Pattern;

/**
 * Created by fangjiejie on 2017/6/6.
 */
public class UserModel {
    @NotEmpty
    private String username;
    @NotEmpty
    private String password;
    @NotEmpty
    @Pattern(regexp = "^\\d+$")
    @Range(min=0,max = 99)
    private String age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

ValidateController

package com.lyf.controller;

import com.lyf.po.UserModel;
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 javax.validation.Valid;
import java.util.Map;

/**
 * Created by fangjiejie on 2017/6/6.
 */
@Controller
@RequestMapping("/validate")
public class ValidateController {
    //1.spring-mvc配置必须使用自动注解形式,否则不好使
    //2.视图层必须使用spring控件,否则不好使
    //3.以下语句必须首先实例化个空对象,并且装在model中,否则出现找不到属性错误
    //键的名字是"userModel",且值是vo的类名,首字母小写,契约式编程
    //4.视图层中必须有commandName:"userModel",且值是vo的类名,首字母小写,契约式编程
    @RequestMapping("/show")
    public String showForm(Map map){
        UserModel user=new UserModel();
        map.put("user",user);
        return "validationform";
    }
   @RequestMapping("/val")
        public String validate(@Valid @ModelAttribute("user") UserModel user, BindingResult result, Model model){
     if(result.hasErrors()){
         return "validationform";
     }else{
         return "validationsuccess";
     }
    }
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: fangjiejie
  Date: 2017/6/6
  Time: 16:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<a href="/validate/show">表单验证a>
body>
html>

validationform.jsp

<%--
  Created by IntelliJ IDEA.
  User: fangjiejie
  Date: 2017/6/6
  Time: 16:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Titletitle>
head>
<body>

<form:form method="post" action="/validate/val" commandName="user">
    <h4 align="center"><u>登录页u>h4>
    <table align="center">
        <tr>
            <td>用户名:td>
            <td><form:input path="username" /><font color="red">
                <form:errors    path="username" />font>td>
        tr>
        <tr>
            <td>年龄:td>
            <td><input type="number" name="age" value="10" ><font color="red">
                <form:errors path="age" />font>td>
        tr>
        <tr>
            <td>密码:td>

            <td><form:password path="password" /><font color="red">
                <form:errors     path="password" />font>



            td>
        tr>
        <tr>

        <tr>
            <td>td>
            <td><input type="submit" value="Submit" />td>
        tr>
    table>
form:form>
body>
html>

validationsuccess.jsp

<%--
  Created by IntelliJ IDEA.
  User: fangjiejie
  Date: 2017/6/6
  Time: 16:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h2>注册成功!h2>
body>
html>

你可能感兴趣的:(springmvc,spring,mvc,validation)