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

  • #61
    getBindingResult

    Could you please specify where from the method getBindingResult(request, object) has come. I am getting an error while writing in my eclipse ide.
    To which API does it belong to?

    Comment


    • #62
      The following import statements are used in my controller

      The following link will demonstrate how to do validation with MultiActionController

      http://forum.springsource.org/showpo...3&postcount=49


      The following imports are used in my controller which is the subclass of MultiActionController

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

      import org.springframework.validation.BindingResult;
      import org.springframework.validation.ValidationUtils;
      import org.springframework.validation.Validator;
      import org.springframework.web.bind.ServletRequestDataBin der;
      import org.springframework.web.servlet.ModelAndView;
      import org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController;

      Comment


      • #63
        I has the same problem, please help me:
        Profile.java
        Code:
        public class Profile {
        	private String name;
        
        	public void setName(String name) {
        		this.name = name;
        	}
        
        	public String getName() {
        		return name;
        	}
        
        	@Override
        	public String toString() {
        		StringBuffer buffer = new StringBuffer();
        		buffer.append("Name: " + name + ";");
        		return buffer.toString();
        	}
        }
        ProflieController.java
        Code:
        public class ProfileController extends MultiActionController {
        	private ProfileManager profileManager;
        
        	public void setProfileManager(ProfileManager profileManager) {
        		this.profileManager = profileManager;
        	}
        
        	public ModelAndView create(HttpServletRequest request,
        			HttpServletResponse response, Profile profile) throws Exception {
        		return new ModelAndView("profileAdd");
        	}
        
        	public ModelAndView edit(HttpServletRequest request,
        			HttpServletResponse response) throws Exception {
        		Profile profile = profileManager.findByProfileName(ServletRequestUtils
        				.getRequiredStringParameter(request, "profileName"));
        		return new ModelAndView("profileEdit", "model_pfofile", profile);
        	}
        
        	public ModelAndView add(HttpServletRequest request,
        			HttpServletResponse response, Profile profile) throws Exception {
        		profileManager.add(profile);
        		return new ModelAndView("profileAdd");
        	}
        
        	public ModelAndView list(HttpServletRequest request,
        			HttpServletResponse response) throws Exception {
        		List<Profile> profiles = profileManager.getProfiles();
        		return new ModelAndView("profileList", "model_profiles", profiles);
        	}
        
        	public ModelAndView remove(HttpServletRequest request,
        			HttpServletResponse response) throws Exception {
        		String profileName = ServletRequestUtils.getRequiredStringParameter(
        				request, "profileName");
        		Profile profile = new Profile();
        		profile.setName(profileName);
        		profileManager.remove(profile);
        		return new ModelAndView("redirect:list.htm");
        	}
        }
        ProfileValidator.java
        Code:
        public class ProfileValidator implements Validator {
        
        	@Override
        	public boolean supports(Class clazz) {
        		return clazz.equals(Profile.class);
        	}
        
        	@Override
        	public void validate(Object target, Errors errors) {
        		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
        				"required.profileName", "Profile name is required.");
        
        	}
        }
        my jsp files:

        include.jsp
        Code:
         <%@ page session="false"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
        <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
        <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
        profileAdd.jsp
        Code:
        <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
        <%@ include file="/WEB-INF/jsp/include.jsp"%>
        <html>
        
        <body>
        <form:form action="add.htm" commandName="model_pfofile">
        	<spring:message code="name" />
        	<input type="text" name="name" />
        	<form:errors path="name" />
        	<input type="submit" />
        </form:form>
        </body>
        </html>
        my spring bean config:
        Code:
         	<bean id="urlMapping"
        		class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        		<property name="caseSensitive" value="true"></property>
        		<property name="order">
        			<value>0</value>
        		</property>
        	</bean>
        
        	<bean class="com.mycompany.myproj.web.ProfileController">
        		<property name="profileManager" ref="profileManager" />
        		<property name="validators">
        			<list>
        				<bean class=""com.mycompany.myproj.domain.ProfileValidator" />
        			</list>
        		</property>
        	</bean>
        When show profileAdd.jsp and I click Submit button (name of profile is empty) I get the next exception:

        org.springframework.web.bind.ServletRequestBinding Exception: Errors binding onto object 'command'; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBinding Result: 1 errors
        Field error in object 'command' on field 'name': rejected value [null]; codes [required.profileName.command.name,required.profile Name.name,required.profileName.java.lang.String,re quired.profileName]; arguments []; default message [Profile name is required.]
        org.springframework.web.bind.ServletRequestDataBin der.closeNoCatch(ServletRequestDataBinder.java:121 )
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.bind(MultiActionController.jav a:541)
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.invokeNamedMethod(MultiActionC ontroller.java:470)
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.handleRequestInternal(MultiAct ionController.java:410)
        org.springframework.web.servlet.mvc.AbstractContro ller.handleRequest(AbstractController.java:153)
        org.springframework.web.servlet.mvc.SimpleControll erHandlerAdapter.handle(SimpleControllerHandlerAda pter.java:48)
        org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:875)
        org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:807)
        org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:571)
        org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:501)
        javax.servlet.http.HttpServlet.service(HttpServlet .java:617)
        javax.servlet.http.HttpServlet.service(HttpServlet .java:717)


        root cause
        org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBinding Result: 1 errors
        Field error in object 'command' on field 'name': rejected value [null]; codes [required.profileName.command.name,required.profile Name.name,required.profileName.java.lang.String,re quired.profileName]; arguments []; default message [Profile name is required.]
        org.springframework.web.bind.ServletRequestDataBin der.closeNoCatch(ServletRequestDataBinder.java:121 )
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.bind(MultiActionController.jav a:541)
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.invokeNamedMethod(MultiActionC ontroller.java:470)
        org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.handleRequestInternal(MultiAct ionController.java:410)
        org.springframework.web.servlet.mvc.AbstractContro ller.handleRequest(AbstractController.java:153)
        org.springframework.web.servlet.mvc.SimpleControll erHandlerAdapter.handle(SimpleControllerHandlerAda pter.java:48)
        org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:875)
        org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:807)
        org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:571)
        org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:501)
        javax.servlet.http.HttpServlet.service(HttpServlet .java:617)
        javax.servlet.http.HttpServlet.service(HttpServlet .java:717)

        Comment


        • #64
          When I try your solution the empty profile name was inserted to my DB. Validaton not work:
          Code:
          public class ProfileController extends MultiActionController {
          	private ProfileManager profileManager;
          	private BindingResult errors;
          	private final Log logger = LogFactory.getLog(getClass());
          
          	public void setProfileManager(ProfileManager profileManager) {
          		this.profileManager = profileManager;
          	}
          
          	public BindingResult getErrors() {
          		return errors;
          	}
          
          	public void setErrors(BindingResult errors) {
          		this.errors = errors;
          	}
          
          	public ModelAndView create(HttpServletRequest request,
          			HttpServletResponse response) {
          		try {
          			Profile newProfile = (Profile) newCommandObject(Profile.class);
          			bind(request, newProfile);
          			validate(newProfile);
          			if (errors.hasErrors()) {
          				logger.debug("HAS ERRORS");
          				return new ModelAndView("profileAdd", errors.getModel());
          			} else {
          				return new ModelAndView("Stage3");
          			}
          		} catch (Exception expObj) {
          			logger.error(expObj);
          			return new ModelAndView("ShowException");
          		}
          	}
          
          	@Override
          	protected void bind(HttpServletRequest request, Object command)
          			throws Exception {
          		ServletRequestDataBinder binder = createBinder(request, command);
          		binder.bind(request);
          		errors = binder.getBindingResult();
          	}
          
          	public void validate(Object command) {
          		Validator[] validators = getValidators();
          		if (validators != null) {
          			for (int index = 0; index < validators.length; index++) {
          				Validator validator = validators[index];
          				if (validator instanceof ProfileValidator) {
          					if (((ProfileValidator) validator).supports(command
          							.getClass()))
          						ValidationUtils.invokeValidator(validators[index],
          								command, errors);
          				} else if (validator.supports(command.getClass()))
          					ValidationUtils.invokeValidator(validators[index], command,
          							errors);
          			}
          		}
          	}
          
          	public ModelAndView edit(HttpServletRequest request,
          			HttpServletResponse response) throws Exception {
          		Profile profile = profileManager.findByProfileName(ServletRequestUtils
          				.getRequiredStringParameter(request, "profileName"));
          		return new ModelAndView("profileEdit", "model_pfofile", profile);
          	}
          
          	public ModelAndView add(HttpServletRequest request,
          			HttpServletResponse response, Profile profile) throws Exception {
          		profileManager.add(profile);
          		return new ModelAndView("profileAdd");
          	}
          
          	public ModelAndView list(HttpServletRequest request,
          			HttpServletResponse response) throws Exception {
          		List<Profile> profiles = profileManager.getProfiles();
          		return new ModelAndView("profileList", "model_profiles", profiles);
          	}
          
          	public ModelAndView remove(HttpServletRequest request,
          			HttpServletResponse response) throws Exception {
          		String profileName = ServletRequestUtils.getRequiredStringParameter(
          				request, "profileName");
          		Profile profile = new Profile();
          		profile.setName(profileName);
          		profileManager.remove(profile);
          		return new ModelAndView("redirect:list.htm");
          	}
          }
          my profileList.jsp
          Code:
           <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
          <%@ include file="/WEB-INF/jsp/include.jsp"%>
          
          <html>
          <body>
          <h3><spring:message code="users.profiles" /></h3>
          
          <form action="create.htm"><%@ include
          	file="/WEB-INF/jsp/tableToolBar.jsp"%>
          <table border="1">
          	<tr>
          		<th><spring:message code="name" /></th>
          	</tr>
          	<c:forEach items="${model_profiles}" var="profile">
          		<tr>
          			<td>${profile.name}</td>
          			<td><a href="edit.htm?profileName=${profile.name}"><spring:message
          				code="edit" /></a></td>
          			<td><a href="remove.htm?profileName=${profile.name}"><spring:message
          				code="delete" /></a></td>
          		</tr>
          	</c:forEach>
          </table>
          </form>
          
          </body>
          </html>
          When I click submit on the profileAdd.jsp (profile name is empty) the empty string inserted to my DB. Validation not work. Why?

          Comment


          • #65
            OK, it's work. If you want validator in the MultiActionController you need in the you class controller (in this casle ProfileController):
            1. Override method bind(...)
            2. Write your own method validate(...)

            Thanks for all in this thread

            Here are all parts of the puzzle:
            Code:
            public class ProfileValidator implements Validator {
            
            	@Override
            	public boolean supports(Class clazz) {
            		return clazz.equals(Profile.class);
            	}
            
            	@Override
            	public void validate(Object target, Errors errors) {
            		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
            				"required.profileName", "Profile name is required.");
            	}
            }
            
            
             public class ProfileController extends MultiActionController {
            	private ProfileManager profileManager;
            
            	public void setProfileManager(ProfileManager profileManager) {
            		this.profileManager = profileManager;
            	}
            
            	BindingResult errors;
            
            	public BindingResult getErrors() {
            		return errors;
            	}
            
            	public void setErrors(BindingResult errors) {
            		this.errors = errors;
            	}
            
            	@Override
            	protected void bind(HttpServletRequest request, Object command)
            			throws Exception {
            		ServletRequestDataBinder binder = createBinder(request, command);
            		binder.bind(request);
            		errors = binder.getBindingResult();
            	}
            
            	public void validate(Object command) {
            		Validator[] validators = getValidators();
            		if (validators != null) {
            			for (int index = 0; index < validators.length; index++) {
            				Validator validator = validators[index];
            				if (validator instanceof ProfileValidator) {
            					if (((ProfileValidator) validator).supports(command
            							.getClass())) {
            						ValidationUtils.invokeValidator(validators[index],
            								command, errors);
            					}
            				} else if (validator.supports(command.getClass())) {
            					ValidationUtils.invokeValidator(validators[index], command,
            							errors);
            				}
            			}
            		}
            	}
            
            	public ModelAndView newProfile(HttpServletRequest request,
            			HttpServletResponse response) throws Exception {
            		return new ModelAndView("profileAdd");
            	}
            
            	public ModelAndView edit(HttpServletRequest request,
            			HttpServletResponse response) throws Exception {
            		Profile profile = profileManager.findByProfileName(ServletRequestUtils
            				.getRequiredStringParameter(request, "profileName"));
            		return new ModelAndView("profileEdit", "model_pfofile", profile);
            	}
            
            	public ModelAndView add(HttpServletRequest request,
            			HttpServletResponse response) throws Exception {
            		try {
            			Profile profile = (Profile) newCommandObject(Profile.class);
            			bind(request, profile);
            			validate(profile);
            			if (errors.hasErrors()) {
            				return new ModelAndView("profileAdd", errors.getModel());
            			}
            			profileManager.add(profile);
            			return new ModelAndView("redirect:list.htm");
            		} catch (Exception expObj) {
            			logger.info(expObj);
            			return new ModelAndView("profileAdd");
            		}
            	}
            
            	public ModelAndView list(HttpServletRequest request,
            			HttpServletResponse response) throws Exception {
            		List<Profile> profiles = profileManager.getProfiles();
            		return new ModelAndView("profileList", "model_profiles", profiles);
            	}
            
            	public ModelAndView remove(HttpServletRequest request,
            			HttpServletResponse response) throws Exception {
            		String profileName = ServletRequestUtils.getRequiredStringParameter(
            				request, "profileName");
            		Profile profile = new Profile();
            		profile.setName(profileName);
            		profileManager.remove(profile);
            		return new ModelAndView("redirect:list.htm");
            	}
            }
            profileAdd.jsp
            HTML Code:
            <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
            <%@ include file="/WEB-INF/jsp/include.jsp"%>
            <html>
            
            <body>
            <form:form action="add.htm">
            	<spring:message code="name" />
            	<input type="text" name="name" />
            	<form:errors path="name" cssClass="errorBox" />
            	<input type="submit" />
            </form:form>
            </body>
            </html>
            profileList.jsp
            HTML Code:
            <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
            <%@ include file="/WEB-INF/jsp/include.jsp"%>
            
            <html>
            <body>
            <h3><spring:message code="users.profiles" /></h3>
            
            <form action="newProfile.htm"><%@ include
            	file="/WEB-INF/jsp/tableToolBar.jsp"%>
            
            <table border="1">
            	<tr>
            		<th><spring:message code="name" /></th>
            	</tr>
            	<c:forEach items="${model_profiles}" var="profile">
            		<tr>
            			<td>${profile.name}</td>
            			<td><a href="edit.htm?profileName=${profile.name}"><spring:message
            				code="edit" /></a></td>
            			<td><a href="remove.htm?profileName=${profile.name}"><spring:message
            				code="delete" /></a></td>
            		</tr>
            	</c:forEach>
            </table>
            </form>
            
            </body>
            </html>
            In myproj-servlet.xml

            Code:
            	<bean id="urlMapping"
            		class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
            		<property name="caseSensitive" value="true"></property>
            	</bean>
            
            	<bean class="md.deeplace.sas.web.ProfileController">
            		<property name="profileManager" ref="profileManager" />
            		<property name="validators">
            			<list>
            				<bean class="com.mycompany.myproj.domain.ProfileValidator" />
            			</list>
            		</property>
            	</bean>

            Comment


            • #66
              if you metod handler has 3 parameters, then you can't call you bind method. Call only validate method.

              Code:
               	public ModelAndView add(HttpServletRequest request,
              			HttpServletResponse response, Profile profile) throws Exception {
              		try {
                                     //remove bind because you have 3 parameters
              			validate(profile);
              			if (bindingResult.hasErrors()) {
              				return new ModelAndView("profileAdd", bindingResult.getModel());
              			}
              			profileManager.add(profile);
              			return new ModelAndView("redirect:list.htm");
              		} catch (Exception expObj) {
              			logger.info(expObj);
              			return new ModelAndView("profileAdd");
              		}
              	}

              Comment


              • #67
                Originally posted by jerry.yan.mj View Post
                You can of course do validation for multiactioncontroller.

                The error you got is not from validation first of all. it is from the data binding. The data binder is not able to bind the input to the command object. Your code hasn't reached validation.

                I don't know if you really understand the multiactioncontroller or not.

                In multiactioncontroller source, this is really important to understand. what is your command object.

                // If last parameter isn't of HttpSession type, it's a command.
                if (paramTypes.length >= 3 &&
                !paramTypes[paramTypes.length - 1].equals(HttpSession.class)) {
                Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
                params.add(command);
                bind(request, command);
                }

                There is a final method invokeNamedMethod. It includes this piece of code. What it really means is the flexibility of command object of this type of controller. So, you can want to pass your command object as the 3rd parameter to your method signature: public ModelAndView newcontactHandler(HttpServletRequest request, HttpServletResponse response, Phonebook phoneBook) for example.
                OK, I pass my object as 3th parameter, but get same error. Why? If I pass 3th parameter in my method handler them MultiActionConroller must automatcally bind and validate. My method is :
                Code:
                	public ModelAndView add(HttpServletRequest request,
                			HttpServletResponse response, Profile profile) throws Exception {
                ...
                }
                and now look at the MultiActionConroller.class:

                Code:
                 	// If last parameter isn't of HttpSession type, it's a command.
                			if (paramTypes.length >= 3 &&
                					!paramTypes[paramTypes.length - 1].equals(HttpSession.class)) {
                				Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
                				params.add(command);
                				bind(request, command);
                			}
                
                protected void bind(HttpServletRequest request, Object command) throws Exception {
                		logger.debug("Binding request parameters onto MultiActionController command");
                		ServletRequestDataBinder binder = createBinder(request, command);
                		binder.bind(request);
                		if (this.validators != null) {
                			for (int i = 0; i < this.validators.length; i++) {
                				if (this.validators[i].supports(command.getClass())) {
                					ValidationUtils.invokeValidator(this.validators[i], command, binder.getBindingResult());
                				}
                			}
                		}
                		binder.closeNoCatch();
                	}
                as you can see in this code , the MultiActionController must bind and validate because my method has 3 parameters. Why then it do not do this and I get error:

                org.springframework.web.bind.ServletRequestBinding Exception: Errors binding onto object 'command'; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBinding Result: 1 errors
                Field error in object 'command' on field 'name': rejected value []; codes [required.profileName.command.name,required.profile Name.name,required.profileName.java.lang.String,re quired.profileName]; arguments []; default message [Profile name is required]
                org.springframework.web.bind.ServletRequestDataBin der.closeNoCatch(ServletRequestDataBinder.java:121 )
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.bind(MultiActionController.jav a:541)
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.invokeNamedMethod(MultiActionC ontroller.java:470)
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.handleRequestInternal(MultiAct ionController.java:410)
                org.springframework.web.servlet.mvc.AbstractContro ller.handleRequest(AbstractController.java:153)
                org.springframework.web.servlet.mvc.SimpleControll erHandlerAdapter.handle(SimpleControllerHandlerAda pter.java:48)
                org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:875)
                org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:807)
                org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:571)
                org.springframework.web.servlet.FrameworkServlet.d oPost(FrameworkServlet.java:511)
                javax.servlet.http.HttpServlet.service(HttpServlet .java:637)
                javax.servlet.http.HttpServlet.service(HttpServlet .java:717)


                root cause
                org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBinding Result: 1 errors
                Field error in object 'command' on field 'name': rejected value []; codes [required.profileName.command.name,required.profile Name.name,required.profileName.java.lang.String,re quired.profileName]; arguments []; default message [Profile name is required]
                org.springframework.web.bind.ServletRequestDataBin der.closeNoCatch(ServletRequestDataBinder.java:121 )
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.bind(MultiActionController.jav a:541)
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.invokeNamedMethod(MultiActionC ontroller.java:470)
                org.springframework.web.servlet.mvc.multiaction.Mu ltiActionController.handleRequestInternal(MultiAct ionController.java:410)
                org.springframework.web.servlet.mvc.AbstractContro ller.handleRequest(AbstractController.java:153)
                org.springframework.web.servlet.mvc.SimpleControll erHandlerAdapter.handle(SimpleControllerHandlerAda pter.java:48)
                org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:875)
                org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:807)
                org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:571)
                org.springframework.web.servlet.FrameworkServlet.d oPost(FrameworkServlet.java:511)
                javax.servlet.http.HttpServlet.service(HttpServlet .java:637)
                javax.servlet.http.HttpServlet.service(HttpServlet .java:717)

                note The full stack trace of the root cause is available in the Apache Tomcat/6.0.20 logs.

                Comment


                • #68
                  A document on Spring MVC Framework

                  Dear Friends,

                  I have prepared a document on J2EE Spring MVC Framework.

                  This document may helpful to the people who want to learn Spring Framework, specially, for beginners.

                  You can access the document from the following link

                  http://docs.google.com/fileview?id=0...OWZlZmY5&hl=en

                  http://docs.google.com/fileview?id=0...YzQyMjFi&hl=en

                  thanks & regards
                  SARAVANAN SIVAJI

                  Comment


                  • #69
                    Great post

                    This is a great post!!

                    I too faced BinderException(command doesnt exist in request attribute). I followed all the steps followed in this post but I was getting it anyways.

                    I had that Exception when the page where I have written MultiActionController is loaded, from another MultiActionController.

                    so I added mv.addObject("command",new domain.MCaseDetails()); in the previous multiactioncontroller. I know that this is a bit awkward. But it worked for me.

                    Not sure if it is the right way, But I think it will help someone..

                    Comment


                    • #70
                      Thanx

                      I have login here only to thank you guys for your discussion. It resolves my problem with binding my form. My problem was using difrent comand name I didn't now that binder binds errors to default "command" name of object. I resolve it by
                      @Override
                      protected String getCommandName(Object command) {
                      return beanName;

                      }
                      Thanks ones again

                      Comment


                      • #71
                        validation in multiaction controller

                        Hi guys I have successfully implemented validation in multiaction controller .actually i have tweaked the bind method and defined bindObject method in a super class.BaseController which extends MultiactionController.

                        protected BindException bindObject(HttpServletRequest request, Object command,
                        Validator validator) throws Exception {
                        ServletRequestDataBinder binder = createBinder(request, command);
                        binder.bind(request);

                        BindException errors = new BindException(command,getCommandName(command));
                        if(validator.supports(command.getClass())){
                        ValidationUtils.invokeValidator(validator, command, errors);
                        }
                        return errors;

                        }



                        and multiaction class extends this class and in any method for example authenticateUser method ---->

                        public ModelAndView authenticateUser(HttpServletRequest request,
                        HttpServletResponse response,Login command) throws Exception {

                        System.out.println("Authenticating user : ");
                        ModelAndView mv = new ModelAndView("welcome","command",command);
                        mv.addObject("command",command);

                        BindException errors = super.bindObject(request, command, new LoginValidator());

                        if(errors.hasErrors()) {

                        mv.addAllObjects(errors.getModel());

                        mv.setViewName("login");
                        return mv;

                        }


                        return mv;
                        }

                        Here is the bind method in multiaction controller
                        protected void bind(HttpServletRequest request, Object command) throws Exception {
                        ServletRequestDataBinder binder = createBinder(request, command);
                        binder.bind(request);

                        }

                        and in the loginValidator --

                        public void validate(Object target, Errors errors) {

                        Login login = (Login) target;


                        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", "error.not-specified", "field can not be empty");
                        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.not-specified", "field can not be empty");
                        }


                        it works fine if u have defined the properties file to show the errors in jsp using <form:errors path> and command object is Login with userId and password properties
                        Last edited by luv_spring; Jun 21st, 2011, 07:15 AM.

                        Comment


                        • #72
                          problem with based controller and some source code

                          Comment


                          • #73
                            thanks all of you. you solved my problem about Multi Action Controller. you all have a great job.

                            Thanks

                            Comment

                            Working...
                            X