1

我有一个带有两个参数 long 和 String 的 Spring 控制器:

@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);
        //...
    }
//...

如果我这样调用它:

http://localhost:8080/webarch/webpage/1/blahblah

一切皆好:

webpageId=1
webpageAddress=blahblah

但是如果我用斜杠传递字符串参数(在这种情况下是 URL 地址):

http://localhost:8080/webarch/webpage/1/https://en.wikipedia.org/wiki/Main_Page

我收到一个错误:

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'

如何传递这样的参数?

4

2 回答 2

3

那么错误是由弹簧控制器映射引起的,当Spring看到像这样的url时

http://localhost:8080/webarch/webpage/1/https://en.wikipedia.org/wiki/Main_Page

它不“知道”“ https://en.wikipedia.org/wiki/Main_Page ”应该作为参数映射到“{webpageId}/{webpageAddress}”映射,因为每个斜杠都被解释为更深层次的控制方法映射。它寻找控制器方法映射,(webpage/1/http:{anotherMapping}/wiki{anotherMapping}/Main_Page{anotherMapping})这种映射显然不是由“{webpageId}/{webpageAddress}”处理的

编辑

根据您的评论,您可以尝试这样的事情

@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..
}

使用弹簧 4.2.1

SomeParsing 应该使用一些正则表达式来仅提取 URL '变量'

于 2015-11-12T01:07:10.470 回答
1

只需对 URL 中的所有特殊字符进行编码。

https://en.wikipedia.org/wiki/Main_Page

变成这样:

https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMain_Page

您可以将其作为 URL 参数传递而不会出现任何问题。解码是自动完成的,因此如果您在控制器中将参数作为变量访问,它包含已解码的 URL,您可以使用它而无需任何转换。

有关 URL 编码的更多信息:https ://en.wikipedia.org/wiki/Percent-encoding

于 2015-11-12T06:28:07.673 回答