spring 中带有 url-pattern 重定向的上下文路径 [英] Context path with url-pattern redirect in spring
问题描述
我对tomcat服务器上的路径和网址有点困惑,让我解释一下:
I'm having a bit of a puzzle with paths and urls on a tomcat server, let me explain:
我的tomcat webapp目录是:/server
My tomcat webapp directory is: /server
我已经在目录/server/myapp/subfolder 中部署了一个 spring 应用程序
I have deployed a spring application in directory /server/myapp/subfolder
这意味着我的上下文路径/server/myapp
This means my context path /server/myapp
我的 servlet 的 url-pattern 为/subfolder/*
My servlet has an url-pattern of /subfolder/*
可以通过 url http://server.com/myapp/subfolder/ 访问我的 servlet
My servlet can be reached at url http://server.com/myapp/subfolder/
在我的许多弹簧控制器中,我返回一个重定向:
In a many of my spring controllers i return a redirect:
return "redirect:/item/list";
这会将访问者重定向到 http://server.com/myapp/item/list
This redirects the visitor to http://server.com/myapp/item/list
这当然会导致 404,因为正确的 url 是:http://server.com/myapp/subfolder/item/list
This of course results in a 404 cause the right url is: http://server.com/myapp/subfolder/item/list
这可以很容易地解决,只需将所有内容都放在一个单独的 web 应用程序中或简单地删除 url-pattern.但两者都不可能,因为单独的 webapp 意味着不同的类加载器(导致其他系统出现问题),并且像/这样的 url-pattern 会与服务器上运行的其他应用程序发生冲突.
This can easily be solved by just putting everything is a separate webapp or simply removing the url-pattern. But both aren't possible because a separate webapp means a different class-loader (causes problem with other systems) and url-pattern like / will conflict with other applications running on the server.
我可以将重定向更改为redirect:/subfolder/item/list",这将修复重定向.
I can change my redirect to "redirect:/subfolder/item/list", that will fix the redirect.
是否有更好的解决方案,以便我不必在使用上下文路径的任何地方手动添加子文件夹/"?
Is there maybe a better solution so that i don't have to manually add "subfolder/" everywhere the contextpath is used?
推荐答案
最后我简单做了一个 util 函数:
In the end i simply made a util function:
public String redirect(String path){
return "redirect:/subfolder"+path;
}
有点 hacky,但它允许我在 url-pattern 更改时快速更改子文件夹".
Bit hacky, but it allows me to quickly change "subfolder" in case the url-pattern changes.
视图中的@url 标签也使用上下文路径,所以我创建了自己的@url 标签,将子文件夹"添加到上下文路径中.
The @url tag in the view also uses contextpath, so i created my own @url tag which adds "subfolder" to the contextpath.
现在春天似乎很开心,我再也没有任何 404 了.
Spring now seems happy, i don't get any 404's anymore.
这篇关于spring 中带有 url-pattern 重定向的上下文路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!