aditya
aditya

Reputation: 495

Passing an object from JSP to Spring controller

I created a class named Person. Then I pass an object of this class via Spring controller to JSP page, say abc.htm.

Now I want it to transfer back from abc.htm to another controller. How could I do that?

Also tell me if any other class object (say Address class object) uses that person object as parameter, then how would I pass that Address class object to the controller.

I am very confused, please help me.

Upvotes: 2

Views: 10690

Answers (1)

Bozho
Bozho

Reputation: 597106

After the page is rendered you are no longer in the "Java realm", so you don't have your objects. You can rebuild them based on the parameters that are sent back in the next request.

This is called "binding". In Spring MVC this is done automatically (more or less) if you are using the <form:x> tags. Then in your controller your objects will be accessible as method attributes:

@RequestMapping(..)
public String foo(YourObject object) {..}

You might need a @ModelAttribute annotation if the name of your param and the one in the JSP are not the same. The MVC docs write:

Command or form objects to bind parameters to: as bean properties or fields, with customizable type conversion, depending on @InitBinder methods and/or the HandlerAdapter configuration. See the webBindingInitializer property on AnnotationMethodHandlerAdapter. Such command objects along with their validation results will be exposed as model attributes by default, using the non-qualified command class name in property notation. For example, "orderAddress" for type "mypackage.OrderAddress". Specify a parameter-level ModelAttribute annotation for declaring a specific model attribute name.

I'd suggest you review the PetClinic Sample Application to see how this works in practice.

Upvotes: 1

Related Questions