gpt4 book ai didi

java - 覆盖 HttpServletRequest 中的 getContextPath(用于 URL 重写)

转载 作者:行者123 更新时间:2023-11-30 12:01:45 24 4
gpt4 key购买 nike

我有一个网络应用程序,我想扩展它以支持具有新 URL 的多种语言。例如,www.example.com/home.do 保持英语,但 www.example.com/es/home.do 是西类牙语。我的第一个想法是创建一个过滤器,它将传入的 url 重写为/es/home.do 到/home.do(并在请求中设置区域设置);这很好用。过滤器用 HttpServletRequestWrapper 包装 ServletRequest,它覆盖 getContextPath() 以返回语言:

class FakeContextRequest extends HttpServletRequestWrapper {

private String context = "";
FakeContextRequest(HttpServletRequest request, String context) {
super(request);
// snip some validation code
this.context = request.getContextPath() + context;
}
@Override
public String getContextPath() {
return this.context;
}
}

我的过滤器转发到适当的请求如下:

FakeContextRequest fr = new FakeContextRequest(request, lang);
fr.getRequestDispatcher(newResourceName).forward(fr, response);

我的问题是下一个 servlet 没有正确转发。下一个 servlet(通常是 Struts ActionServlet)转发到 JSP(通常使用 Struts Tiles);当我到达 JSP 时,HttpServletRequest 已被包装多次,并且有问题的对象报告上下文为空(根上下文,这是应用程序实际部署的位置)。

我希望重写上下文,以便我所有已经存在的上下文感知代码可以自动将语言插入到编写的 URL 中。这可能吗?

编辑: 我通过使用包装的 HttpServletResponse 而不是包装的 HttpServletRequest 解决了我的问题;我在 response.encodeURL() 方法中重写了 URL。

最佳答案

我不确定重写 getContextPath() 是否足以解决您的问题。如果 Struts 在幕后调用 ServletContext.getContextPath(),或者使用 getRequestURI() 等,会怎样?

关于java - 覆盖 HttpServletRequest 中的 getContextPath(用于 URL 重写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/260252/

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