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
Related
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.
I have a rest controller returning a json list of objects. When I call method 1) it works as required.
When I need to configure serialisation to ignore certain properties in one request but not the other, I am using mixIn annotation and objectMapper. When I return the object it is in xml instead of json as before. Can anybody help? I realise I am now returning a string but if I want the same respose as 1) do I need to convert string to object and return in responseEntity as before.
1)
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ResponseEntity<List<MyObject>> search(#RequestBody SearchParams searchParams){
List<MyObject> result = myService.find(searchParams);
return new ResponseEntity<List<MyObject>(result, HttpStatus.OK);
}
returns
[
{"prop1":"val1", "prop2":"val2"},
{"prop1":"val3", "prop2":"val4"}
]
2)
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ResponseEntity<String> search(#RequestBody SearchParams searchParams){
List<MyObject> result = myService.find(searchParams);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().addMixInAnnotations(MyObject.class, MyObjectFilter.class);
String json = objectMapper.writeValueAsString(result);
return new ResponseEntity<String>(json, HttpStatus.OK);
}
returns
<data contentType="text/plain;charset=ISO-8859-1" contentLength="*"><![CDATA[
[
{"prop1":"val1", "prop2":"val2"},
{"prop1":"val3", "prop2":"val4"}
]
]]></data>
This appears in xml tab in soapui instead of json tab. Can anybdy help?
I want to build a small RESTful Service, send a PUT request with an Object of a class I created (MyObject), and getting a response with only status.
My controler:
#RestController
public class MyControler {
#RequestMapping(path = "/blabla/{id}", method = RequestMethod.PUT)
#ResponseBody
public ResponseEntity<String> putMethod (#PathVariable("id") Long id,
#RequestBody MyObject t) {
/*todo*/
return new ResponseEntity<String>(HttpStatus.OK);
}
My Test App
#SpringBootApplication
public class App {
public String httpPut(String urlStr) {
MyObject myObject = new MyObject(p,p,....);
URI url = null;
HttpEntity<MyObject> requestEntity;
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.APPLICATION_JSON);
headers.setAccept(list);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Content-Type", "application/json");
requestEntity = new HttpEntity<Transaction>(t, headers);
ResponseEntity<String> response =
rest.exchange(url, HttpMethod.PUT, requestEntity, MyObject.class);
return response.getStatusCode().getValue();
}
Im getting an HttpClientErrorException: 400 Bad Request
Where is my mistake? What I want is for Spring to automaticly serialize the MyObject. MyObject class is implementing serializable.
What do I miss?
}
Maybe you're doing to much?
Did you try to put the object as json via postman or something similar? If so what is the response?
Nevertheless i created a minimal example for consuming a service via Springs RestTemplate.
This is all needed code for getting a custom object AND putting a custom object via RestTemplate
public void doTransfer(){
String url = "http://localhost:8090/greetings";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Greeting> greeting = restTemplate.getForEntity(url, Greeting.class);
LOGGER.info(greeting.getBody().getValue());
Greeting myGreeting = new Greeting();
myGreeting.setValue("Hey ho!");
HttpEntity<Greeting> entity = new HttpEntity<Greeting>(myGreeting);
restTemplate.exchange(url, HttpMethod.PUT, entity, Greeting.class);
}
I've provided a sample project with a sender (maybe not a good name .. it is the project with the greetings endpoint) and a receiver (the project which consumes the greetings endpoint) on Github
Try to do this:
ResponseEntity<MyObject> responseSerialized =
rest.exchange(url, HttpMethod.PUT, requestEntity, MyObject.class);
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.
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 );
}