Springboot RestControler multiple produces - spring-boot

I have one method in my RestController that produces 2 types of return
#PostMapping(value = {"myUrl"}, produces = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
So when are everything ok. the method return the multipart_form but when I got some validation error, I need to return that error in a JSON type.
It`s possible to make this? in my requet (with postman) if I insert in Accept header /, when I got error the return are 406 not acceptable(and not the json), but if I put application/json he return my succes in a Json too :(
It`s possible to return 2 dif produces in one request? how
tks

Related

POST request response being sent in weird format

I intend to send my server response in the following format
Api Doc
I did the following
headersR.add("response_code", "OK");
headersR.add("cmd_code", "SET_FK_NAME");
headersR.add("trans_id", Long.toString(System.currentTimeMillis()/1000000));
JSONPObject map1 = new JSONPObject("fk_name", "jj");
return new ResponseEntity<>(map1, headersR, HttpStatus.OK);
I was getting a negative response from the other side so I checked Wireshark(Had a hard time logging my response body). And I got this in Wireshark.
Wirehark Screenshot
The response body is Definitely not JSON.
How can I fix this?
The response body fk_name("jj") is not JSON, it's JSONP -- Browser would take the function name fk_name and try to execute it with "jj" as parameter.
The root cause is you are using JSONPObject, whose constructor accepts 2 parameters: a function name, and the data value. Not the expected JSON key and value.
To fix this issue and return {"fk_name":"jj"}, remove the JSONPObject stuff and use code as follow:
return new ResponseEntity<>("{\"fk_name\":\"jj\"}", headersR, HttpStatus.OK);

Request method is always same when endpoint called using Postman

Using POSTMANto call an endpoint for example:
http://localhost/v1
Checking Request Method in the code using:
context.getRequest().getMethod()
No matter what I change request method in postman request, I always get the first request method I select let say GET.
When i change request to
http://localhost/v1/
It works and start sending correct request methods i select in POSTMAN
http://localhost/v1
I am expecting that when I call:
http://localhost/v1
or
http://localhost/v1/
It should behave same way.
Any explanation to point to the right direction would be appreciated
you need to redirect /v1 to /v1/ try like
#RequestMapping(value="/v1")
public ModelAndView redirectToPage() {
return new ModelAndView("redirect:/v1/");
}

Different response from a controller method based on HTTP Response code

How do you write a controller method which can either return a View or HTTP response status code based on if its 200 then view else the response status code.
#RequestMapping(value="/",method=RequestMethod.GET)
public String showLanding()
{
return View.Landing;
}
I want to handle in case of 401, 403, 500 etc. just status code should be returned instead of view.
To return the 403- Unauthorized status code,
#RequestMapping(value="/",method=RequestMethod.GET)
public String showLanding()
{
return HttpStatus.UNAUTHORIZED;
}
See this:
http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/http/HttpStatus.html?is-external=true
How to respond with HTTP 400 error in a Spring MVC #ResponseBody method returning String?
You could also check out the #ResponseStatus annotation as well as ResponseEntity (for more dynamic scenarios)
I'm far from suggesting that you should do flow control with Exceptions - but those HTTP statuses are errors and exceptions. So you might want to throw business exceptions from your controller methods and then handle those using #ExceptionHandlers.
You can also target a subset of Controllers and assist those with Exception handling using #ControllerAdvice.

Spring mvc controller null return handler

#RequestMapping(method = RequestMethod.GET)
#ResponseBody
public List<Country> getListOfCountries() {
return countryService.listAll();
}
It displays a json view of the object but if the service return null, then I want to display an error message, Any suggestions pls?
First of all, even if this does not directly answer the question, your objects should never ever return null instead of empty collections - you can find the reasoning in Effective Java 2nd Edition, Item 43 / p.201
So, if the situation when no countries were found is normal it must be processed by the client JS code that will check the count and display the respective message.
If something has gone wrong you can throw an exception(as Biju has pointed out +1) - I believe that it's the service who should throw the exception because it knows the reason why it happened, and not to return null anyway.
I'd like to add that in Spring 3.2(in pre Spring 3.2 returning response body is complicated) you can set an #ExceptionHandler that will both return JSON and set the HTTP status code which can be later processed by the client. I think that returning a custom JSON response with some error code is most optimal here.
#RequestMapping("/test")
#ResponseBody
public List<Country> getListOfCountries() {
//assuming that your service throws new NoCountriesFoundException();
//when something goes wrong
return countryService.listAll();
}
#ExceptionHandler(NoCountriesFoundException.class)
ResponseEntity<String> test() {
return new ResponseEntity<String>(
"We are sorry, our server does not know any countries yet.",
HttpStatus.I_AM_A_TEAPOT );
}
Then in the JS code, you can do specific processing depending on the returned status code.
Also, to avoid declaration of the same #ExceptionHandler in different controllers, in Spring 3.2 you can put #ExceptionHandler inside a #ControllerAdvice annotated class.
For details, see http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers and http://www.springsource.org/node/3738 for 3.2 specific things
You have a couple of options I think:
If you return a null back, it will be returned as an empty string "", you can probably look for that and handle it.
Return a wrapper type on top of your list, this way if the wrapped list is null something like this will be returned back to the client {"countries":null} which can be more easily handled at the javascript end.
Throw an exception, which will propagate as a 500 status code back to the client, you can then have an error handler on the javascript side to handle this scenario.

MVC 3 + REST return custom http error?

In my application I am trying to get it so that when a REST api call is made, if there is an error that it return a proper status code then either Json or Xml in the body of the response.
So 400: { 'ErrorCode': '400', 'Reason' : 'You did something wrong..' }
or 400: <Error><ErrorCode>400</ErrorCode><Reason>You did something wrong</Reason></Error>
However I can't seem to find how to set the status and body to make this happen. Using fiddler inspect whats being passed back and fourth I've found that if I return a normal ActionResult then I can return the body message ok but the status is 200. If I use HttpException then I can set the status code but the body message is returned as a large html document. I've tried using HttpStatusCodeResult but that just seems to fail and return a 302.
I'm a bit stumped.
Try Response.StatusCode = (int)HttpStatusCode.BadRequest; in your action method. Check out this article at develoq for a short tutorial: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/
Web API can handle this in various ways, but if you want to stick to ASP.NET MVC then use the code below:
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return Content("Error description goes here.", "text/plain");
Check out MVC 4 Beta, there is a new feature called Web API that will help you solve this issue.

Resources