我需要取得web应用的根路径,却并不想在每个控制器方法中去用request.getContextPath去取得,看到很多文章说spring的监听器WebAppRootListener可以取得应用的根路径。
经过实际测试,该监听器取得的是应用根路径所对应的物理路径。这并不是我想要的。
我决定改写WebAppRootListener。
将在新的listener中将 String root = servletContext.getRealPath()改为 String root = servletContext.getContextPath()
然后在web.xml用此listener替换掉原来的WebAppRootListener就可以像使用WebAppRootListener一样取得应用的根路径了。
比如:http://127.0.0.1/test如果应用名为test,得到的路径为“/test”。