How to Set Form Bean before it goes to JSP page - spring

I am an absolute beginner. So please bear with me if I miss the obvious.
Environment I am using: Spring Portlet MVC (3.0), Liferay 6.0.6
I have a controller, a form bean and a JSP page.
I am able to successfully submit a form and get the form bean by using the below code. However I am stuck on how to preload some values into my form bean before the bean is forwarded to JSP. Can somebody point out the right direction:
My Controller:
#ActionMapping(params = "spring_action=resetPasswordViewAction")
protected void resetPasswordAction(ActionRequest actionRequest, Map<String, Object> model, ActionResponse actionResponse, #RequestParam String customerId, #RequestParam String userName) {
model.put("customerId", customerId);//Preload form bean value with this
model.put("userName", userName);//Preload form bean value with this
actionResponse.setRenderParameter("spring_render", "resetPasswordView");
}
#RenderMapping(params = "spring_render=resetPasswordView")
protected ModelAndView resetPasswordView(RenderRequest renderRequest, Map<String, Object> model) {
return new ModelAndView("resetPassword", model);
}
#ActionMapping(params = "spring_action=resetPasswordUpdateAction")
protected void resetPasswordUpdateAction(ActionRequest actionRequest, Map<String, Object> model, ActionResponse actionResponse, final ResetPassword resetPasswordCriteria) {
LOG.info(resetPasswordCriteria.toString());// Form values are retrieved successfully
actionResponse.setRenderParameter("spring_render", "resetPasswordView");
}
#ModelAttribute("resetPasswordCriteria")
public ResetPassword getResetPasswordCriteria() {
return new ResetPassword();
}
My JSP Page:
<form:form id="resetPasswordForm" name="resetPasswordForm" commandName="resetPasswordCriteria" method="post" action="${resetPasswordUpdateActionURL}">
<form:label path="customerId" /><!--Preload this field value-->
<form:label path="userName" /><!--Preload this field value-->
<form:password path="password" />
<form:password path="confirmPassword" />
<input type="submit" value="Submit" />
</form:form>
Form Bean:
public class ResetPassword {
private String customerId = "";
private String userName = "";
private String password = "";
private String confirmPassword = "";
//Getters Setters
}

In your rendering method resetPasswordView, place an object named resetPasswordCriteria (your commandName in jsp) of type ResetPassword to the model.

Related

Spring not reading model attributes from form submission

In my current spring-boot project, I have this form:
<form class="form-container" id="form" method="post" th:object="${command}" th:action="#{/usuario/register}">
...
<div class="form-row">
<div class="col-25">
<label for="login">Login</label>
</div>
<div class="col-75">
<input type="text" id="login" th:field="*{username}" placeholder="Login">
</div>
</div>
...
</form>
which is handled by this spring controller:
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#Valid Usuario object, BindingResult result) throws Exception {
this.serv.register(object);
}
my problem is that object is getting a null value, not allowing the program to persist the data. Displaying the content for both variables object and result, they show null; but if I try display the parameter's value with:
System.out.println("result.model.username: "+result.getModel().get("username"));
the correct value is shown. What's the issue here, why #Valid Usuario object, BindingResult result get me a null value, but HttpServletRequest gets the correct values?
UPDATE
Based on the sugestion below, I try this:
#ModelAttribute(value = "usuario")
public Usuario newEntity()
{
return new Usuario();
}
#RequestMapping(value = "/register", method=RequestMethod.GET)
public String formRegister(Model model) {
model.addAttribute("command", newEntity());
return "register";
}
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#ModelAttribute("usuario") Usuario object) throws Exception {
this.serv.register(object);
}
But got the same problem.
I managed to solve this issue changing the parameter:
#ModelAttribute("usuario") Usuario object
to:
#ModelAttribute("command") Usuario object
following the suggestion in the comment above (from M.Deinum)

Args with Spring MVC

