使用@RequestMapping注释时获取请求的值(URL)

2022-09-03 12:18:40

当我将多个值映射到@RequestMapping(如多个Spring @RequestMapping注释)时,我可以获得请求的值(URL)吗?

喜欢这个:

@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model) throws Exception {     
    String requestedValue = getRequestedValue();  // I want this.

    // I want to do something like this with requested value.
    String result; 
    if (requestedValue.equals("center")
        result = "center";
    else if (requestedValue.equals("left")
        result = "left";
    return result;
}

答案 1

您可以将 Request () 本身作为处理程序方法的参数。因此,您可以检查请求 URL 以获取“值”。HttpServletRequest

@RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET)
public String getCenter(Model model, HttpServletRequest request) throws Exception {             
   String whatYouCallValue = request.getServletPath(); 
   ....

Javadoc: https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getServletPath--

顺便说一句:如果我对你的理解是正确的,你希望有不同的网址,而不是不同的值。


答案 2

从 Spring 3.1.0 开始,您可以将 URI 模板模式与正则表达式结合使用

@RequestMapping(value={"/{path:[a-z-]+}"}, method=RequestMethod.GET)
public String getCenter(@PathVariable String path) throws Exception {             
    // "path" is what I want
}

推荐