Return "View" inside "Json" with Spring MVC - json

I'm using Spring MVC, and I need return in the Controller, a Json object that contains the view, by example, the related jsp page.
return: { name: "fragment-form", other-info:"other-info", view: view}
where "view" should be the JSP page linked to your ModelAndView
I read other post, but I not find the solution, because I need that controller to the work, if it's posible.
Sugestions?
EDIT:
I have a form with your values, and the submit, from javascript execute this follow code:
#RequestMapping(method = RequestMethod.POST)
public Object create(#Valid #RequestBody PatientForm form, HttpServletResponse response) {
ModelMap map = new ModelMap();
map.put("form", form);
return new ModelAndView("addPatientForm", map);
}
I need return a Json where the "ModelAndView("addPatientForm", map)" processed within the json that is returned.

Would something like this work for you:
#RequestMapping(value="/somepage", method=RequestMethod.POST)
public ResponseEntity<String> generateViewasJSON(){
JSONObject json = new JSONObject();
json.put("name","fragment-form");
...
HttpHeaders headers = new HttpHeaders();
headers.set( "Content-Type", "application/json" );
return new ResponseEntity<String>( json.toString(), headers, HttpStatus.OK );
}

Related

Send Json Object to Spring Controller

Hy guys.
I have this js code, where I create an object to send to a Spring controller via Ajax function:
$('#eventsdatageneral').on('click', '.btn.btn-info', function(event)
{
var today_date = new Date().getTime();
var dataToSend = new Object();
dataToSend.dateToSend = today_date;
dataToSend.nameToSend = host_name;
dataToSend.typeToSend = type_name;
console.log(dataToSend);
event.preventDefault();
//here starts the code to sending data to Spring controller
$.ajax({
url: "../todaydatarecover.json",
type: "post",
data: dataToSend,
success : function() {
console.log("Invio riuscito.");
//console.log(moment(today_date).format('DD/MM/YYYY'));
}
});
});
This is the controller:
#PostMapping(value="/todaydatarecover.json")
#ResponseBody
public ModelAndView todayInfoAndIdRecover(ModelAndView model, HttpServletRequest request,
#RequestParam(name="dateToSend", required=false) long dateInBox,
#RequestParam(name="nameToSend", required=false) String nameInBox,
#RequestParam(name="typeToSend", required=false) String typeInBox) throws IOException
{
//First of all, we invoke getinfo methods to take info and id
Timestamp date = new Timestamp(dateInBox);
Events event = networks.getInfoandId(nameInBox, typeInBox, date);
//Second, we put this list in the model and set properties for jquery datatables
model.addObject("data", event);
//Verify id and info
System.out.println("The info is: " + event.getInfo());
System.out.println("The id is: " + event.getId());
//Finally, we return the model
return model;
}
When I try to execute, i got an org.springframework.dao.EmptyResultDataAccessExceptionIncorrect result size: expected 1, actual 0; but, if I query the DB via MySQL client, i can take the correct result without problems. So, there is a row that match the query I perform; this make me think that the problem is how I create the Json Object and/or I send it to Controller.
What's my error?
When sending informations with data, it's in the request's body, you can't retrieve your data with #RequestParam. You need to use #RequestBody and create and object with your three variables.
Example :
#PostMapping(value="/todaydatarecover.json")
#ResponseBody
public ModelAndView todayInfoAndIdRecover(#RequestBody TodayData todayData, ModelAndView model, HttpServletRequest request) throws IOException
{

Springboot Thymeleaf Cache page

I implement a client application. This application consume a Rest webservice and these service return and html page as a variable in a model.
I take these html page successfully from Rest Service and try to write to a blank html page.
My code to write html page.
public void writeToHtml(ResponseModel response) {
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(src/main/resources/templates/test.html);
writer = new BufferedWriter(fWriter);
writer.write(response.getHtmlPage());
writer.newLine();
writer.close();
} catch (Exception e) {
}
}
These function can take htmlPage from ResponseModel and write successfully to test.html
Untill there everthing work properly and my controller display it on secreen.
However, if I again call same Rest service, it can again write to "test.html" but, on the screen it shows the first created html page.
Probably it cache the first html and if I rewrite again. I just take cache one.
My Controller
#RequestMapping(value = "/testPath", method = RequestMethod.POST)
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {
RestTemplate restTemplate = new RestTemplate();
ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
writeToHtml(response);
return "test";
}
Could you help me to solve these issue ?
IDEA : Inteliji
I solved my problem a bit differently:
#RequestMapping(value = "/testPath", method = RequestMethod.POST, produces = "text/html")
#ResponseBody
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {
RestTemplate restTemplate = new RestTemplate();
ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
writeToHtml(response);
return response.getHtmlPage();
}
So I don't need to create an HTML page.

make mvc controller return text instead of json

I am trying to make method Spring MVC method in controller to return text instead of json.
My current method looks like this
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
public ModelAndView uploadFile(#RequestParam("file") MultipartFile file) {
LOGGER.debug("Attempt to upload file with template.");
try {
String fileContent = FileProcessUtils.processFileUploading(file);
return createSuccessResponse(fileContent);
} catch (UtilityException e) {
LOGGER.error("Failed to process file.", e.getWrappedException());
return createResponse(INTERNAL_ERROR_CODE, e.getMessage());
}
}
But the response header content-type: application/json.
I was trying to pass HttpServletResponse to controller and set content type but it still continued to return json.
What's the problem?
What's FileProcessUtils? Google doesn't bring up anything. Is it a class created by you or your organization? It would appear that the method is returning a response with a content-type of application/json. What were you expecting it to return and why? You would have to somehow parse the json to extract the data necessary for constructing a ModelAndView or find another method that returns what you want.
But without more information on FileProcessUtils, it isn't possible to provide more of an answer.
You can either do this:
#RequestMapping(value = "/foo", method = RequestMethod.GET)
public ResponseEntity foo() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
return ResponseEntity.ok().headers(headers).body("response");
}
or do this:
#RequestMapping(value = "/foo", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
Both works fine.

How to send JSON in Spring?

I tried to find how I can write in Spring to POST JSON from REST client. For example, I wrote:
#RequestMapping(value = "/{userId}/add", method = RequestMethod.POST, headers = {"content-type=application/json"})
#ResponseBody
public Map<String, String> saveUser(#RequestBody User user, BindingResult result) {
Map<String, String> jsonResponse = new HashMap<String, String>();
if (result.hasErrors()) {
jsonResponse.put("Message", "Can't add the user");
jsonResponse.put("Code", "401");
return jsonResponse;
}
userService.addUser(user);
jsonResponse.put("Message", "Success add User");
jsonResponse.put("Code", "200");
return jsonResponse;
}
End tested it from Firefox REST client. But I saw 404 error. What am I doing wrong? Thanx for help.
First, if the URI of your request ended with "/user/2/add", it won't map to your method, which is mapped as "/{userId}/add". This will cause the HTTP 404 error you receive. Instead, your URI should end with "/2/add", if the "userId" is 2.
Second, annotating the User parameter with #RequestBody is not enough for the complex User type. You will need to convert your JSON request body into a User object. You can accomplish this with the MappingJacksonHttpMessageConverter. By declaring a bean of this type, you can use Jackson's annotations to control how the JSON is parsed into the User properties.

spring mvc rest mongo dbobject response

i want to create a spring mvc rest call and the response should be the results from the mongo db (Basic)DBObject. the DBObject is, as far as i know, a JSON object. is it possible to return this objects or should i return the normal string content of them?
this is the solution i have so far:
#RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
public ResponseEntity<String> getContentByIdsAsJSON(#PathVariable("ids") String ids)
{
String content = null;
StringBuilder builder = new StringBuilder();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
List<String> list = this.contentService.findContentByListingIdAsJSON(ids);
if (list.isEmpty())
{
content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data found</error>";
return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}
for (String json : list)
{
builder.append(json + "\n");
}
content = builder.toString();
return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}
does anyone have a better solution for that requirement?
thx very much in advance.
simon
I'm see a strange thing in you code. Do you must return json or xml? If you must return json it's simple in your situation, #ResponseBody do the magic
#RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
#ResponseBody
public MyGreatContentObject getContentByIdsAsJSON(#PathVariable("ids") String ids) {
return this.contentService.findContentByListingId(ids);
}
in any way, i'm think you still must learn base concepts a little more