通过spring验证器类进行验证时,jsp页面上的异常

时间:2013-01-25 11:59:46

标签: spring-mvc

我在使用验证器类验证spring im时遇到问题,验证正确发生但是对于int and date类型,当我在表单字段中提供不同类型的字符串时,则整个exception被粘贴我的jsp页面我想在那上面提供正确的消息格式。我想要做的更多事情我想在这个验证器类中使用正则表达式,请提供一段正则表达式的代码片段,以便我可以在这个验证器类中实现

这是我的控制器

    package com.nousinfo.tutorial.controllers;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.ServletRequestDataBinder;
    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.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    import com.nousinfo.tutorial.model.EmployeeForm;
    import com.nousinfo.tutorial.service.impl.EmployeeServiceImpl;
    import com.nousinfo.tutorial.service.impl.ProjectServiceImpl;
    import com.nousinfo.tutorial.service.model.EmployeeBO;
    import com.nousinfo.tutorial.validator.EmployeeValidator;

    /**
     * 
     * @author ankurj
     * 
     */
    @Controller
    @RequestMapping("employee")
    public class EmployeeController {

        private EmployeeServiceImpl employeeServiceImpl;
        private ProjectServiceImpl projectServiceImpl;
        private EmployeeValidator employeeValidator;

        public void setEmployeeServiceImpl(EmployeeServiceImpl employeeServiceImpl) {
            this.employeeServiceImpl = employeeServiceImpl;
        }

        /**
         * Set the view to Employee Form
         * 
         * @param model
         *            is the entity mapped to form object
         * @return view
         * @throws Exception
         */
        @RequestMapping(value = "/searchspring", method = RequestMethod.GET)
        public String view(Model model) throws Exception {
            EmployeeBO employeeBO = new EmployeeBO();
            model.addAttribute("employeeBO", employeeBO);
            return "EmployeeForm";
        }

        public void setEmployeeValidator(EmployeeValidator employeeValidator) {
            this.employeeValidator = employeeValidator;
        }

        /**
         * set the view to "AboutUS"
         * 
         * @return VIEW
         */
        @RequestMapping(value = "/aboutUs", method = RequestMethod.GET)
        public String aboutUsView() {
            return "AboutNous";
        }

        /**
         * This method is used to insert the detail of employee or simply create new
         * employee with detail
         * 
         * @param employeeForm
         *            is the model entity mapped to form object
         * @param bindingResult
         * @param model
         * @return
         * @throws Exception
         */
        @RequestMapping(value = "/createEmployee", method = RequestMethod.POST)
        public ModelAndView createEmployee(
                @ModelAttribute("employeeBO") EmployeeBO employeeBO,
                BindingResult bindingResult) throws Exception {
            ModelAndView model = new ModelAndView();
            employeeValidator.validate(employeeBO, bindingResult);
            System.out.println(bindingResult);
            System.out.println(employeeBO.getEmployeeNumber());
            if (bindingResult.hasErrors()) {
                model.setViewName("EmployeeForm");
                return model;
            }
            model.addObject("employeeBO", employeeBO);

            if (employeeBO.getUpdateStatus() == 'A') {
                boolean flag = employeeServiceImpl.actionDecider(employeeBO);
                if (flag == false) {
                    model.setViewName("DBError");

                } else
                    model.setViewName("Success");
            }

            return model;
        }
}

这是我的验证员类

package com.nousinfo.tutorial.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.nousinfo.tutorial.service.model.EmployeeBO;

public class EmployeeValidator implements Validator {

    public boolean supports(Class<?> arg0) {
        return EmployeeBO.class.isAssignableFrom(arg0);
    }

