denelias
denelias

Reputation: 41

How to pass Object to ModelAttribute in controller - Spring

Is it possible to pass an object (car) to my controller by using a select tag? When i try to use the following code, the car parameter is not recognised and it results is:

400-Bad Request

A car consists of 2 Strings (Brand, Model) A spot consists of 1 car and 2 Strings (town, streetName)

My jsp page:

<form:form method="post" modelAttribute="spot" action="${post_url}">        
    <form:select path="car">   
        <form:option value="-" label="--Select car"/>  
        <form:options items="${cars}"/>
    </form:select> 

    <form:input type="text" path="town"/>        
    <form:input type="text" path="streetName"/>            
    <button>Save</button>
</form:form>

My controller:

@RequestMapping(value="/addSpot", method = RequestMethod.POST)
public String save(@ModelAttribute("spot") Spot spot){   
    service.addSpotToService(spot);      
    return "redirect:/spots.htm";
}

Upvotes: 0

Views: 1654

Answers (1)

Periklis Douvitsas
Periklis Douvitsas

Reputation: 2491

you can creta a component to convert the Long id of Car to object car

@Component
public class CarEditor extends PropertyEditorSupport {

    private @Autowired CarService carService;

    // Converts a Long to a Car
    @Override
    public void setAsText(Long id) {
        Car c = this.carService.findById(id);

        this.setValue(c);
    }

}

in your controller add this

private @Autowired CarEditor carEditor;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Car.class, this.carEditor);
    }

and then pass the id of car in the select

    <form:select path="car">   
        <form:option value="-" label="--Select car"/>  
        <form:options items="${cars}" itemValue="id" itemLabel="model"/>
    </form:select> 

have a look at the spring documentation http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html and specifically at the section The options tag

The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

Let me know if this worked for you

Upvotes: 1

Related Questions