Spring MVC Form Not Submitting Value

1.2k Views Asked by At

Resolution

I've now managed to get this working.

It was my own oversight that was causing the null result, and thanks to @WillKeeling for pointing out that I was mapping the form to the wrong controller method.

Rather than creating a new Role object for the form to submit, I was (for an unknown reason) asking it to submit a User object.

My working JSP & Controller below:

<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="newRole">
    <div class="input-group">
        <span class="input-group-addon">Roles</span>
        <form:select class="form-control" path="rolename" multiple="false">
            <form:options items="${roles}" title="rolename" itemValue="rolename" itemLabel="rolename" />
        </form:select>
        <span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
    </div>
</form:form>

Controller Mapping

@RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(@ModelAttribute("newRole") Role  newRole, @PathVariable("username") String username) {
    System.out.println(newRole.getRolename());
    return "redirect:/users/" + username;
}

Original Question

I may be missing something obvious here but I was hoping someone may be able to help.

I'm building an access management system for the team I work in. I've got a form on a jsp (code below) which should submit a new "role" object that can be handled into the repository in the back end.

At the moment however, when I click submit the logging reports that the value is "null". Can somebody please shed some light on why this is?

Form in JSP

<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="user">
    <div class="input-group">
        <span class="input-group-addon">Roles</span>
        <form:select class="form-control" path="roles" multiple="false">
            <form:options items="${roles}" title="roles" itemValue="rolename" itemLabel="rolename" />
        </form:select>
        <span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
    </div>
</form:form>

Controller

Original path is /users with the following controller.

@RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(@ModelAttribute("user") User user) {
    System.out.println(user.getRoles());
    return "redirect:/users/" + user.getUsername();
}

Result in Console

Role [rolename=null]
0

There are 0 best solutions below