    public void validate(Object object, Errors errors) {
        boolean found = false;
        Pattern pattern = Pattern.compile("[0-9]");

        ValidationUtils.rejectIfEmpty(errors, "firstName",
                "employeeBO.firstName");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "employeeBO.title");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city",
                "employeeBO.city");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "state",
                "employeeBO.state");

        EmployeeBO employeeBO = (EmployeeBO) object;

        if (pattern.matcher(employeeBO.getFirstName()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("firstName", "employeeregex.string");
        }

        if (pattern.matcher(employeeBO.getLastName()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("lastName", "employeeregex.string");
        }

        if (pattern.matcher(employeeBO.getCity()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("city", "employeeregex.string");
        }
        if (pattern.matcher(employeeBO.getState()).find()) {
            found = true;
        }
        if (found) {
            errors.rejectValue("state", "employeeregex.string");
        }
        if (employeeBO.getEmployeeNumber() == null) {

            errors.rejectValue("employeeNumber", "employeeBO.employeeNumber");

        }
        if (employeeBO.getPincode() == null) {
            errors.rejectValue("pincode", "employeeBO.pincode");

        }

        if (employeeBO.getTelephoneNumber() == null) {
            errors.rejectValue("telephoneNumber", "employeeBO.telephoneNumber");

        }
        if (employeeBO.getMobileNumber() == null)
            errors.rejectValue("mobileNumber", "employeeBO.mobileNumber");

    }

}

这是我提供输入的jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/taglibs/input-1.0"
    prefix="input"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Create Employee</title>
<script>
    function home() {
        window.location.href = "/EmployeeWebSpring/search/searchspring";

    }
</script>
</head>

<body background="../images/flower.jpg">

    <table width="1254" height="74" border="0" align="center">

        <tr>

            <td width="20" height="68" align="center" bgcolor="#FFFFFF"><img
                src="../images/Header.png" width="1300" height="92" /></td>
        </tr>
    </table>
    <p>
        <br />
    </p>
    <hr size="1" width="1254">
    <h1 align="center">
        <font color="FFA54F">Employee Form</font>
    </h1>
    <form:form id="form" method="post"
        action="/EmployeeWebSpring/employee/createEmployee"
        commandName="employeeBO">
        <table align="center" class="table">
            <tr>
                <form:hidden path="updateStatus" value="A" />
            </tr>
            <tr>
                <td>EmployeeNumber:</td>


                <td><form:input path="employeeNumber" /><font color="red"><form:errors
                            path="employeeNumber" /></font></td>
            </tr>
            <tr>
                <td>First_Name:</td>

                <td><form:input path="firstName" /><font color="red"><form:errors
                            path="firstName" /></font></td>
            </tr>

            <tr>
                <td>Last_Name:</td>

                <td><form:input path="lastName" /><font color="red"><form:errors
                            path="lastName" /></font></td>
            </tr>
            <tr>
                <td>Title:</td>

                <td><form:input path="title" /><font color="red"><form:errors
                            path="title" /></font></td>
            </tr>
            <tr>
                <td>Department_Id:</td>

                <td><form:input path="departmentId" /></td>
            </tr>
            <tr>
                <td>Address1:</td>

                <td><form:input path="address1" /></td>
            </tr>
            <tr>
                <td>Address2:</td>

                <td><form:input path="address2" /></td>
            </tr>
            <tr>
                <td>City:</td>

                <td><form:input path="city" /><font color="red"><form:errors
                            path="city" /></font></td>
            </tr>

            <tr>
                <td>State:</td>

                <td><form:input path="state" /><font color="red"><form:errors
                            path="state" /></font></td>
            </tr>
            <tr>

                <td>Pincode:</td>

                <td><form:input path="pincode" /><font color="red"><form:errors
                            path="pincode" /></font></td>
            </tr>
            <tr>
                <td>Telephone_Number:</td>

                <td><form:input path="telephoneNumber" /><font color="red"><form:errors
                            path="telephoneNumber" /></font></td>
            </tr>

            <tr>
                <td>Mobile_Number:</td>

                <td><form:input path="mobileNumber" /><font color="red"><form:errors
                            path="mobileNumber" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Birth:</td>

                <td><form:input path="dateOfBirth" /><font color="red"><form:errors
                            path="dateOfBirth" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Anniversary:</td>

                <td><form:input path="dateOfAnniversary" /><font color="red"><form:errors
                            path="dateOfAnniversary" /></font></td>
            </tr>

            <tr>
                <td>Date_Of_Joining:</td>

                <td><form:input path="dateOfJoining" /><font color="red"><form:errors
                            path="dateOfJoining" /></font></td>
            </tr>
            <tr>
                <td>Date_Of_Leaving:</td>

                <td><form:input path="dateOfLeaving" /><font color="red"><form:errors
                            path="dateOfLeaving" /></font></td>
            </tr>
            <tr>
                <td>Reason_For_Leaving:</td>

                <td><form:input path="reasonForLeaving" /></td>
            </tr>
        </table>

        <br>
        <br />
        <p>&nbsp;</p>
        <br>

        <table align="center">
            <tr>
                <td><input type="submit" name="method" value="Save" /></td>
                <td><input type="button" value="Cancel" onclick="home()" /></td>
            </tr>
        </table>
        <hr size="1" width="786">
        <p>&nbsp;</p>
    </form:form>
</body>
</html>

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为问题来自于您没有初始化控制器中的转换器。

您需要添加的第一件事是控制器中的InitBinder

@InitBinder public void initBinder(WebDataBinder binder) {
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");  //Select the format you want
 dateFormat.setLenient(false); 
 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

根据您的目的,您将需要不同的CustomEditor:

 binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); //Trim strings
 binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); //to handle file upload

您还可以在EmployeeBO添加以下注释,具体取决于您要使用的类型:

@Temporal(TemporalType.TIMESTAMP) 
@DateTimeFormat(style = "S-")  //format: 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-'.
private Date dateOfBirth;

@NumberFormat(style=Style.NUMBER)
private Long employeeNumberamount;