url字符串java spring mvc中属性中的斜杠

iswrvxsc  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(300)

我正在为我的工作开发一个JavaSpringMVC应用程序。我们总是有一个问题,当我们有斜杠在网址。我们使用的是Java8和Tomcat7。在“当前页面”的jsp中,我们有以下href:

<td style="vertical-align: middle;"><a id="column" style="color: #EB9316" href="${pageContext.request.contextPath}/user/other-page/${c.property}/${dto.year}">${c.property}</a></td>

这里我们传递对象的属性和年份作为参数。在“otherpage”中,我们获取属性和年份并过滤db上的对象c。问题是property是一个字符串,它的名称中有时会有斜杠,比如“thing/otherthing”,我们必须同时使用year和property在另一个页面中进行过滤。年是从网页的上下文中取出来的,它不给问题。
遵循“other page”java控制器中的代码:

@GetMapping("/user/other-page/{property}/{year}")
public String homeUserOtherPageFilter(@PathVariable String property, @PathVariable Integer year, RedirectAttributes attributes) {
    property= URLDecoder.decode(property, "UTF-8");
    attributes.addFlashAttribute("property", property);
    attributes.addFlashAttribute("year", year);
    return "redirect:/user/other-page";
}

名称中的斜杠导致404错误。我尝试在“当前页”java控制器中使用以下代码对斜杠进行编码。

try {
        for (chapter chapter: chapters) {
            chapter.setProperty(URLEncoder.encode(chapter.getProperty(), "UTF-8")); 
        }
    } catch (UnsupportedEncodingException e){
        logger.debug("Url encode failed ", e);
    }

但这仍然不起作用,即使使用url编码,tomcat也会给我错误404,甚至无法到达其他页面控制器进行解码。如果我在“当前页”的2020页上,单击“thing/otherthing”链接,则会出现准确的错误:
请求的资源[/application/user/other page/2020/thing%2otherthing]不可用
当然,对于没有斜线的房产,一切都很好。我做错什么了?

zsohkypk

zsohkypk1#

编辑:我解决了这个问题。出于某种奇怪的原因,tomcat不喜欢将“/”转换为“%2f”,但由于某种我不知道的原因,它接受将“/”编码为“%252f”,这是通过对参数进行两次编码而得到的。所以我不得不把当前页面中的代码改成java控制器

try {
    for (chapter chapter: chapters) {
        chapter.setProperty(URLEncoder.encode(URLEncoder.encode(chapter.getProperty(), "UTF-8"), "UTF-8")); 
    }
} catch (UnsupportedEncodingException e){
    logger.debug("Url encode failed ", e);
}

现在一切正常。

相关问题