Jersey endpoint using '+' in queryparam - java

I want to design an endpoint similar to
$host/api/products?price=under+5
How can I use '+' in queryparam?
I could do like this to get that url
#GET
#Path("/products?price=under+{price}")
But How can I do using #QueryParam? If I use the following,
#GET
#Path("/products")
#UnitOfWork
public Response getProducts(#NotNull #QueryParam("price") String price) {
I get
$host/api/products?price=5

The value of the price query parameter must be URL encoded. When URL encoded, the + character becomes %2B. So you'll have under%2B5.
With it, the following should work fine:
#GET
#Path("/products")
public Response getProducts(#NotNull #QueryParam("price") String price) {
// the value of price will be: under+5
...
}
If you don't want the JAX-RS runtime to decode the price parameter, annotate it with #Encoded.

Related

How can I pass a value with '/' symbol as get parameter to my controller?

I have controller:
#RestController
public class MyController {
#GetMapping(value = "/products/{value}")
public String get(#PathVariable String value) {
System.out.println(value);
return "OK";
}
}
After start server I try to send a message like this:
http://localhost:8080/products/Mazda
and I see in console Mazda. But when I send value with a backslash:
http://localhost:8080/products/Mazda\6
I get an error:
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
How can I pass a value with '\' symbol as get parameter to my controller?
I expect: Mazda\6
First, you need to encode the path variable on the client side. Here is an example for Java:
URLEncoder.encode("Mazda\\6", "UTF-8");
The result will be Mazda%5C6.
The second step is to allow the processing of requests containing special characters in their URLs.
Third, decode the string in the controller:
String decodedValue = URLDecoder.decode(value, "UTF-8");

How to get parameter which is containing question mark(?) from rest url in spring

i need get string from url where is "?" but controller does not accept "?"
I need send something like "Hello world?"
but I get only "Hello world"
I find solution for dot(.) -- value = "{textToTransform:.+}"
#RestController
#RequestMapping(textTransformCtrl.BASE_URI)
public class textTransformCtrl {
#Autowired
private TextTransformatorService textTransformatorService;
public static final String BASE_URI = "transform/text";
#RequestMapping(value = "{textToTransform:.+}")
public String getText(#PathVariable final String textToTransform) {
return textTransformatorService.transformText(textToTransform);
}
}
Question mark is a reserved character in URLs. It indicates where the query string starts.
If you want to send a ? as a parameter value and be able to read it on server side, you must URL encode it.
When URL encoded, Hello world? becomes Hello+world%3F.
You can use %3F to manually encode it or take a look at UriBuilder

RequestMapping with String parameter containing URL

I have a Spring controller with two parameter long and String:
#RequestMapping(value = "/webpage")
#Controller
public class WebpageContentController {
//...
#RequestMapping(value = "{webpageId}/{webpageAddress}", method = RequestMethod.GET)
public String contentWebpageById(#PathVariable long webpageId, #PathVariable String webpageAddress) {
System.out.println("webpageId=" + webpageId);
System.out.println("webpageAddress=" + webpageAddress);
//...
}
//...
If I invoke it like this:
http://localhost:8080/webarch/webpage/1/blahblah
All is fine:
webpageId=1
webpageAddress=blahblah
But If I pass String parameter with slash (in this case URL address):
http://localhost:8080/webarch/webpage/1/https://en.wikipedia.org/wiki/Main_Page
I get an error:
org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/webarch/webpage/1/https://en.wikipedia.org/wiki/Main_Page] in DispatcherServlet with name 'appServlet'
How pass such parameter?
Well the error is caused by springs controllers mapping, when Spring sees url like
http://localhost:8080/webarch/webpage/1/https://en.wikipedia.org/wiki/Main_Page
It doesn't 'know' that the 'https://en.wikipedia.org/wiki/Main_Page' should be mapped as parameter to "{webpageId}/{webpageAddress}" mapping since every slash is interpreted as a deeper controler method mapping. It looks for controller method mapping like (webpage/1/http:{anotherMapping}/wiki{anotherMapping}/Main_Page{anotherMapping}) wich this kind of mapping is obviously not handled by "{webpageId}/{webpageAddress}"
EDIT
According to your comment you can try something like this
#RequestMapping(value = "/{webpageId}/**", method = RequestMethod.GET)
public String contentWebpageById(HttpServletRequest request) {
String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String extractedPathParam = pathMatcher.extractPathWithinPattern(pattern, request.getServletPath());
extractedPathParam = extractedPathParam.replace("http:/", "http://");
extractedPathParam = extractedPathParam.replace("https:/", "https://");
//do whatever you want with parsed string..
}
Using spring 4.2.1
SomeParsing should use some Regular Expression to extract only the URL 'variable'
Just encode all special characters in the URL.
https://en.wikipedia.org/wiki/Main_Page
becomes this:
https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMain_Page
and you can pass it as URL parameter without any problems. Decoding is done automatically, so if you access the parameter as variable in your controller, it contains the URL already decoded and you can use it without any converting needed.
More information about URL encoding: https://en.wikipedia.org/wiki/Percent-encoding

Is it possible to extarct path parameter and url in jersey

I am actually trying to separate URL and path parameters in jersey implementation.
My request URL is /web/seller/{pathpartma1}/{pathparam2}
I need to get the following data from the request
Request url: /web/seller
Parameter1 name = pathpartma1
Parameter2 name = pathparam2
My method looks like this
#GET
#Path(value = "/web/seller/{pathparam1}/{pathparam2}")
#Produces(MediaType.JSON)
public String myMethod(#Context HttpServletRequest request,#PathParam("pathparam1") String pathparam1, #PathParam("pathparam2") String pathparam2)
{
/////
}
Can some one tell if it is possible to extract url and path parameter names in my method.
Your Path is incorrect - the lef tbrace is missing at the end.

Optional param not working in jersey using regex

I am working to cater REST url of three types:
url/detail/3 (integer only)
url/detail/hello (String only)
url/detail/3/1d
For URL 1 and 3 I am using method1 and for URL 2 method2 is used.
Problem 1: All requests type of 1 and 2 matches method 2 only.Though I've specified Integer pattern in method 1 for queries having integer specifically.
Problem 2: To use an optional param (like in 3) I am using method1 because jersey doesn't provide any option for optional param.But url types of url/detail/3/1d is never matched as specified in method 1.
Please help me understand what I am doing wrong as I am newbie to jersey.
#GET
#Path("/detail/{id: \\d+}/{time-period:(/time-period/[^/]+?)?}")
#Produces({ MediaType.APPLICATION_JSON })
#Consumes(MediaType.APPLICATION_JSON)
public JResponse method1(
#Context HttpHeaders headers,
#PathParam("id") String id,
#PathParam("time-period") String timePeriod) {
if(timePeriod == null || timePeriod.equals(""))
{
//code
}
else
//code
}
#GET
#Path("/detail/{name}")
#Produces({ MediaType.APPLICATION_JSON })
#Consumes(MediaType.APPLICATION_JSON)
public JResponse method2(
#Context HttpHeaders headers, #PathParam("name") String name) {
//code
}
Maybe a missing whitespace leads to the problem. See Optional #PathParam in Jax-RS
You can define default values for parameters with #DefaultValue("1000")
Instead of complicated regexps you should probably use subresource.
#Path("detail/{id}{time-perioid:(/[^/]+?)?}")
http://x.y.z:4080/analytics/internal/detail/kala
2014-01-17 07:35:50,509 [http-nio-4080-exec-8] INFO xxx - id: kala
2014-01-17 07:35:50,510 [http-nio-4080-exec-8] INFO xxx - time-period:
and
http://x.y.z:4080/analytics/internal/detail/kala/123
2014-01-17 07:36:01,644 [http-nio-4080-exec-9] INFO xxx - id: kala
2014-01-17 07:36:01,645 [http-nio-4080-exec-9] INFO xxx - time-period: /123
If id can be string or integer I would go validating it inside handler.

Categories

Resources