spring mvc 創建下拉框並進行驗證demo

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

該例子主要介紹瞭如何對下拉框是否選值進行驗證。其中驗證主要使用JSR-303,數據綁定經過spring,該例子主要基於JSR-303驗證例子的代碼進行了簡單的修改,其項目結構以下所示:html

首先,添加DepartmentVO模型。java

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引用。web

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來對其進行轉換。spring

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中添加綁定方法。spring-mvc

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文件。tomcat

<%@ 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訪問。mvc

相關文章
相關標籤/搜索