spring MVC中基于hibernate validator的form表单验证

首先,在pom.xml中添加hibernate.validator的支持

		
		
			org.hibernate
			hibernate-validator
			4.3.1.Final
		

表单提交页面user_add.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




add user


	
		添加用户
		账号:
		
		
		密码:
		
		
		
		
		
	


新建一个用于验证的Bean:ValidUserBean

package com.worldless.admin.controller;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;

@Component("ValidUserBean")
public class ValidUserBean {

	@NotEmpty
	@Email
	private String account;
	
	@NotEmpty
	@Length(min=6,max=16)
	private String password;

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

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

来修改controller,

package com.worldless.admin.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RequestMethod;

@Controller
public class AdminController {

	@Autowired
	private ValidUserBean validUserBean;

        //通过url访问新增页面
	@RequestMapping(value = "admin/add", method = RequestMethod.GET)
	public String userNew(Model model) {
		model.addAttribute("validUserBean", validUserBean);
		return "admin/user_add";
	}

        //点击按钮提交时
	@RequestMapping(value = "admin/add", method = RequestMethod.POST)
	public String userAdd(
			@ModelAttribute("validUserBean") @Valid ValidUserBean validUserBean,
			BindingResult result, Model model) {
		if (!result.hasErrors()) {
			model.addAttribute("show", "ok");
		}
		return "admin/user_add";
	}

}

访问页面

输入错误时显示


输入正确时显示



你可能感兴趣的:(spring,tool,suite(STS),spring,MVC,jsp相关)