Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - Spring MVC @Path variable with { } braces

Am developing an application using spring boot. In REST controller i prefer to use path variable(@PathVariabale annotation). My code fetching the path variable but it contatins { } braces as it is in the url. Please any one suggest me to solve this issue

@RequestMapping(value = "/user/item/{loginName}", method = RequestMethod.GET)
public void getSourceDetails(@PathVariable String loginName) {
    try {
        System.out.println(loginName);
        // it print like this  {john}
    } catch (Exception e) {
        LOG.error(e);
    }
}

URL

http://localhost:8080/user/item/{john}

Out put in controller

{john}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use http://localhost:8080/user/item/john to submit your request instead.

You give Spring a value of "{john}" to the path variable loginName, so Spring get it with the "{}"

Web MVC framework states that

URI Template Patterns

URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI. The proposed RFC for URI Templates defines how a URI is parameterized. For example, the URI Template http://www.example.com/users/{userId} contains the variable userId. Assigning the value fred to the variable yields http://www.example.com/users/fred.

In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
 public String findOwner(@PathVariable String ownerId, Model model) {
     Owner owner = ownerService.findOwner(ownerId);
     model.addAttribute("owner", owner);
     return "displayOwner"; 
  }

The URI Template " /owners/{ownerId}" specifies the variable name ownerId. When the controller handles this request, the value of ownerId is set to the value found in the appropriate part of the URI. For example, when a request comes in for /owners/fred, the value of ownerId is fred.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...