Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Designing classes to populate model in spring MVC

Hi,
I want to populate data into the model from inside a controller.
Suppose there is a controller method  fetchResponse(Task task) That takes some Task object...
and returns a json TaskResponse object.

now here could be one implementation :

fetchResponse(Task task  @(RequestParam))
{

TaskResponse taskResponse = new TaskResponse(task);
return serialize taskResponse.
}

TaskResponse {

attributes.
.
.
.
TaskResponse(Task task)
{
populate attributes
}

This is one way in which all the attributes of the TaskResponse object will be filled inside the TaskResponse object which will be serialized and sent .

Please suggest any pros and cons of this aproach... Also any alternatives.

Thanks
Avatar of girionis
girionis
Flag of Greece image

Why do you need serialisation? Do you send the response to another server? Why not simply set the Task to Model itself?

model.addAttribute("taskResponse", taskResponse);

Open in new window

Avatar of Rohit Bajaj

ASKER

The spring method is @ResponseBody
And so i can just send the TaskResponse object. probably spring serializes it automatically. Its about building the TaskResponse Object and then returning it.
The main question is about the design of code.  one way is  inside the controller only i do :
TaskResponse = new TaskResponse();
taskREsponse.set(0
taskResponse.set()
some looping to populate value
taskResponse.set(value)

This pollutes the controller.
On the other hand the taskREsponse depends on task Object
So i can just do taskResponse = new TaskResponse(task);
And inside the constructor of the TaskResponse() i build up the TaskResponse object so the login for taskResponse stays inside TaskResponse.
This way the controller is not polluted with the code.
Wanted expert opions on this way the pros and cons some are cleaer..
And other alternative ways..
Thanks
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is the correct answer.