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

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.

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());
//...
}

What should I do in springboot if I use a post request with only one parameter?

No use of map and bean, what is a good solution?
How to get the orderId better
#RequestMapping(value = "/submitTail", method = RequestMethod.POST)
#ResponseBody
public Object generateTailOrder(String orderId) {
}
Use PathVariable if you can add orderId somewhere in URL. Take care of API standards.
Example: /orders/{orderId}/submitTrail
By doing this your API will be more informative and should not be invoked without orderId.
#RequestMapping(value = "/submitTail/{orderId}", method =
RequestMethod.GET)
public Object generateTailOrder(#PathVariable String orderId) {
}
OR
#GetMapping(value = "/submitTail/{orderId}")
public Object generateTailOrder(#PathVariable String orderId) {
}

Spring: How can I get value from uri?

How can the callbackFacebook function get the value of code from the uri?
uri = http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code) {
System.out.println(code);
return "login";
}
Try this. code is a query parameter judging by your URL, not a path variable. Path variables are a part of the path itself (i.e. if your URL was something like /{code}/callback, then code is a PathVariable).
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
System.out.println(code);
return "login";
}
If your URL is http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo then it is case of request parameters so the method will be like below.
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
return "login";
}
If your URL is http://localhost:8081/callback/AQDNm6hezKdTsId5k4oXKNo then then it is case of path variables method will be like below.
#RequestMapping(value = "/callback/{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(value = "code") String code) {
return "login";
}
Refer requestparam-vs-pathvariable for better clarity.
I will explain 2 ways.
1-If it is added in the session in somewhere in the project as attribute,You can get it like this :
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
String code1 = request.getSession().getAttribute("code").toString();
return "login";
}
example output : AQDNm6hezKdTsId5k4oXKNo
2-You can directly get URL.But then you need to parse URL.Because all URL is coming.
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
StringBuffer requestURL = request.getRequestURL();
return "login";
}
example output : http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo

404 Request Resource not found

I am using Spring Framework with restful web services, and I am trying to create an API with restful service and use a get method. I have created a method and I'm trying to have it return a string, but instead I get a 404 error - requested resources not found. Please see my code below:
#RestController
#RequestMapping("/test")
public class AreaController {
public RestResponse find(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
I am using: localhosr:8080/MyProject/wangdu
This error occurs because you forgot to add
#RequestMapping(value = "/{name}", method = RequestMethod.GET) before your find method:
#RestController
#RequestMapping("/test")
public class AreaController {
#RequestMapping(value = "/{name}", method = RequestMethod.GET)
public RestResponse find(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
Please make sure about this:
The value that the find method is returning is a String with the value "list" and the find method declaration is waiting for a RestResponse object
For example if I have a RestResponse object like this:
public class RestResponse {
private String value;
public RestResponse(String value){
this.value=value;
}
public String getValue(){
return this.value;
}
}
Then try to return the value in this way:
public RestResponse find(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return new RestResponse("list");
}
Verify that the method has #RequestMapping annotation with the value that your expect from the url
#RequestMapping(method = RequestMethod.GET, value = "/{name}")
By default the proper way to call the rest resource is by the #RequestMapping value that you set at the #RestController level (#RequestMapping("/test")), in this case could be: http://localhost:8080/test/myValue
If you need to use a different context path then you can change it on the application.properties (for spring boot)
server.contextPath=/MyProject/wangdu
In that case you can call the api like this:
http://localhost:8080/MyProject/wangdu/test/myValue
Here is the complete code for this alternative:
#RestController
#RequestMapping("/test")
public class AreaController {
#RequestMapping(method = RequestMethod.GET, value = "/{name}")
public RestResponse find(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return new RestResponse("list");
}

spring boot : RequestMapping

I have following three REST API methods :
#RequestMapping(value = "/{name1}", method = RequestMethod.GET)
public Object retrieve(#PathVariable String name1) throws UnsupportedEncodingException {
return configService.getConfig("frontend", name1);
}
#RequestMapping(value = "/{name1}/{name2}", method = RequestMethod.GET)
public Object retrieve(#PathVariable String name1, #PathVariable String name2) throws UnsupportedEncodingException {
return configService.getConfig("frontend", name1, name2);
}
#RequestMapping(value = "/{name1}/{name2}/{name3}", method = RequestMethod.GET)
public Object retrieve(#PathVariable String name1, #PathVariable String name2, #PathVariable String name3) {
return configService.getConfig("frontend", name1, name2,name3);
}
getConfig method is configured to accept multiple parameters like:
public Object getConfig(String... names) {
My Question is : is it possible to achieve the above RequestMapping using only one method/RequestMapping ?
Thanks.
Simple approach
You can use /** in your mapping to grab any URL and then extract all parameters from the mapping path. Spring has a constant which allows you to fetch the path from the HTTP request. You just have to remove the unnecessary part of the mapping and split the rest to get the list of parameters.
import org.springframework.web.servlet.HandlerMapping;
#RestController
#RequestMapping("/somePath")
public class SomeController {
#RequestMapping(value = "/**", method = RequestMethod.GET)
public Object retrieve(HttpServletRequest request) {
String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
String[] names = path.substring("/somePath/".length()).split("/");
return configService.getConfig("frontend", names);
}
}
Better approach
However, path variables should be rather used for identifying resources in your application and not as a parameters to a given resource. In that case, it is advised to stick with simple request parameters.
http://yourapp.com/somePath?name=value1&name=value2
You mapping handler would look much more simple:
#RequestMapping(method = RequestMethod.GET)
public Object retrieve(#RequestParam("name") String[] names) {
return configService.getConfig("frontend", names);
}
You should probably use #RequestParam instead and method POST in order to achieve what you want.
#RequestMapping(name = "/hi", method = RequestMethod.POST)
#ResponseBody
public String test(#RequestParam("test") String[] test){
return "result";
}
And then you post like that:
So your array of Strings will contain both values
Also in REST a path corresponds to a resource, so you should ask yourself "what is the resource i am exposing ?". It would probably be something like /config/frontend and then you specify your options through request params and/or HTTP verbs
You can retrieve the complete path with request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE) and then parse it to get all the values.
This should work:
#SpringBootApplication
#Controller
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping(value ={"/{name1}","/{name1}/{name2}","/{name1}/{name2}/{name3}"})
public #ResponseBody String testMethod(
#PathVariable Map<String,String> pathvariables)
{
return test(pathvariables.values().toArray(new String[0]));
}
private String test (String... args) {
return Arrays.toString(args);
}
}

Resources