我有一个URL为.../Organizer.html的GWT应用程序。我也想从URL .../organizer访问它。因此,我决定用servlet过滤器中的覆盖的HttpServletRequestgetRequestURL()方法用包装器替换原始的getRequestURI()

过滤器代码:

String[] urlSplit = req.getRequestURL().toString().split("/");
String urlEnd = urlSplit[urlSplit.length -1];


if (urlEnd.equals(ORGANIZER_URL_ALTERNATIVE)){
    String newUrl = req.getRequestURL().toString().
            replace(ORGANIZER_URL_ALTERNATIVE, ORGANIZER_URL);
    String newUri = req.getRequestURI().toString().
            replace(ORGANIZER_URL_ALTERNATIVE, ORGANIZER_URL);
    request = new ChangeUrlRequest(req, newUrl, newUri);

}

//Just to check if it works
req =  (HttpServletRequest) request;
System.out.println(req.getRequestURL());
System.out.println(req.getRequestURI());

chain.doFilter(request, response);




请求包装器:

class ChangeUrlRequest extends HttpServletRequestWrapper {


    private StringBuffer newUrlBuffer;
    private String newUri;

    public ChangeUrlRequest(HttpServletRequest request,String newUrl, String newUri) {
        super(request);

        newUrlBuffer = new StringBuffer(newUrl);
        this.newUri = newUri;
    }

    @Override
    public StringBuffer getRequestURL() {
        return newUrlBuffer;
    }

    @Override
    public String getRequestURI() {
        return newUri;
    }

}


这按预期的方式工作,可以使用.../organizer并由.../Organizer.html代替

我现在遇到的问题是,无论我从浏览器访问... / organizer还是... / Organizer.html,即使URL / URI相同,也只有... / Organizer.html可以工作并且适用于... / organizer Tomcat抱怨找不到页面:HTTP状态404-/my-page/Organizer.html

上面代码中System.out的输出:

使用Organizer.html(有效):

网址:http://localhost:8080/my-page/Organizer.html
URI:/my-page/Organizer.html

与组织者一起(上面提到的404):

网址:http://localhost:8080/my-page/Organizer.html
URI:/my-page/Organizer.html

我是否需要覆盖或更改其他内容?

最佳答案

如果目标是能够通过任一URL访问应用程序,则可能有一个更简单的解决方案。您可以编写一个/organizer上可访问的servlet,并将请求转发到HTML页面,例如:

@WebServlet(urlPatterns="/organizer")
public class OrganizerServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Organizer.html");
        dispatcher.forward(request,response);
    }
}


请注意,如果/organizer/Organizer.html的路径不在应用程序的根目录中,则可能需要对其进行修改。

07-24 14:48