Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - Stop further processing when redirecting in a filter

I have URLRewirteFilter which checks if requested domain starts with www. and redirects to no-www url. How can I stop futher processing (invoking JSF app, call servlets etc.) when request is to be redirected? So far I have this:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String sn = req.getServerName().toLowerCase();
    if (sn.startsWith("www.")) {
        String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.reset();
        resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        resp.setHeader("Location", url);
    }
    chain.doFilter(request, response);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just either add a return statement to the end of the if

if (sn.startsWith("www.")) {
    String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    resp.setHeader("Location", url);
    return;
}
chain.doFilter(request, response);

or add an else

if (sn.startsWith("www.")) {
    String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    resp.setHeader("Location", url);
} else {
    chain.doFilter(request, response);
}

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...