How to pass json parameters with jax-rs? - ajax

if I want to post json parameter to a url with jax-rs, how to receive the parameters in the back end and convert it into an integer array?
parameters:{"sbfIdList":[14]}
backend service(in java): I tried below , but feel no luck, I just got an empty array.
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/delete")
public String deleteSbc(#QueryParam("sbfIdList") List<Long> sbfIds,#Context HttpServletRequest request, #Context HttpServletResponse response) {
return "";
}
I request the backend service using POST method.

Related

How to map POST parameters to model object using spring MVC method

I have a form that contains a file and some other input field elements.
Submit is done as follows:
var xhrArgs = {
form: attachmentForm,
handleAs: "json",
load: dojo.hitch(this, this._uploadSuccess),
error: dojo.hitch(this, this._uploadError)
};
var deferred = dojo.io.iframe.send(xhrArgs);
On backend i have a Spring controller listening for this POST request as follows:
#RequestMapping(value="/uploadAttachment.spr", consumes = { "multipart/form-data" })
public String execute(HttpServletRequest request, HttpServletResponse response)
Everything works fine so far.
I would like now to get all request parameters (basically the POST payload) inside a POJO object.
I tried adding a #RequestBody parameter, but it fails with bad request(400):
#RequestMapping(value="/uploadAttachment.spr", consumes = { "multipart/form-data" })
public String execute(HttpServletRequest request, HttpServletResponse response,
#RequestBody AttachmentFormModel model)
I assume it fails because the payload is not in JSON format.
So my question is: what is the best way to automatically map all request parameters into a model object?
I've managed to fix this using #ModelAttribute instead of #RequestBody

Jersey get credentials from url

I have an url like this:
http://log:pass#localhost:8080/myendpoint
And Jersey endpoint:
#GET #Produces(MediaType.APPLICATION_JSON) #Path("/login")
#Consumes(MediaType.APPLICATION_JSON) public Response login(
#Context HttpHeaders headers, #QueryParam("callback") String callback)
{
}
And ideally I want to get 'log' and 'pass' in my endpoint method. How to do that in Jersey? I tried many endpint method signatures, filters, etc but it shows me
http://localhost instead of http://log:pass#localhost everywhere
How to achieve this?
Assuming that in your front end, you are sending your parameters as a json object using JSON.stringify() then back in your endpoint method. Add this as a second argument to that method signature JsonObject payload. Then you can access your query parameters within that method as follows
String log = payload.getString("log");
String pass = payload.getString("pass");
Revised Version
#Path("/login")
#GET
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response login(#Context UriInfo uriInfo, #Context HttpHeaders headers, #QueryParam("callback") String callback) {
URI requestUri = uriInfo.getRequestUri();
String authority = requestUri.getAuthority(); // authority contains what you need;
}

Spring boot/Spring MVC - How to forward a response from another request

I need a rest end point whose response is HTML. But instead of a view defined in my project, i would like to forward the HTML response from another request made inside that rest end point.
For example, my rest end point makes a http request to an internal service and returns the HTML returned from that service? Is it possible? Any thoughts?
Here is a code example
#RequestMapping("/test")
public String testMe(Model model, #RequestParam("param1") String param1, #RequestParam("param2") String param2)
{
//Make a Http call to an internal service and return the response from that call
return "<RESPONSE_FROM_THAT_CALL>";
}
I would like to return the HTML response from the internal service
You can use a RestTemplate to fetch the result from the other service and just return it as a String:
#Controller
public class MyController {
private RestTemplate restTemplate = new RestTemplate();
#ResponseBody
#RequestMapping("/test")
public String testMe(Model model, #RequestParam("param1") String param1, #RequestParam("param2") String param2) {
URI uri = UriComponentsBuilder.fromHttpUrl("http://www.example.com");
.queryParam("param1", param1)
.queryParam("param2", param2)
.build()
.toUri());
return restTemplate.getForObject(uri, String.class);
}
}
If you'll have more endpoints that you wanna proxy to another service, you should consider using e.g. Zuul as a micro proxy. See e.g. this blog post explaining how you can easily create such a proxy.

How to get the HTTP Request body content in a Spring Boot Filter?

I want to get the raw content that is posted towards a RestController. I need it to do some processing on the raw input.
How can I get the raw body content without interfering with the Filter Chain?
Here is a sample of controllerAdvice where you can access RequestBody and RequestHeader as you do in your controller. The Model attribute method is basically to add model attributes which are used across all pages or controller flow. It gets invoked before the controller methods kick in. It provides cleaner way of accessing the RESTful features rather than convoluted way.
#ControllerAdvice(annotations = RestController.class)
public class ControllerAdvisor {
#ModelAttribute
public void addAttributes(HttpServletRequest request, HttpServletResponse response,Model model, #RequestBody String requestString, #RequestHeader(value = "User-Agent") String userAgent) {
// do whatever you want to do on the request body and header.
// with request object you can get the request method and request path etc.
System.out.println("requestString" + requestString);
System.out.println("userAgent" + userAgent);
model.addAttribute("attr1", "value1");
model.addAttribute("attr2", "value2");
}
}
I use #ModelAttribute method to set value from #RequestBody.
#ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler
{
public CustomRestExceptionHandler() {
super();
}
private Object request;
#ModelAttribute
public void setRequest(#RequestBody Object request) {
this.request = request;
}
#Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
logger.info(this.request)
}
}

Using both #RequestBody and #RequestParam together in spring mvc3

I am using spring-mvc 3.1.0.RELEASE and for some reason, mapping POST with query params and request body does not work.
Here is how my controller method looks:
#RequestMapping(method = POST, value = "/post-to-me/")
public void handlePost(
#RequestBody Content content,
#RequestParam("param1") String param1,
#RequestParam("param2") String param2
){
//do stuff
}
However, if I convert all the request params to path params, mapping works. Has anyone run into something similar?
Thanks!
EDIT:
"does not work" == 404 when I try doing, POST /post-to-me?param1=x&param2=y
First, your POST url doen't match the controller method url, your POST url must be "/post-to-me/?param1=x&param2=y" not "/post-to-me?param1=x&param2=y"
Second, where did Content class come from?? I used a String and works fine for me
#RequestMapping(method = RequestMethod.POST, value = "/post-to-me/")
public void handlePost(#RequestBody String content,
#RequestParam("param1") String param1,
#RequestParam("param2") String param2, HttpServletResponse response) {
System.out.println(content);
System.out.println(param1);
System.out.println(param2);
response.setStatus(HttpServletResponse.SC_OK);
}
Note that I used HttpServletResponse to return a HTTP 200 code, but I think there is a better solution for return Http codes, check this: Multiple response http status in Spring MVC
Trailing slash at the end of your request mapping value might be the problem.
Try:
#RequestMapping(method = RequestMethod.POST, value = "/post-to-me")
or send your POST request to POST /post-to-me/?param1=x&param2=y

Resources