gpt4 book ai didi

java - 带有包含 URL 的字符串参数的 RequestMapping

转载 作者:行者123 更新时间:2023-11-29 03:03:07 25 4
gpt4 key购买 nike

我有一个带有两个参数 long 和 String 的 Spring Controller :

@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'

如何传递这样的参数?

最佳答案

这个错误是由 spring Controller 映射引起的,当 spring 看到这样的 url 时

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

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

编辑

根据您的评论,您可以尝试这样的操作

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

使用 Spring 4.2.1

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

关于java - 带有包含 URL 的字符串参数的 RequestMapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com