Spring not reading model attributes from form submission - spring

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)

Related

Thymeleaf input type="date" can not display and update

I can't find the right way to display the "birthday" field from datbase!
Even when i try to submit the new value to db, it doesn't work. What i'm doing wrong?
Here is my code:
Controller
#RequestMapping(value = {"/settings"}, method = RequestMethod.GET)
public ModelAndView settings() {
ModelAndView model = new ModelAndView();
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
#RequestMapping(value = {"/settings"}, method = RequestMethod.POST)
public ModelAndView updateUserGeneralSettings(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
userService.update(user);
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
HTML
<form method="POST" th:action="#{/settings}" th:object="${user}">
<div>
</div>
...
...
<div class="costum-field">
<label for="dateOfBirth" th:text="#{field.dateOfBirth}"></label>
<input type="date" id="dateOfBirth" class="form-control" th:field="*{dateOfBirth}"/>
</div>
...
...
<div>
</div>
</form
View in browser
So, as you can see all fields are working properly. Please suggest what is my mistake.

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

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">

How to Set Form Bean before it goes to JSP page

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.

Resources