使用form:options进行表单验证

时间:2013-02-27 21:41:14

标签: java spring jsp

Form:Options工作得很好,但如果我在表单中提交了错误的数据,则form:options中的newContact.jsp会将departmentList的第一个元素显示为已选中。

的ContactController:

@RequestMapping(value="/saveContact", method=RequestMethod.GET)
public ModelAndView newuserForm(){
    ModelAndView mav = new ModelAndView("newContact");
//  Contact contact = new Contact();        
//  Department department = new Department();
    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String name = user.getUsername();
    mav.addObject("username", name);
    mav.addObject("newContact", new Contact());
//  mav.addObject("department", department);
    mav.addObject("departmentList", departmentService.listDepartment());

    //mav.getModelMap().put("newContact", contact);
    return mav;
}

@RequestMapping(value="/saveContact", method=RequestMethod.POST)
public String create(@ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,Map<String, Object> map)
{
    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String name = user.getUsername();

    map.put("departmentList", departmentService.listDepartment());
    map.put("username", name);

    contactFormvalidator.validate(contact, result);
    if (result.hasErrors()) 
    {               
        return "newContact";
    }
    contactService.addContact(contact);
    status.setComplete();
    //return "redirect:/showContacts.do";
    return "newContactSuccess";
}

newContact.jsp:

<%@include file="header.jsp"%>

<div id="menu">
    <div id="subMenu"></div>
</div>


<div id="main">

    <h2>Contact Manager</h2>

    <form:form  method="post" action="saveContact.do" commandName="newContact" >

        <table>
            <tr>
                <td><form:label path="firstname">
                        <spring:message code="label.firstname" />
                    </form:label></td>
                <td><form:input path="firstname" /></td>
                <td><form:errors path="firstname" cssStyle="color:red"></form:errors> </td>
            </tr>
            <tr>
                <td><form:label path="lastname">
                        <spring:message code="label.lastname" />
                    </form:label></td>
                <td><form:input path="lastname" /></td>
                <td><form:errors path="lastname" cssStyle="color:red"></form:errors> </td>
            </tr>
            <tr>
                <td><form:label path="email">
                        <spring:message code="label.email" />
                    </form:label></td>
                <td><form:input path="email" /></td>
                <td><form:errors path="email" cssStyle="color:red"></form:errors> </td>
            </tr>
            <tr>
                <td><form:label path="telephone">
                        <spring:message code="label.telephone" />
                    </form:label></td>
                <td><form:input path="telephone" /></td>
                <td><form:errors path="telephone" cssStyle="color:red"></form:errors> </td>
            </tr>

            <tr>    
                <td><form:label path="department">
                        <spring:message code="label.department" />
                    </form:label></td>  
                    <td><form:select path="department" >        
                    <form:option  label="**SELECT**" value="0"></form:option>                           
                            <form:options  items="${departmentList}"  itemValue="id" itemLabel="name"></form:options>                           
                        </form:select> </td>
                    <td><form:errors path="department" cssStyle="color:red"></form:errors> </td>
            </tr>  



            <tr>
                <td colspan="2"><input type="submit"
                    value="<spring:message code="label.addcontact"/>" /></td>
            </tr>



        </table>
    </form:form>        

</div>

<%@ include file="footer.jsp"%>

ContactFormValidator:

package pl.ivmx.contact.validator;

import java.util.regex.*;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import pl.ivmx.contact.form.Contact;;

//@Component("contactFormValidator")
public class ContactFormValidator implements Validator{
    @Override
    public boolean supports(Class clazz) {
        return Contact.class.isAssignableFrom(clazz);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validate(Object obj, Errors errors) {       
        Contact contact = (Contact) obj;
        Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*@[a-zA-Z]*.[a-zA-Z]*");
        Matcher m = p.matcher(contact.getEmail());
        boolean b = m.matches();
        if (b != true) {
            errors.rejectValue("email", "error.is.not.valid",
                    "Email  does not Valid ");
        }

        if (contact.getFirstname() == null || contact.getFirstname().length() < 3) {
            errors.rejectValue("firstname", "error.empty.field",
                    "Please Enter First Name");
        }

        if (contact.getLastname() == null || contact.getLastname().length() < 4) {
            errors.rejectValue("lastname", "error.empty.field",
                    "Please Enter Last Name");
        }

        if (contact.getTelephone() == 0 || String.valueOf(contact.getTelephone()).trim().length() < 2 ||
                String.valueOf(contact.getTelephone()).trim().length() > 9) {
            errors.rejectValue("telephone", "error.empty.field",
                    "Please Enter Telephone");
        }

        if (contact.getDepartment() == null) {
            errors.rejectValue("department", "error.empty.field",
                    "Please select department");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

而不是在提交方法中返回String,而是返回ModelAndView ...

@RequestMapping(value="/saveContact", method=RequestMethod.POST)
public ModelAndView create(@ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,ModelMap map)
    {
       User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       String name = user.getUsername();

       map.addAttribute("departmentList", departmentService.listDepartment());
       map.addAttribute("username", name);

       contactFormvalidator.validate(contact, result);
       if (result.hasErrors()) 
       {               
         return new ModelAndView("newContact",map);
       }
       contactService.addContact(contact);
       status.setComplete();
       //return new ModelAndView("redirect:/showContacts.do");
       return new ModelAndView("newContactSuccess");

}