Generate unique address to controller using Spring MVC 4 [duplicate] - java

I am trying to build a request filter that will only get used if it matches a pattern of the letter e, then a number. However I cannot seem to get it to work. I keep getting 400 errors every time I try something with regex.
If I just use the following it "works" but also captures mappings that do not have numbers which I don't want.
#RequestMapping(value = "e{number}",
method = RequestMethod.GET)
I have tried the following combinations.
#RequestMapping(value = "e{number}",
params = "number:\\d+",
method = RequestMethod.GET)
#RequestMapping(value = "e{number:\d+}",
method = RequestMethod.GET)
#RequestMapping(value = "/e{^\\+?\\d+\$}",
method = RequestMethod.GET)
#RequestMapping(value = "/{^\\e+?\\d+\$}",
method = RequestMethod.GET)

According to the documentation, you have to use something like {varName:regex}. There's even an example :
#RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(#PathVariable String version, #PathVariable String extension) {
// ...
}
}

You should use:
#RequestMapping("/e{number:\\d+})
Notice the "escaped slash" before the \d digit specifier.

Related

Spring-mvc requestParam not supports unicode characters

I'm new in spring-mvc, I 'm trying to post unicode characters to my method
#RequestMapping(value = ["api/test"], method = [RequestMethod.POST], produces = ["text/plain; charset=utf-8"])
#ResponseBody
fun saveData(#RequestParam(value = "myParam") myParam: String): String {
println(myParam) // prints characters like á?¥á??á? á??á?£á??á??á?
return myParam
}
It doesn't have any problem with ASCII character encoding params.
I'm testing this service using postman.
I think I have saw the all questions about this issue, but nothing worked for me, the result is same :/

How to correctly escape '/' in Spring Rest #PathVariable

In Spring Boot 1.5.4 I have a request mapping like this:
#RequestMapping(value = "/graph/{graphId}/details/{iri:.+}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public JSONObject getGraph(#PathVariable Long graphId,
#PathVariable String iri) {
log.debug("Details called for graph ID {} for IRI {}", graphId, iri);
return detailsService.getDetails(graphId, iri);
}
Accessing
http://localhost:9000/api/v1/graph/2/details/http%3Anthnth33
works fine and the server maps the request correctly and the code returns the expected result
But accessing
http://localhost:9000/api/v1/graph/2/details/http%3A%2F%2Fserverurl.net%2Fv1%2Fus%2Fh.schumacher%408tsch.net%2Fn%2FLouSchumacher
gives a bad server request (Failed to load resource: the server responded with a status of 400 (Bad Request)). The request mapping to the end point isn't even done in that case.
Obviously the slash '/' encoded as %2F (using encodeURIComponent()) causes trouble. Why? What am I missing? How should uri parameter then be encoded?
The question is not only about how to extract PathVariables but more on how to force String to recognize the correct mapping.
The issue with your example is how Spring is doing path matching. The URL you have provided as example
http://localhost:9000/api/v1/graph/2/details/http%3A%2F%2Fserverurl.net%2Fv1%2Fus%2Fh.schumacher%408tsch.net%2Fn%2FLouSchumacher
will be decoded into by container
http://localhost:9000/api/v1/graph/2/details/http://serverurl.net/v1/us/h.schumacher#8tsch.net/n/LouSchumacher
before processing by Spring matcher. This makes matche think that this only http: corresponds {iri:.+} and as later goes / so it is some longer path you don't have a mapping for.
The approach described here should work for you: Spring 3 RequestMapping: Get path value
#RequestMapping(value = "/graph/{graphId}/details/**",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public JSONObject getGraph(#PathVariable Long graphId,
HttpServletRequest request) {
String iri = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
log.debug("Details called for graph ID {} for IRI {}", graphId, iri);
return detailsService.getDetails(graphId, iri);
}

How to share information between Spring controller methods from GET and POST requests?

I'm new to Spring and I want to:
1) when an user visits localhost/admin/users I want the predefined options to apply
2) On localhost/admin/users I have some buttons that perform a POST with four parameters because my boss don't want me to use get (and I think is better to use POST, too)
3) I have a controller method adminUsersPost that manages the POST request, and I want that method to be able to make my browser to reload using the adminUsersGet method, but with the information sent in the POST request.
What I'm getting now in my browser is an alert with a webpage content in some weird encoding, I hope it is correct but I don't know.
#RequestMapping(value = "/admin/users", method = RequestMethod.GET)
public ModelAndView adminUsersGet(
Integer page,
Integer items,
String sorting,
String sortingDirection)
{
// predefined options
Integer pagina = 1;
Integer itemsPorPagina = 10;
String ordenacion = "idUsuario";
String dirOrdenacion = "asc";
// end of predefined options
// Code that I want for it to use POST params from the other method
ModelAndView mv = new ModelAndView("adminUsers");
return mv;
}
#RequestMapping(value = "/admin/users", method = RequestMethod.POST)
public ModelAndView adminUsersPost(
#RequestParam(value = "pagina") Integer pagina,
#RequestParam(value = "itemsPorPagina") Integer itemsPorPagina,
#RequestParam(value = "ordenacion") String ordenacion,
#RequestParam(value = "dirOrdenacion") String dirOrdenacion)
{
// Here I try to pass the POST parameters to the GET method for reloading
// the webpage with the new content
return adminUsersGet(pagina, itemsPorPagina, ordenacion, dirOrdenacion);
}
The pattern POST params-->GET same parameters is a common one. What you need is RedirectAttributes which will store your parameters into the session and redirect to your GET method. Once the GET is hit spring will automatically remove all attributes from the session, thus none of the POST parameters will be displayed in the browser url in the GET method. Have a look here for a complete example and adjust it for your needs.

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

How to match extension in any path level with Spring MVC?

i need to a request mapper that match only images in any path level.
For example, it must match;
http://localhost:8080/filename.jpg
http://localhost:8080/figs/filename.jpg
I tried regex and non-regex way;
#RequestMapping(value = "{reg:(?:\\w|\\W)+\\.(?:jpg|bmp|gif|jpeg|png|webp)$}", method = RequestMethod.GET)
But, it matches with http://localhost:8080/filename.jpg but not matches with http://localhost:8080/figs/filename.jpg or http://localhost:8080/anypathlevelNtimes/
figs/filename.jpg
How can it matches with all path level and file extension is only image.
Edit: It is OK now
#RequestMapping(value = {"/**/{extension:(?:\\w|\\W)+\\.(?:jpg|bmp|gif|jpeg|png|webp)$}"}, method = RequestMethod.GET)
Solution proposed by OP:
#RequestMapping( //
value = {"/**/{extension:(?:\\w|\\W)+\\.(?:jpg|bmp|gif|jpeg|png|webp)$}"}, //
method = RequestMethod.GET //
)
#RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(#PathVariable String version, #PathVariable String extension) {
// ...
}
reference https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html
https://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/util/AntPathMatcher.html

Categories

Resources