Announcement Announcement Module
Collapse
No announcement yet.
How to do validation using MultiActionController Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • #16
    no secret now

    Since, I have included my source. Maybe I can tell you more about this multiactioncontroller.

    You might noticed my validator part. With this, you can assign which validator should be executed when which method is called.

    Comment


    • #17
      jerry,

      do u want me to override the bind method in my controller?

      Could you tell me exactly what I have to do next?

      Thanks

      Comment


      • #18
        talk to you later as i am at work.

        talk to you later as i am at work.

        Comment


        • #19
          Thank u very much jerry for ur great job

          Thank you jerry for your kind reply. I am waiting for you...

          Comment


          • #20
            Successfully Completed

            Hi jerry,

            My sincere thanks to you. I successfully completed my Validation with MultiActionController.

            Thank you for your great job.

            Thanks once again for every once support.

            Comment


            • #21
              what's wrong? I'd like to know.

              what's wrong? I'd like to know.

              Comment


              • #22
                Hi jerry,

                As you suggested I overridden the bind() method in my controller.

                public class PhoneBookController extends MultiActionController
                {


                BindingResult errors; //Declaring errors as instance variable to catch error


                protected void bind(HttpServletRequest request, Object command) throws Exception
                {
                //This contain similar to your bind, with modifications for my specific application,
                }



                public ModelAndView newcontactHandler(HttpServletRequest request, HttpServletResponse response)
                {
                if(errors.hasErrors())
                {
                return new ModelAndView("addcontact",errors.getModel());
                }
                return new ModelAndView("add-success");
                }
                }
                }}

                The only place where I end up is unable to catch the BindingException, which here I resolved by declaring the errors as instance variable.

                ****** Thank you 'Jerry' for your support *********

                Comment


                • #23
                  Generally we have mapping in xml file for dispatcher servlet to decide which controller to use as per URL mapping but if we have to take decision on basis of request parameters then MultiActionController can be used.

                  Spring offers a multi-action controller with which multiple actions can be aggregated into one controller, grouping functionality together. The multi-action controller is capable of mapping requests to method names and then invoking the right method name. Using the multi-action controller is especially handy when you have a lot of common functionality in one controller, but want to have multiple entry points to the controller.
                  r4 revolution for ds

                  Comment


                  • #24
                    Hi sarvanan,
                    I went through this forum and found that i am also facing the same difficulty which you went through before.. Could you send the code that you have written while overriding the bind method..
                    I would be very much thankfull to you if you could help me.

                    Thnx
                    Levis

                    Comment


                    • #25
                      Hi Levis, sorry for the belated reply

                      I think the code is already available in this thread, given by one of our friend jerry, thanks to him. Anyhow I will repaste the code here

                      The following is my multi action controller,

                      public class MyController extends MultiActionController
                      {

                      BindingResult errors; //Declaring errors as instance variable to catch error


                      /** My overidden bind() method */

                      protected void bind(HttpServletRequest request, Object command) throws Exception
                      {
                      ServletRequestDataBinder binder = createBinder(request, command);
                      binder.bind(request);
                      errors = binder.getBindingResult();
                      }



                      /** My validator */

                      public void MyValidator(Object command)
                      {
                      /** Invoking validator **/
                      Validator[] validators = getValidators();
                      if (validators != null)
                      {
                      for (int index = 0; index < validators.length; index++)
                      {
                      Validator validator = validators[index];
                      if (validator instanceof CustomerInfoValidator)
                      {
                      if (((CustomerInfoValidator)validator).supports(comma nd.getClass())) ValidationUtils.invokeValidator(validators[index], command, errors);
                      }
                      else if (validator.supports(command.getClass()))
                      ValidationUtils.invokeValidator(validators[index], command, errors);
                      }
                      }
                      }



                      /** this is my method handler */

                      public ModelAndView newcontactHandler(HttpServletRequest request, HttpServletResponse response)
                      {
                      if(errors.hasErrors())
                      {
                      return new ModelAndView("addcontact",errors.getModel());
                      }
                      return new ModelAndView("add-success");
                      }
                      }
                      }

                      }


                      I hope this help, If u can't understand let me know...

                      Comment


                      • #26
                        still Facing the Same Problem with Multiaction controller

                        Hi...


                        With which version of Spring you are able to display errors using Validator in Multiaction controller
                        i'm using spring 2.0.6.....and facting the problem...
                        getting Exception as :

                        ommand=com.person.formBean.Person@604dd8
                        org.springframework.validation.BindingResult.comma nd=org.springframework.validation.BeanPropertyBind ingResult: 1 errors Error in object 'command': codes [LName req.command,LName req]; arguments []; default message [null]

                        Thanks in advance...

                        Comment


                        • #27
                          I really suggest people who use Spring read the source code.

                          Comment


                          • #28
                            mailny i'm facing problem with the command object....

                            Comment


                            • #29
                              public ModelAndView newcontactHandler(HttpServletRequest request, HttpServletResponse response)

                              If this is your signature, you haven't passed in your command object. As in the source code, MultiActionController, method name invokeNamedMethod,
                              if (paramTypes.length >= 3 &&
                              !paramTypes[paramTypes.length - 1].equals(HttpSession.class)) {
                              Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
                              params.add(command);
                              bind(request, command);
                              }

                              You won't have the command object.

                              Comment


                              • #30
                                Pls look at the code and tell me where i'm doing wrong

                                ----------------------------------------------------
                                Controller Class
                                ----------------------------------------------------
                                /**
                                *
                                */
                                package com.person.controller;

                                import java.io.IOException;
                                import java.util.List;

                                import javax.servlet.http.HttpServletRequest;
                                import javax.servlet.http.HttpServletResponse;

                                import org.apache.log4j.Logger;
                                import org.springframework.validation.BindException;
                                import org.springframework.validation.BindingResult;
                                import org.springframework.validation.ValidationUtils;
                                import org.springframework.validation.Validator;
                                import org.springframework.web.HttpRequestMethodNotSuppor tedException;
                                import org.springframework.web.bind.ServletRequestBinding Exception;
                                import org.springframework.web.bind.ServletRequestDataBin der;
                                import org.springframework.web.bind.ServletRequestUtils;
                                import org.springframework.web.servlet.ModelAndView;
                                import org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController;

                                import com.person.formBean.Person;
                                import com.person.service.IPersonService;
                                import com.person.validator.PersonValidator;

                                /**
                                * @author bdontu
                                * PersonController class is used to define multiple operations for Person
                                *
                                */
                                public class PersonController extends MultiActionController {
                                /**
                                * Service Injection
                                */
                                private IPersonService personService;
                                /**
                                * Logger definition
                                */
                                private Logger logger = Logger.getLogger(PersonController.class);

                                /**
                                * This MEthod is used to show Add Person Page.
                                * @param request
                                * @param response
                                * @return
                                */
                                public ModelAndView showPage(HttpServletRequest request,
                                HttpServletResponse response) {
                                logger.info("##############Entered showPage Method###################");
                                ModelAndView mav=new ModelAndView("addperson");
                                mav.addObject("personForm",new Person());
                                if (null != request.getAttribute("errorsExist")
                                && Boolean.parseBoolean(request.getAttribute("errorsE xist").toString()) == true) {
                                mav.addObject("errorsExist",true);
                                }
                                return mav;
                                }
                                /**
                                * This Method is used to
                                * @param request
                                * @param response
                                * @param command
                                * @return
                                * @throws IOException
                                * @throws HttpRequestMethodNotSupportedException
                                * @throws ServletRequestBindingException
                                */
                                public ModelAndView addPerson(HttpServletRequest request,
                                HttpServletResponse response,Person command) throws IOException,
                                HttpRequestMethodNotSupportedException, ServletRequestBindingException {
                                logger.info("Entered addPerson Method###################");
                                ModelAndView mav = new ModelAndView("addperson","command",command);
                                try {
                                if (null != command) {
                                // add validator and call bind object to get the result
                                BindException errors = bindObject(request, command, new PersonValidator());;
                                logger.info("After errors checking");
                                if (errors.hasErrors()) {
                                //check for existance of errors
                                mav.addObject("errorMap",errors.getModel());
                                } else {
                                //No Errors exist in the form then save the Person Object
                                Person person = new Person();
                                person.setFirstName(command.getFirstName());
                                person.setLastName(command.getLastName());
                                if (null != command.getId()) {
                                logger.info("Updating Person with Id.."+command.getId());
                                person.setId(command.getId());
                                }
                                personService.savePerson(person);
                                List<Person> personList = personService.getAllPerson();
                                return new ModelAndView("viewallpersons", "personList", personList);
                                }
                                }
                                return mav;
                                } catch (Exception ex) {
                                ex.printStackTrace();
                                return null;
                                }

                                }


                                /**
                                * This Method is used to check errors that exist in the form.
                                * @param request
                                * @param command
                                * @param validator
                                * @return
                                * @throws Exception
                                */
                                protected BindException bindObject(HttpServletRequest request,
                                Object command, Validator validator) throws Exception {
                                bind(request, command);
                                ServletRequestDataBinder binder = createBinder(request, command);
                                binder.bind(request);
                                //BindingResult brErrors = binder.getBindingResult();
                                BindException errors = new BindException(command,
                                getCommandName(command));
                                if (validator.supports(command.getClass())) {
                                ValidationUtils.invokeValidator(validator, command, errors);
                                }
                                logger.error("Errors Count : "+errors.getErrorCount());
                                return errors;
                                }

                                public void setPersonService(IPersonService personService) {
                                this.personService = personService;
                                }

                                }

                                --------------------------------------------------
                                my displatcher servlet : person-servlet.xml
                                --------------------------------------------------


                                <beans>
                                <bean class="com.person.validator.PersonValidator" id="personValidator"/>
                                <!-- This bean is a MethodNameResolver definition for a
                                MultiActionController. It maps URLs to methods for the
                                "PersonController" bean.-->
                                <bean id="methodNameResolver"
                                class="org.springframework.web.servlet.mvc.multiac tion.PropertiesMethodNameResolver">
                                <property name="mappings">
                                <props>
                                <prop key="/addPerson.html">addPerson</prop>
                                <prop key="/showAddPerson.html">showPage</prop>
                                </props>
                                </property>
                                </bean>

                                <bean id="personController" class="com.person.controller.PersonController" >
                                <property name="personService" ref="personService" />
                                <property name="methodNameResolver" ref="methodNameResolver"/>
                                <!-- <property name="validators"><list><ref bean="personValidator"/></list></property>-->
                                </bean>

                                <bean id="urlMapping"
                                class="org.springframework.web.servlet.handler.Sim pleUrlHandlerMapping">
                                <property name="mappings">
                                <props>
                                <prop key="/addPerson.html">personController</prop>
                                <prop key="/showAddPerson.html">personController</prop>
                                </props>
                                </property>
                                </bean>


                                <bean id="viewResolver"
                                class="org.springframework.web.servlet.view.Intern alResourceViewResolver">
                                <property name="viewClass">
                                <value>org.springframework.web.servlet.view.JstlVi ew</value>
                                </property>
                                <property name="prefix">
                                <value>/WEB-INF/jsp/</value>
                                </property>
                                <property name="suffix">
                                <value>.jsp</value>
                                </property>
                                </bean>
                                </beans>

                                Comment

                                Working...
                                X