I need to pass two #RequestBody parameters into my REST API POST method. How can I achieve this and can I do it using DefaultHttpClient? - spring

My REST API method is:
#RequestMapping(value = "/api/test/summary", method = RequestMethod.POST)
postSummaryData(#RequestBody String one, #RequestBody String two) { ... }

#RequestMapping(value = "/api/test/summary/{one}/{two}", method = RequestMethod.POST) postSummaryData( #RequestParam String one, #RequestParam String two) {
}
Also you can try below:
#RequestMapping(value = "/api/test/summary", method = RequestMethod.POST) postSummaryData() {
RequestAttributes attr = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes)attr).getRequest();
// you can get param from this request
}

Related

#PathVariable with slashes in middle of RequestMapping URL

I have a Spring controller mapping like following:
#RequestMapping(value = "api/{pathVar1}/receipt", method = RequestMethod.POST)
#ResponseBody
public String generateReceipt(HttpServletRequest request, #PathVariable String pathVar1) {
....
}
In this case what if the pathVar1 has slash('/').
Example request:
'api/CODE/1/receipt'
pathVar1 is supplied with
'CODE/1'
.
I guess it's not the cleanest solution, but it seems to be working:
Replace #PathVariable in API path with ** to accept anything between "api/" and "/receipt", and then extract the needed part of path.
#RequestMapping(value = "api/**/receipt", method = RequestMethod.POST)
#ResponseBody
public String generateReceipt(HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String apiPath = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
String neededPathVariableValue = apiPath.substring(0, apiPath.length() - "/receipt".length());
//...
}

How to get a param from URL Rest Service that is after a question mark (?)

I have the following String that I receive in my rest service:
.6.75:5050/pretups/C2SReceiver?REQUEST_GATEWAY_CODE=8050122997&REQUEST_GATEWAY_TYPE=EXTGW&LOGIN=CO8050122997_EXTGW&PASSWORD=89b87741ca3f73b0b282ae165bad7501&SOURCE_TYPE=XML&SERVICE_PORT=190
I have the following code:
#Controller
public class servicioscontroller {
#RequestMapping(value = "/pretups/{p1}?{trama}", method = RequestMethod.GET)
#ResponseBody
public String enviarTrama(#PathVariable("p1") String p1,#PathVariable("trama") String trama){
return p1+trama;
}
}
And im getting this result:
C2SReceive
I need also the string after that ?, what im doing wrong or how do I get that? thanks
You should use #RequestParam:
#Controller
public class servicioscontroller {
#RequestMapping(value = "/pretups/{p1}", method = RequestMethod.GET, params = ["trama"])
#ResponseBody
public String enviarTrama(
#PathVariable("p1") String p1,
#RequestParam(name = "trama", required = "true") String trama
){
return p1+trama;
}
}
Note that you have to put request params in the #RequestMapping's params attribute instead of the path string.
The difference between #RequestParam and #PathParam is described in this answer.

spring can't receive post param send by postman

And My Controller is like
#RequestMapping(value = "/auth/company/delete", method = RequestMethod.POST,
produces = {"application/json", "application/xml"})
#ResponseBody
public ResponseMessage deleteCompany(#RequestParam("companyId") Integer companyId) {
return companyManageService.deleteCompany(companyId);
}
But when I type code in chrome console using
$.post( "http://ltc_dev.leapstack.cn/gw/security/auth/company/delete", { companyId: 1 })
.done(function( data ) {
alert( data.success);
alert( data.message);
});
I got correct response, so.....
I'm not sure if it is a postman's bug, or I cofig the controller wrong
In your question, your controller method try to take companyId as request param. In postman you are sending companyId in request body. Like I said in comment you can send request param in url section directly like that: /auth/company/delete?companyId=2. Spring boot can detect companyId request parameter and assign it to method's companyId variable directly.
If you want to send companyId in request body (You said that in comment) you have to change your method's signature like below.
#RequestMapping(value = "/auth/company/delete", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
#ResponseBody
public ResponseMessage deleteCompany(#RequestBody Map<String, Integer> map) {
return companyManageService.deleteCompany(map.get("companyId"));
}
Or:
#RequestMapping(value = "/auth/company/delete", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
#ResponseBody
public ResponseMessage deleteCompany(#RequestBody CompanyDTO company) {
return companyManageService.deleteCompany(company.getCompanyId);
}
public class CompanyDTO {
private Integer companyId;
//getter setter
}
If you want to use request body and want to catch integer value directly in controller method's variable as integer your request body should be like:
{2}
And controller method should be like:
#RequestMapping(value = "/auth/company/delete", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
#ResponseBody
public ResponseMessage deleteCompany(#RequestBody Integer companyId) {
return companyManageService.deleteCompany(companyId);
}

400 (Bad Request) while sending json in Spring

I'm trying to send json string to Spring controller, i'm getting 400 - bad request as response
i'm using Spring 4.0.3
This is my controller
#Controller
public class Customer{
#RequestMapping(value = "/apis/test", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody String test(HttpServletRequest params) throws JsonIOException {
String json = params.getParameter("json");
JsonParser jObj = new JsonParser();
JsonArray jsonObj = (JsonArray ) jObj.parse(json);
for(int i = 0; i < jsonObj.size(); i++) {
JsonObject jsonObject = jsonObj.get(i).getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString());
}
return json;
}
}
Please help me to solve this
#RequestMapping(value = "/apis/test", method = RequestMethod.GET, produces = "application/json")
The above means this is a HTTP GET method which does not normally accept data. You should be using a HTTP POST method eg:
#RequestMapping(value = "/apis/test", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody String test(#RequestParam final String param1, #RequestParam final String param2, #RequestBody final String body) throws JsonIOException {
then you can execute POST /apis/test?param1=one&param2=two and adding strings in the RequestBody of the request
I hope this helps!

After calling URL "/article/1234abcd" how to retrieve the value `1234abcd` from inside the `article` action?

#RequestMapping(value = "/article", method = RequestMethod.GET)
public final String article(final ModelMap model)
{
}
If this is called using the address:
/article/1234abcd
How can the value 1234abcd be retrieved from inside the article method?
By using #PathVariable:
#RequestMapping(value = "/article/{articleId}", method = RequestMethod.GET)
public final String article(final ModelMap model, #PathVariable String articleId)
{
}
See Spring docs for more info.

Resources