Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic path to resource in springmvc

Tags:

java

spring

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?

like image 472
user3601578 Avatar asked Dec 27 '25 16:12

user3601578


1 Answers

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 {
like image 159
Jan Avatar answered Dec 31 '25 16:12

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!