Servlet过滤器 - 更改URL不起作用

时间:2014-07-27 18:03:16

标签: java tomcat servlets

我有一个GWT应用程序,其URL为.../Organizer.html。我也想从网址.../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适用于... /组织者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

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

1 个答案:

答案 0 :(得分:0)

如果目标是能够通过任一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不在应用程序的根目录,则可能需要修改这些路径。