Announcement Announcement Module
Collapse
No announcement yet.
Validation in MultiActionController (Spring MVC) Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Validation in MultiActionController (Spring MVC)

    Hi,

    I'm trying to implement validation for view in MultiActionController. But i'm struck. I'm sure that there should be some way to implement validation something similar to SimpleFormController, but unable to sort out, what it colud be. Please help in this regard.

  • #2
    Can you post what you've tried so far?

    Comment


    • #3
      code snippets

      Please find my code below and suggest any corrections needed.

      controller-servlet.xml
      --------------------

      Code:
      <bean name="/test.do" class="com.test.controller.TestController" >
        <property name="methodNameResolver">
            <bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
      	<property name="paramName" value="methodToCall"/>
            </bean>
        </property>
      </bean>
      <bean name="viewBean" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
          <property name="prefix" value="/jsp/"></property>
      
          <property name="suffix" value=".jsp"></property>
      </bean>
      TestController
      -------------
      Code:
      public class TestController extends MultiActionController{
      	
      	
      	public ModelAndView result(HttpServletRequest request, HttpServletResponse response,TestCommand otestCommand) 
          throws Exception {
      		
      	
      		ModelAndView mav = new ModelAndView("Result","resultCommand", otestCommand);
      		TestValidator testValidator = new TestValidator();
      		Object delegate = new Object();
      		BindException errors = new BindException(otestCommand, "otestCommand");
      		testValidator.validate(otestCommand, errors);
      		HashMap resultMap = new HashMap();
      		if(errors.hasErrors()){
      			resultMap.put("otestCommand",otestCommand);
      			//mav =  new ModelAndView("Test","otestCommand", otestCommand);
      			
      			//mav.addObject("errors",errors);
      			//bind(request, errors);
      			
      			resultMap.put("errors",errors);
      			mav =  new ModelAndView("Test",resultMap);
      		   
      			return mav;
      		}
      		mav.addObject("Name", otestCommand.getFirstName());
      		mav.addObject("Qual", otestCommand.getQualification());
      		
      		return mav;
      	}
      
      	public ModelAndView home(HttpServletRequest request, HttpServletResponse response,TestCommand otestCommand ) 
          throws Exception {
      		
      	
      		ModelAndView mav = new ModelAndView("Test","otestCommand", otestCommand);
      		
      	   
      		return mav;
      	}
      		
      }
      Test.jsp
      --------
      Code:
      <script type="text/javascript">
      	function test()
      	  {
      	     
      	     document.testForm.action = "test.do?methodToCall=result";
      	     document.testForm.submit();
      	  }
      </script>
      
      <form name="testForm" method="post">
          <spring:nestedPath path="otestCommand"> 
           <table>
           <c:out value="${errors}"/>
               <tr>	<c:forEach var="err" items="${errors.globalErrors}">
                      <span class="error"><c:out value="${err.defaultMessage}"/></span><br />
                    </c:forEach>
              
      
      
               		<spring:bind path="firstName">
               			         			
               			<c:out value="${status.value}"/>
                       <td>Enter Name<input type="text" name="firstName" value="<c:out value="${status.value}"/>"></td>
                       <c:out value="${status.errorMessage}"/>
                       
                       </spring:bind>
                </tr> 
      		<tr><spring:bind path="qualification">
                        <td>Enter Qualification:<input type="text" name="qualification" ></td>
                        <c:out value="${status.value}"/>
                        </spring:bind>
                   </tr>
      	  <tr>
                  <td>Click me :<input type ="button" name="Submit" value="Submit" onclick="return test()">
              </tr>
           </table>
            </spring:nestedPath>
      </form>
      TestValidator
      -------------
      Code:
      public class TestValidator implements Validator
      {
         private final Log logger = LogFactory.getLog(getClass());
         
         public boolean supports(Class givenClass)
         {
            return givenClass.equals(TestCommand.class);
         }
         
         public void validate(Object obj, Errors errors)
         {
      	   TestCommand givenData = (TestCommand)obj;
            
            if (givenData == null)
            {
               errors.reject("error.nullpointer", "Null data received");
            }
            else
            {
              
          	  ValidationUtils.rejectIfEmptyOrWhitespace(errors,  "firstName", "required.firstname", "First name is required");
              /* if (givenData.getAge().length() < 0) {
              	 errors.rejectValue("age", "negativevalue");
               } else if (givenData.getAge().length() > 10) {
              	 errors.rejectValue("age", "too.darn.old");
               }*/
      
            }
         }
      }
      TestCommand
      -------------

      Code:
      public class TestCommand {
      	
      	public String firstName=null;
      	public String qualification=null;
      
      	public String getFirstName() {
      		return firstName;
      	}
      	public void setFirstName(String firstName) {
      		this.firstName = firstName;
      	}
      		
      	public String getQualification() {
      		return qualification;
      	}
      	public void setQualification(String qualification) {
      		this.qualification = qualification;
      	}
      
      }
      Please suggest a way to implement validation.

      Thanks in advance.
      Last edited by rev1nth; Oct 13th, 2008, 02:33 AM.

      Comment


      • #4
        Hello!! Please anybody help

        Comment


        • #5
          Why dont you switch to annotated controllers of spring 2.5?
          Wth that you can create controllers like old multiaction style with simpleformcontrollers capabilities.
          Read the official documentation of spring 2.5

          Comment


          • #6
            Just for example:

            Code:
            @Controller
            @SessionAttributes("user")
            @RequestMapping("/someurlpath*")
            public class MyController
            {
            
                @Autowired	
                private UserServicerImpl userService;
            
                @ModelAttribute("command")
                public User populateUser(HttpServletRequest request)
                {		
                    	
            	return new User();
            
                }
            
                //EXAMPLE FOR PROCESSING FORM SUBMIT, LIKE OLD SIMPLEFORMCONTROLLER
                @RequestMapping(params="action=new_user") 
                public String userLoginHandler(method = RequestMethod.POST,
                                                           ModelMap model,
                                                           @ModelAttribute("user") User user,
                                                           BindingResult result )
                {	
                     	
                     UserValidator userValidator = new UserValidator(user, result);
                     if(result.hasErrors())
                     {
                          return "user_registration";
                     }
            	 this.userService.registerNew(user.getUserName(),user.getPassword());
            	 return "redirect:/someurlpath.html?action=user_registered";
                     
                }	    
            
                @RequestMapping(params="action=user_registered")
               { 
                   return "user_registered";
               }
            
                //EXAMPLES OF OLD MULTIACTIONCONTROLLER STYLE
                @RequestMapping(params="action=link1")
                public String onLink1Hadler()
                {
                    return "link1_page";
                }  
            
            
               @RequestMapping(params="action=link2")
                public String onLink1Hadler()
                {
                    return "link2_page";
                }  
            
               @RequestMapping("/sublink1")
                public String onLink1Handler(@RequestParam("param1") Integer param1,
                                                        @RequestParam("param2") String param2)
                {
            
                    /*Do something with param1 and param2 variables*/
                    return "sublink1_page";
                }  
            
            
                 
            
            }

            In this way u can able to integrate in unique controllers multiactioncontroller and simpleformcontrollers capabilities.
            Again, onto the same controller u can process multiple submits from various forms (not only one).
            The annotated controllers want @Controller annotation at class level,optionally @SessionAttribute("some_command_name") in order to execute binding and processing submit and a @RequestMapping, wich give to spring's controller the infotmation about wich url classes must mapped by controller; in the example, MyController map all address starting with /someurlpath* (ex: /someurlpath/path1, or /someurlpath.html?action=new_user, and so on).

            Again, tanks to annotastion, the method signature is very very flexible, u can insert various "in" parameters for your convenience.
            This is only a little hint.
            Take a look of the official docs, annotated controllers now are very powrful.

            Best regards
            riboriori
            Last edited by riboriori; Oct 11th, 2008, 07:38 AM.

            Comment


            • #7
              @rev1nth: Are you sure you're posting the form to the proper URL?

              http://localhost:8080/testapp/contro...dToCall=result

              In your code you have the submit button making a JavaScript call, though you didn't provide the code for that. I replaced it with

              <td>Click me :<input type="submit" name="Submit" value="Submit"></td>

              and the validation worked fine...

              Comment


              • #8
                riboriori, thanks for your suggestion, but i need an implementation in MultiActionController.


                wwheeler, thanks for your reply.

                This is how my page displays after submitting. The errors corresponding to the text field are not displayed by using <c: out value="${status.errorMessage}"/>.

                How can I bind the errors to the field or property? Is my approach towards validation in MultiActionController correct? or is there any better way?

                i have updated the javascript, that i'm using in jsp in my earlier post.

                <script type="text/javascript">
                function test()
                {

                document.testForm.action = "test.do?methodToCall=result";
                document.testForm.submit();
                }
                </script>

                Comment

                Working...
                X