java - Validating a form in JSP -


i'm validating simple form using spring , hibernate in jsp (using simpleformcontroller) of hibernatevalidator explained here. form containing 1 field follows.

<%@page contenttype="text/html" pageencoding="utf-8" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  <form:form method="post" id="userform" name="userform" action="temp.htm" commandname="validationform">                <table>         <tr>             <td>user name:<font color="red"><form:errors path="username" /></font></td>         </tr>          <tr>             <td><form:input path="username" /></td>         </tr>                         <tr>             <td><input type="submit" value="submit" /></td>         </tr>         </table>  </form:form> 

the following command class in validation criteria defined.

package validators;  import javax.validation.constraints.size; import org.hibernate.validator.constraints.notempty;   final public class validationform  {     @notempty(message="must not left blank.")     @size(min = 1, max = 2)     private string username;      public void setusername(string username)     {             this.username = username;     }      public string getusername()     {             return username;     }         } 

the following dispatchar-servlet.xml file different configurations can made.

<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"    xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop"                  xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">     <bean class="org.springframework.web.servlet.mvc.support.controllerclassnamehandlermapping" /> <bean class="org.springframework.web.servlet.mvc.simplecontrollerhandleradapter" />   <bean id="tempservice" class="usebeans.tempserviceimpl" /> <bean id="tempcontroller" class="controller.temp" p:tempservice-ref="tempservice" p:formview="temp" p:successview="temp"/>  <bean id="messagesource" class="org.springframework.context.support.reloadableresourcebundlemessagesource">     <property name="basename" value="/web-inf/messages" /> </bean>  <bean id="urlmapping" class="org.springframework.web.servlet.handler.simpleurlhandlermapping">     <property name="mappings">         <props>             <prop key="index.htm">indexcontroller</prop>             <prop key="temp.htm">tempcontroller</prop>                         </props>     </property> </bean>  <bean id="viewresolver"       class="org.springframework.web.servlet.view.internalresourceviewresolver"       p:prefix="/web-inf/jsp/"       p:suffix=".jsp" />  <bean name="indexcontroller"       class="org.springframework.web.servlet.mvc.parameterizableviewcontroller"       p:viewname="index" /> 

tempservice interface containing 1 method add(validationform validationform){...} , tempserviceimpl class implements tempservice interface.

the controller class temp follows.

package controller;  import java.util.hashmap; import java.util.map; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.validation.valid; import org.springframework.validation.bindexception; import org.springframework.web.bind.annotation.modelattribute; import org.springframework.web.servlet.modelandview; import org.springframework.web.servlet.mvc.simpleformcontroller; import usebeans.tempservice; import validators.validationform;  @suppresswarnings("deprecation") final public class temp extends simpleformcontroller {     private tempservice tempservice=null;     public temp()     {                     setcommandclass(validationform.class);         setcommandname("validationform");     }      //this method may not necessary.     public void settempservice(tempservice tempservice)      {         this.tempservice = tempservice;     }      @override     protected modelandview onsubmit(httpservletrequest request, httpservletresponse response, @modelattribute("validationform") @valid object command, bindexception errors) throws exception     {         validationform validationform=(validationform) command;         tempservice.add(validationform);   //may not necessary.                  if(errors.haserrors())  //never evaluates true though text box on form left blank.         {                             system.out.println("user name : "+validationform.getusername());             //or something.         }             else         {             //do stuff such database operations insert, update or delete.          }                   modelandview mv=new modelandview("temp", "validationform", validationform);         return mv;     }      @override     protected modelandview showform(httpservletrequest request, httpservletresponse response, bindexception errors) throws exception     {                     modelandview mv=new modelandview("temp", "validationform", new validationform());         return mv;     } } 

now, happening here when form submitted on clicking submit button on form, onsubmit() method in controller class temp invoked in i'm imposing if condition if(errors.haserrors()){}.

accordingly, if textfield on form empty, form rendering contains validation errors , if condition should evaluated true , specified error message should displayed (as specified in validationform class @notempty(message="must not left blank.")) never happens [the object of validationform available through object command parameter of onsubmit() method]. condition never evaluates true whether or not text box contains value.

what missing here? feel i'm following wrong way use hibernatevalidator. hints or guidelines helpful me.

[the application runs no errors form intended validated isn't validated]

putting @valid on method params doesn't work old-fashioned controllers extend commandcontroller , children (e.g., simpleformcontroller). feature of annotationmethodhandleradapter, need using annotated controller work.

(there reason had suppress deprecation warning on class! :) )

reader's digest version:

instead of defining own urlmapping , in dispatcher use <mvc:annotation-driven/>

then instead of extending simpleformcontroller make regular class , annotate @controller , method @requestmapping.

@controller @requestmapping("/temp.htm") public class temp {  @requestmapping(method=requestmethod.get) public modelandview getform() {   modelandview mv=new modelandview("temp", "validationform", new validationform());   return mv; }  @requestmapping(method=requestmethod.post) public modelandview postform(@valid validationform validationform, bindingresult errors) {         tempservice.add(validationform);   //may not necessary.                  if(errors.haserrors())  //never evaluates true though text box on form left blank.         {                             system.out.println("user name : "+validationform.getusername());             //or something.         }             else         {             //do stuff such database operations insert, update or delete.          }                   modelandview mv=new modelandview("temp", "validationform", validationform);         return mv; } 

there tons of tutorials on internet way more content can reproduce here. check out current version of spring petclinic sample application detailed examples.


Comments

Popular posts from this blog

All overlapping substrings matching a java regex -

c++ - Using OpenSSL in a multi-threaded application -

php - Deleting/Renaming a locked file -