I need help to pars args in a method inside my controller.
i have a form for sending my parameter to function
<form method="post" action="/">
<input type="text" id="query" placeholder="file to search ...">
<input type="submit" id="submit" value="fetch!">
</form>
and in my controller :
#RestController
public class mainController {
#RequestMapping(value = "/index", method = RequestMethod.POST)
public String index(Model model) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
model.addAttribute("query");
String res = drive.checkFile("query");
return res;
the query is a string send via the form. and return res in the same view.
Do you have any tips?
thanks you very mutch
In Spring MVC It will be like this:
#Controller
public class mainController {
#PostMapping( "/index")
public String index(#ModelAttribute FormDataObjectClass object) throws IOException, GeneralSecurityException {
DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
//model.addAttribute("query");
String name = object.getName();
String address = object.getAddress();
String res = drive.checkFile("query");
return res;
}
Here no need of passing Model as argument as we need a custom Object(FormDataObjectClass) to be used.
Create a class FormDataObjectClass as per you data in HTML form/JQuery post method

Getting CommandBean or form bean object with out #ModelAttribute in spring mvc

I have a requirement of getting commandbean or form bean object into the controller without using #ModelAttribute either from ModelMap or HttpServletRequest or anything else.
My code is:
JSP:
<form:form commandName="user" method="POST"
action="${pageContext.request.contextPath}/user/createUser">
Name:<form:input path="name" />
Password:<form:input path="password" />
<input type="submit"/>
</form:form>
Controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
modelMap.addAttribute("user", new User());
return "userRegistration";
}
#RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user=(User)model.get("user");// Retruns null
//Tried using request object but user object is not available in it.
return "message";
}
}
I tried different ways but nothing worked out.
You can implement a HandlerMethodArgumentResolver to create the bean manually, then (for example) use a WebMvcConfigurerAdapter to declare it. The argument resolvers supportsParameter method should check the expected type of the parameter. After that you can add a parameter in your Controller that is of the desired type.
You can do it by hand like you would do if you did not know the magic of Spring : just the the HttpServletRequest and gets its parameters to feed your User. It could look like :
#RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user= new User();
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name != null) {
user.setName(name);
}
if (password!= null) {
user.setPassword(password);
}
model.addAttribute("user", user);
//Tried using request object but user object is not available in it.
return "message";
}
Or in a more terse way : user.setName(request.getParameter("name");

Neither BindingResult nor plain target object for bean name 'loginuser' available as request attribute

#Controller
#RequestMapping("Page/Login.do")
public class HomeController
{
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req,BindingResult result) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
return "Login";
}
}
Above code is ##HomeController.java##
loginuser.java
package Com.Site.Name.Order;
public class loginuser
{
private String Loginn;
public String getLoginn()
{
System.out.println("hi i m in login get");
return Loginn;
}
public void setLoginn(String loginn)
{
System.out.println("I m in Loin set");
Loginn = loginn;
}
}
My JSP PAGE IS
Login.jsp
<form:form action="Login.do" method="post" commandName="loginuser">
<div id="Getin">
<img alt="" src="Image/loginttt.png">
</div>
<div id="login">
</div>
<form:input path="Loginn"/>
<input type="submit" value="LOGIN"/>
</form:form>
You are trying to use a Model attribute (commandName) but there is no such attribute added to the model or request attributes. You need to add it. Also, the BindingResult in your handler makes no sense. Remove it.
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req, Model model) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
model.addAttribute("loginuser", lu);
return "Login";
}
The Model attributes are added to the request attributes and are therefore available in the jsp.

Spring MVC Form Validation - The request sent by the client was syntactically incorrect

I am trying to add form validations to a working application. I started by adding a NotNull check to Login Form. I am using Hibernate impl of Bean Validation api.
Here's the code I have written
#Controller
#RequestMapping(value="/login")
#Scope("request")
public class LoginController {
#Autowired
private CommonService commonService;
#Autowired
private SiteUser siteUser;
#InitBinder
private void dateBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
}
#ModelAttribute
protected ModelMap setupForm(ModelMap modelMap) {
modelMap.addAttribute("siteUser", siteUser);
return modelMap;
}
#RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView form(ModelMap map){
if (siteUser.getId() == null){
map.addAttribute("command",new SiteUser());
return new ModelAndView("login-form",map);
}else {
return new ModelAndView("redirect:/my-dashboard/"+siteUser.getId());
}
}
#RequestMapping(value="/submit", method=RequestMethod.POST)
public ModelAndView submit(#Valid SiteUser user, ModelMap map, BindingResult result){
if (result.hasErrors()) {
map.addAttribute("command", user);
System.out.println("Login Error block");
return new ModelAndView("login/form",map);
}
else {
User loggedInUser = commonService.login(user.getEmail(), user.getPassword());
if (loggedInUser != null) {
siteUser.setId(loggedInUser.getId());
siteUser.setName(loggedInUser.getName());
System.out.println("site user attr set");
}
return new ModelAndView("redirect:/my-dashboard/"+loggedInUser.getId());
}
}
}
The Model is
#Component
#Scope("session")
public class SiteUser {
private Integer id = null;
#NotNull
private String name = null;
private String email = null;
private String password = null;
private List<String> displayPrivList = null;
private List<String> functionPrivList = null;
// And the getters and setters
}
The JSP is
<c:url var="loginSubmitUrl" value="/login/submit"/>
<form:form method="POST" action="${loginSubmitUrl}">
<form:errors path="*" />
<div class="row">
<div class="span4">
</div>
<div class="span4">
<h3>Please Login</h3>
<label><span style="color:red">*</span>Email</Label><form:input path="email" type="text" class="input-medium" />
<label><span style="color:red">*</span>Password</Label><form:input path="password" type="password" class="input-medium" />
<br/>
<button type="submit" class="btn btn-primary">Login</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form:form>
I have added messages.properties and the annotation driven bean def in the context xml.
Other answers on the subject talk about form fields not getting posted. In my case, that's the expected behavior - that if I submit a blank form, I should get an error.
Please advise what am I missing?
I think this question had the same issue as yours
Syntactically incorrect request sent upon submitting form with invalid data in Spring MVC (which uses hibernate Validator)
which just points out
You have to modify the order of your arguments. Put the BindingResult result parameter always directly after the parameter with the #Value annotation
You need this: <form:errors path="email" cssClass="errors" />
Use the tag form:errors for each input with the same "path" name.
It is also possible to list all the error at the same time if you don't put a path.
Here, check an full example with sample code that you can download to learn how to do:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/
Can you try changing the <form:form> by including the commandName to it like this
<form:form method="POST" action="${loginSubmitUrl}" commandName="user">

Resources