Multi Action Controller With Validation
Multi Action Controller With Validation
Multi Action Controller With Validation
Problem Description: A Simple Login page with two buttons, which take
user name and password as the inputs. The page has two buttons,
authenticate and login as shown below and performs validation on
click of the buttons.
Implementation:
In the web.xml we have named the servlet as spring; hence the spring
context file is required to be named as spring-servlet.xml
Step 2: Configuring the LoginController(MultiActionController) and
the LoginValidator in spring-servlet.xml
<script type="text/javascript">
function setAction(action1){
document.forms[0].methodToCall.value = action1;
document.forms[0].submit();
}
</script>
<style>
.error { color: red; }
</style>
</td>
</tr>
</table>
<br>
<input type="hidden" name="methodToCall" value="" />
</form:form>
</body>
</html>
Step 4: Creating the controller Login Controller:
package com.spring.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import
org.springframework.web.servlet.mvc.multiaction.MultiActionController
;
BindingResult errors;
@Override
protected void bind(HttpServletRequest request, Object command)
throws Exception {
// TODO Auto-generated method stub
ServletRequestDataBinder binder = createBinder(request,
command);
binder.bind(request);
errors = binder.getBindingResult();
}
PropertyConfigurator.configure("C:\\log4j.properties");
Logger logger = Logger.getLogger(BasicController.class);
return new
ModelAndView("registrationsuccess","command",login);
ValidationUtils.invokeValidator(validators[index],
command, errors);
}
} else if
(validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validators[index], command,
errors);
}
}
}
}
Explaination:
This method will just route the request to the view to the login.jsp
when we access the url
http://localhost::8080/<ContextName>/login.htm (login.htm is
resolved as login.jsp by the resolver)
For the validation in MultiActionController unlike SimpleFormController we need to override the bind
and the validate methods in the controller
For the errors to appear on the login page back we need to set the errors to the request object as shown
below
Running the complete example
Press on Authenticate as the user id is different from 12345 which is given in the Validator, error would
be thrown
Step6: Success Page
If the input is given as 12345 it would be successfully redirected to the next page
Thank You,
Santosh Kothapalli SCWCD