spring mvc 建立下拉框并进行验证demo

原文出处:http://howtodoinjava.com/spring/spring-mvc/spring-mvc-populate-and-validate-dropdown-example/

该例子主要介绍了如何对下拉框是否选值进行验证。其中验证主要使用JSR-303,数据绑定通过spring,该例子主要基于JSR-303验证例子的代码进行了简单的修改,其项目结构如下所示:

spring mvc 建立下拉框并进行验证demo

首先,添加DepartmentVO模型。

package com.howtodoinjava.demo.model;

public class DepartmentVO
{
public DepartmentVO(Integer id, String name) {
super();
this.id = id;
this.name = name;
} private Integer id;
private String name; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "DepartmentVO [id=" + id + ", name=" + name + "]";
}
}

  然后在EmployeeVO类中添加DepartmentVO引用。

package com.howtodoinjava.demo.model;

import java.io.Serializable;

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

public class EmployeeVO implements Serializable
{
private static final long serialVersionUID = 1L; private Integer id; @NotEmpty
private String firstName; private String lastName; private String email; @NotNull
private DepartmentVO department; //Setters and Getters
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
}
public DepartmentVO getDepartment() {
return department;
} public void setDepartment(DepartmentVO department) {
this.department = department;
} @Override
public String toString() {
return "EmployeeVO [id=" + id + ", firstName=" + firstName
+ ", lastName=" + lastName + ", email=" + email
+ ",department=" + department +"]";
}
}

  因为前台提交表单时,在post中department不是直接提交给后台一个实例,而是一个字符串,所以需要对其进行转换,在该例子中主要利用PropertyEditorSupport来对其进行转换。

package com.howtodoinjava.demo.convertor;

import java.beans.PropertyEditorSupport;
import com.howtodoinjava.demo.model.DepartmentVO; public class DepartmentEditor extends PropertyEditorSupport
{
//This will be called when user HTTP Post to server a field bound to DepartmentVO
@Override
public void setAsText(String id)
{
DepartmentVO d;
switch(Integer.parseInt(id))
{
case 1: d = new DepartmentVO(1, "Human Resource"); break;
case 2: d = new DepartmentVO(2, "Finance"); break;
case 3: d = new DepartmentVO(3, "Information Technology"); break;
default: d = null;
}
this.setValue(d);
}
}

  这样当用户提交POST请求时,该方法就会被调用,并new一个对应的DepartmentVO实例。转换的目的实现了,然后就是让Spring使用这个类型,所以需要在EmployeeController中添加绑定方法。

package com.howtodoinjava.demo.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set; import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; 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.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus; import com.howtodoinjava.demo.convertor.DepartmentEditor;
import com.howtodoinjava.demo.model.DepartmentVO;
import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager; @Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController {
@Autowired
EmployeeManager manager; private Validator validator; public EmployeeController()
{
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(DepartmentVO.class, new DepartmentEditor());
} @ModelAttribute("allDepartments")
public List<DepartmentVO> populateDepartments()
{
ArrayList<DepartmentVO> departments = new ArrayList<DepartmentVO>();
departments.add(new DepartmentVO(-1, "Select Department"));
departments.add(new DepartmentVO(1, "Human Resource"));
departments.add(new DepartmentVO(2, "Finance"));
departments.add(new DepartmentVO(3, "Information Technology"));
return departments;
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
EmployeeVO employeeVO = new EmployeeVO();
model.addAttribute("employee", employeeVO);
return "addEmployee";
} @RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
BindingResult result, SessionStatus status) { Set<ConstraintViolation<EmployeeVO>> violations = validator.validate(employeeVO); for (ConstraintViolation<EmployeeVO> violation : violations)
{
String propertyPath = violation.getPropertyPath().toString();
String message = violation.getMessage();
// Add JSR-303 errors to BindingResult
// This allows Spring to display them in view via a FieldError
result.addError(new FieldError("employee",propertyPath, "Invalid "+ propertyPath + "(" + message + ")"));
} if (result.hasErrors()) {
return "addEmployee";
}
// Store the employee information in database
// manager.createNewRecord(employeeVO); // Mark Session Complete
status.setComplete();
return "redirect:addNew/success";
} @RequestMapping(value = "/success", method = RequestMethod.GET)
public String success(Model model) {
return "addSuccess";
}
}

  然后是修改jsp文件。

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <html>
<head>
<title>Add Employee Form</title>
<style>
.error
{
color: #ff0000;
font-weight: bold;
}
</style>
</head> <body>
<h2><spring:message code="lbl.page" text="Add New Employee" /></h2>
<br/>
<form:form method="post" modelAttribute="employee">
<table>
<tr>
<td><spring:message code="lbl.firstName" text="First Name" /></td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td><spring:message code="lbl.lastName" text="Last Name" /></td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td><spring:message code="lbl.email" text="Email Id" /></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr> <!-- DROPDOWN code --> <tr>
<td><spring:message code="lbl.department" text="Department" /></td>
<td><form:select path="department" items="${allDepartments}" itemValue="id" itemLabel="name" /></td>
<td><form:errors path="department" cssClass="error" /></td>
</tr> <tr>
<td colspan="3"><input type="submit" value="Add Employee"/></td>
</tr>
</table>
</form:form>
</body>
</html>

  所有事情完成之后,发布到tomcat中,通过http://localhost:8080/dropdownDemo/employee-module/addNew访问。

spring mvc 建立下拉框并进行验证demo

上一篇:Unity3D方法来隐藏和显示对象


下一篇:WEB 3D SVG CAD 向量 几个实施(转)