In Java-Jersey, it is possible to receive a dynamic path to a resource, e.g.
localhost:8080/webservice/this/is/my/dynamic/path
#GET
#Path("{dynamicpath : .+}")
#Produces(MediaType.APPLICATION_JSON)
public String get(#PathParam("dynamicpath") String p_dynamicpath) {
return p_dynamicpath;
}
prints out: this/is/my/dynamic/path
Question: how to do this in Spring MVC?
For multiple items inside your path you can access the dynamic path values like this:
#RequestMapping(value="/**", method = RequestMethod.GET)
public String get(HttpServletRequest request) throws Exception {
String dynPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println("Dynamic Path: " + dynPath );
return dynPath;
}
If you know beforehand hoe many levels of path variables you'll have you can code them explicit like
#RequestMapping(value="/{path1}/{path2}/**", method = RequestMethod.GET)
public String get(#PathVariable("path1") String path1,
#PathVariable("path2") String path2,
HttpServletRequest request) throws Exception {
String dynPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println("Dynamic Path: " + dynPath );
return dynPath;
}
If you want to see the String returned in your browser, you need to declare the method #ResponseBody as well (so the String you return is the content of your response):
#RequestMapping(value="/**", method = RequestMethod.GET, produces = "text/plain")
#ResponseBody
public String get(HttpServletRequest request) throws Exception {
Related
Is there a way to get the complete path value after the requestMapping #PathVariable values have been parsed?
That is:
/{id}/{restOfTheUrl} should be able to parse /1/dir1/dir2/file.html into id=1 and restOfTheUrl=/dir1/dir2/file.html
Any ideas would be appreciated.
Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE:
#RequestMapping("/{id}/**")
public void foo(#PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = new AntPathMatcher().extractPathWithinPattern(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString(),request.getRequestURI());
...
}
Just found that issue corresponding to my problem. Using HandlerMapping constants I was able to wrote a small utility for that purpose:
/**
* Extract path from a controller mapping. /controllerUrl/** => return matched **
* #param request incoming request.
* #return extracted path
*/
public static String extractPathFromPattern(final HttpServletRequest request){
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
return finalPath;
}
This has been here quite a while but posting this. Might be useful for someone.
#RequestMapping( "/{id}/**" )
public void foo( #PathVariable String id, HttpServletRequest request ) {
String urlTail = new AntPathMatcher()
.extractPathWithinPattern( "/{id}/**", request.getRequestURI() );
}
Building upon Fabien Kruba's already excellent answer, I thought it would be nice if the ** portion of the URL could be given as a parameter to the controller method via an annotation, in a way which was similar to #RequestParam and #PathVariable, rather than always using a utility method which explicitly required the HttpServletRequest. So here's an example of how that might be implemented. Hopefully someone finds it useful.
Create the annotation, along with the argument resolver:
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
#Documented
public #interface WildcardParam {
class Resolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(WildcardParam.class) != null;
}
#Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
return request == null ? null : new AntPathMatcher().extractPathWithinPattern(
(String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
}
}
}
Register the method argument resolver:
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new WildcardParam.Resolver());
}
}
Use the annotation in your controller handler methods to have easy access to the ** portion of the URL:
#RestController
public class SomeController {
#GetMapping("/**")
public void someHandlerMethod(#WildcardParam String wildcardParam) {
// use wildcardParam here...
}
}
You need to use built-in pathMatcher:
#RequestMapping("/{id}/**")
public void test(HttpServletRequest request, #PathVariable long id) throws Exception {
ResourceUrlProvider urlProvider = (ResourceUrlProvider) request
.getAttribute(ResourceUrlProvider.class.getCanonicalName());
String restOfUrl = urlProvider.getPathMatcher().extractPathWithinPattern(
String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)),
String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)));
I have used the Tuckey URLRewriteFilter to handle path elements that contain '/' characters, as I don't think Spring 3 MVC supports them yet.
http://www.tuckey.org/
You put this filter in to your app, and provide an XML config file. In that file you provide rewrite rules, which you can use to translate path elements containing '/' characters into request parameters that Spring MVC can deal with properly using #RequestParam.
WEB-INF/web.xml:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<!-- map to /* -->
WEB-INF/urlrewrite.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite
PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN"
"http://tuckey.org/res/dtds/urlrewrite3.0.dtd">
<urlrewrite>
<rule>
<from>^/(.*)/(.*)$</from>
<to last="true">/$1?restOfTheUrl=$2</to>
</urlrewrite>
Controller method:
#RequestMapping("/{id}")
public void handler(#PathVariable("id") int id, #RequestParam("restOfTheUrl") String pathToFile) {
...
}
Yes the restOfTheUrl is not returning only required value but we can get the value by using UriTemplate matching.
I have solved the problem, so here the working solution for the problem:
#RequestMapping("/{id}/**")
public void foo(#PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
/*We can use UriTemplate to map the restOfTheUrl*/
UriTemplate template = new UriTemplate("/{id}/{value}");
boolean isTemplateMatched = template.matches(restOfTheUrl);
if(isTemplateMatched) {
Map<String, String> matchTemplate = new HashMap<String, String>();
matchTemplate = template.match(restOfTheUrl);
String value = matchTemplate.get("value");
/*variable `value` will contain the required detail.*/
}
}
Here is how I did it. You can see how I convert the requestedURI to a filesystem path (what this SO question is about). Bonus: and also how to respond with the file.
#RequestMapping(value = "/file/{userId}/**", method = RequestMethod.GET)
public void serveFile(#PathVariable("userId") long userId, HttpServletRequest request, HttpServletResponse response) {
assert request != null;
assert response != null;
// requestURL: http://192.168.1.3:8080/file/54/documents/tutorial.pdf
// requestURI: /file/54/documents/tutorial.pdf
// servletPath: /file/54/documents/tutorial.pdf
// logger.debug("requestURL: " + request.getRequestURL());
// logger.debug("requestURI: " + request.getRequestURI());
// logger.debug("servletPath: " + request.getServletPath());
String requestURI = request.getRequestURI();
String relativePath = requestURI.replaceFirst("^/file/", "");
Path path = Paths.get("/user_files").resolve(relativePath);
try {
InputStream is = new FileInputStream(path.toFile());
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
logger.error("Error writing file to output stream. Path: '" + path + "', requestURI: '" + requestURI + "'");
throw new RuntimeException("IOError writing file to output stream");
}
}
private final static String MAPPING = "/foo/*";
#RequestMapping(value = MAPPING, method = RequestMethod.GET)
public #ResponseBody void foo(HttpServletRequest request, HttpServletResponse response) {
final String mapping = getMapping("foo").replace("*", "");
final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
final String restOfPath = url.replace(mapping, "");
System.out.println(restOfPath);
}
private String getMapping(String methodName) {
Method methods[] = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName() == methodName) {
String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
if (mapping.length > 0) {
return mapping[mapping.length - 1];
}
}
}
return null;
}
To improve upon #Daniel Jay Marcaida answer
#RequestMapping( "/{id}/**" )
public void foo( #PathVariable String id, HttpServletRequest request ) {
String restOfUrl = new AntPathMatcher()
.extractPathWithinPattern(
request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString(),
request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString());
}
or
#RequestMapping( "/{id}/**" )
public void foo( #PathVariable String id, HttpServletRequest request ) {
String restOfUrl = new AntPathMatcher()
.extractPathWithinPattern(
request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString(),
request.getServletPath());
}
I have a similar problem and I resolved in this way:
#RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(#PathVariable String siteCode,
#PathVariable String fileName, #PathVariable String fileExtension,
HttpServletRequest req, HttpServletResponse response ) throws IOException {
String fullPath = req.getPathInfo();
// Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
// fullPath conentent: /SiteXX/images/argentine/flag.jpg
}
Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.
My URL request is http://localhost:8080/login/verify/212,32,/cntv5tag07rmy791wbme7xa8x,/SSNZclzqhhH7v6uHIkUsIcPusKo=
I need get the following part: **212,32,/cntv5tag07rmy791wbme7xa8x,/SSNZclzqhhH7v6uHIkUsIcPusKo=**.
The following code doesn't work:
#RequestMapping(value = "/login/verify/{request:.+}", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
public ResponseEntity verifyLogin(#PathVariable(value = "request") String request)
throws InvalidSignatureException
{
}
Error: HTTP Status 404.
Spring can't handle this request.
To match the uri with the slashes, use the double *
#RequestMapping(value = "/login/verify/**",
Then, in the body to get the value, you will use
String str = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)
Sample code:
#RequestMapping(value = "/login/verify/**", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
public ResponseEntity verifyLogin(HttpServletRequest httpServletRequest) throws InvalidSignatureException {
String str = (String) request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)
}
You have forward slashes in your url and those strings will be considered as path variables. Try the following code if there is a possibility that you'll have only 3 path variables. Please have a look at here and here
#RequestMapping(value = {"/login/verify/{string1:.+}",
"/login/verify/{string1:.+}/{string2:.+}",
"/login/verify/{string1:.+}/{string2:.+}/{string3:.+}"}, method = RequestMethod.POST)
public ResponseEntity verifyLogin(HttpServletRequest request, HttpServletResponse httpresponse,
#PathVariable("string1") String string1,
#PathVariable("string2") String string2,
#PathVariable("string3") String string3) {
System.out.println("***************************************************I am called: "+string1+" "+string2+" "+string3);
}
Try this URL instead: http://localhost:8080/login/verify?req=212,32,/cntv5tag07rmy791wbme7xa8x,/SSNZclzqhhH7v6uHIkUsIcPusKo=
And handle it like this:
#RequestMapping("/login/verify")
public String test(#RequestParam("req") String data) {
//'data' will contains '212,32,/cntv5tag07rmy791wbme7xa8x,/SSNZclzqhhH7v6uHIkUsIcPusKo='
String params[] = data.split(",");
}
There is a task to pass file path as #PathVariable in Spring MVC to REST Service with GET request.
We can easily do it with POST sending String of file path in JSON.
How we can do with GET request and #Controller like this?
#RequestMapping(value = "/getFile", method = RequestMethod.GET)
public File getFile(#PathVariable String path) {
// do something
}
Request:
GET /file/getFile/"/Users/user/someSourceFolder/8.jpeg"
Content-Type: application/json
You should define your controller like this:
#RequestMapping(value = "/getFile/{path:.+}", method = RequestMethod.GET)
public File getFile(#PathVariable String path) {
// do something
}
Ok.
you use to get pattern.
sending get pattern url.
Use #RequestParam.
#RequestMapping(value = "/getFile", method = RequestMethod.GET)
public File getFile(#RequestParam("path") String path) {
// do something
}
and if you use #PathVariable.
#RequestMapping(value = "/getFile/{path}", method = RequestMethod.POST)
public File getFile(#PathVariable String path) {
// do something
}
What I did works with relative paths to download/upload files in Spring.
#RequestMapping(method = RequestMethod.GET, path = "/files/**")
#NotNull
public RepositoryFile get(#PathVariable final String repositoryId,
#PathVariable final String branchName,
#RequestParam final String authorEmail,
HttpServletRequest request) {
String filePath = extractFilePath(request);
....
}
And the utilitary function I created within the controller :
private static String extractFilePath(HttpServletRequest request) {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
return apm.extractPathWithinPattern(bestMatchPattern, path);
}
Given a method like:
#RequestMapping(value = {"/foo"}, method = RequestMethod.GET)
public String getMappingValueInMethod() {
log.debug("requested "+foo); //how can I make this refer to /foo programmatically?
return "bar";
}
The use case is for refactoring some lengthly code. I have several GET methods doing roughly the same thing and only the request mapping value is different.
I've looked at using path variables, but this is not really what I want (unless there's some clever use of it that I don't see). I could also get a value from the HttpServletRequest like in this post, but not sure whether there's a better way.
Solution 1
With HttpServletRequest.
#RequestMapping(value = "/foo", method = RequestMethod.GET)
public String fooMethod(HttpServletRequest request) {
String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
System.out.println("path foo: " + path);
return "bar";
}
Solution 2
With reflection.
#RequestMapping(value = "/foo2", method = RequestMethod.GET)
public String fooMethod2() {
try {
Method m = YourClassController.class.getMethod("fooMethod2");
String path = m.getAnnotation(RequestMapping.class).value()[0];
System.out.println("foo2 path: " + path);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return "bar";
}
If you want get path from class (instead method) you can use:
String path = YourClassController.class.getAnnotation(RequestMapping.class).value();
Solution 3
With #PathVariable.
#RequestMapping(value = {"/{foo3}"}, method = RequestMethod.GET)
public #ResponseBody String fooMethod3(#PathVariable("foo3") String path) {
path = "/" + path; // if you need "/"
System.out.println("foo3 path: " + path);
return "bar";
}
The simplest way of doing this would be putting the array directly in the request mapping i am assuming this is what you want.
#RequestMapping(value = {"/foo","/foo1","/foo2"}, method = RequestMethod.GET)
public String getMappingValueInMethod(HttpServletRequest request) {
log.debug("requested "+request.getRequestURI());
return request.getRequestURI();
}
Then name the jsp files similar to the uri or other wise you could store the mapping between the request uri and the name of the page in the db .
I need something similar to enter link description here
So my path would be: /something/else/and/some/more
I would like to map it like so:
#RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String theRestOfPath){ /***/ }
Or
#RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String[] theRestOfPathArr){ /***/ }
The thing is ... I would like everything matched by ** to be passed to the method either:
1. as a string (theRestOfPath = "/else/and/some/more"),
2. or as an array (theRestOfPathArr = ["else","and","some","more"]).
The number of path variables can vary, so I can't do:
#RequestMapping(value="/something/{a}/{b}/{c}", method=RequestMethod.GET)
public String handleRequest(String a, String b, String c){ /***/ }
Is there a way to do that?
Thanks :)
---EDIT---
The solution I ended up with:
#RequestMapping(value = "/something/**", method = RequestMethod.GET)
#ResponseBody
public TextStory getSomething(HttpServletRequest request) {
final String URI_PATTERN = "^.*/something(/.+?)(\\.json|\\.xml)?$";
String uri = request.getRequestURI().replaceAll(URI_PATTERN, "$1");
return doSomethingWithStuff(uri);
}
If you include an HttpServletRequest as an argument to your method, then you can access the path being used. i.e.:
#RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(HttpServletRequest request){
String pattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String path = new AntPathMatcher()
.extractPathWithinPattern(pattern, request.getServletPath());
path = path.replaceAll("%2F", "/");
path = path.replaceAll("%2f", "/");
StringTokenizer st = new StringTokenizer(path, "/");
while (st.hasMoreElements()) {
String token = st.nextToken();
// ...
}
}
There's feature in spring MVC which will do parsing for you. Just use #PathVariable annotation.
Refer: Spring mvc #PathVariable