Using spring and hibernate. How can I also send the messages in model too, with the response of that ajax method? I mean whats a better and most practiced way. Any sample code for the three said cases?:
1 returning String
@RequestMapping (value = "/task/delete/{taskId}", method=RequestMethod.GET)
public @ResponseBody String deleteTask(ModelMap model,
@PathVariable(value="taskId") String taskId
){
result = taskService.deleteTask(Long.parseLong(taskId));
if (result.getIsSuccessful()) {
model.put("successMessages", result.getMessageList());
System.out.println("task deleted ------------------");
return "success";//queued - send model message also (if needed)
}else{
System.out.println("task deletion failed ---------------");
model.put("errorMessages", result.getMessageList());
return "failure";//queued - send model message also (if needed)
}
}
2 returning null (no return object required)
@RequestMapping (value = "/attachment/download/{attachmentId}", method=RequestMethod.GET)
public String downloadFile( HttpServletResponse response,
@PathVariable(value = "attachmentId")Long attachmentId
)throws IOException{
result = taskService.getAttachmentById(attachmentId);
if(result.getIsSuccessful()){
Attachment attachment = (Attachment)result.getObject();
File file = new File(attachment.getPath());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
byte[] ba = FileUtils.readFileToByteArray(file);
response.getOutputStream().write(ba);
}
return null;
//queued - send model message also (if needed)
}
3 returning a full object.
@RequestMapping (value = "/task/create/{parentBoxId}/{taskTitle}/{taskDescription}", method=RequestMethod.GET)
public @ResponseBody Tasks createTask(ModelMap model,
@PathVariable(value="parentBoxId") String parentBoxId,
@PathVariable(value="taskTitle") String taskTitle,
@PathVariable(value="taskDescription") String taskDescription
){
Tasks taskToBeReturned = null;
Tasks task = new Tasks();
task.setTitle(taskTitle);
task.setDescription(taskDescription);
Boxes parentBox = (Boxes)( boxService.getBoxById(Long.valueOf(parentBoxId)) ).getObject();
taskService.setParent(task, parentBox);
result = taskService.save(task);
if(result.getIsSuccessful()){
model.put("successMessages", result.getMessageList());
Tasks savedTask = (Tasks)result.getObject();
System.out.println("box saved title was " + savedTask.getTitle());
taskToBeReturned = new Tasks();
taskToBeReturned.setTitle(savedTask.getTitle());
taskToBeReturned.setId(savedTask.getId());
taskToBeReturned.setDescription(savedTask.getDescription());
}else{
model.put("errorMessages", result.getMessageList());
}
return taskToBeReturned; //queued - send model message also (if needed)
}