java – How to pass your object from jsp to controller

Question:

I have a User , in it there is a link to the Role , and for example, on the editUser page editUser I need to collect a User object in a spring MVC controller (I add User user to the controller parameters), such objects as name(String) , email(String) , age(int) are collected in User normally, and in order to add Role there, I need to get the edited User out of the database, extract its role and assign it to a new User object, and only then do update in hibernate .

So the question is, is it possible to collect User together with Role from the jsp page somehow by spring?

I tried to specify the field in the layout

input type="hidden" name="role" value"${user.role}"

but then the controller does not find at all and redirects to page 400.

PS I add User from the get-controller to jsp, that is, the User variables can be obtained in jsp

Answer:

For me, this is not possible at the client level.

Alternatively, you need to first send the id of the desired object with a request, and then use the id to get it.

I would do it like this

html

...
<form:form modelAttribute("user") action="..." method="post">
...
<input hidden name="id" value="${user.role.id}">
...
<button>SEND</button>
</form:form>
...

Inside method *

.........@ModelAttribute("user") User user, @RequestParam("id") Integer id) {
....
Role role = (Role) session.createQuery("from Role role where role.id=:id").setParameter("id", id).list().get(0);
user.setRole(role);
....
}
Scroll to Top