0

我有一个 javax.servlet.Filter 类,我想重定向 url。问题是当我打电话时

httpResponse.sendRedirect("http://myurl/login.jsp")
return;

它不会重定向到那里。我可以从 firebug 网络控制台看到请求匹配正确的 url,但页面没有改变,当前地址栏 url 保持不变。

该请求看起来有效。

Request URL:http://myurl/login.jsp
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:7001
Referer:http://myurl/index.jsp
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Language:en-US
Content-Length:764
Content-Type:text/html; charset=ISO-8859-1
Date:Fri, 27 Apr 2012 16:49:55 GMT
X-Powered-By:Servlet/3.0 JSP/2.2

响应包含 login.jsp 的内容

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
...
</body>
</html>

我试过使用

request.getRequestDispatcher("/login.jsp").forward(request, response);

这根本行不通,正如我在 Firebug 中看到的那样,它请求我当前所在的 url。

4

3 回答 3

1

发送重定向时不要打电话。否则,过滤器仍将继续对初始 URL 的请求,并且每次您尝试重定向chain.doFilter()时,您的服务器日志都会充满异常。IllegalStateException: response already committed

另请参阅此相关答案:java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been commited

于 2012-04-27T16:27:14.077 回答
0

初始化响应流(例如 response.getWriter())后,重定向不起作用:

对我来说,以下代码失败:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("incoming request :{}", request.getRequestURL());
    boolean failed;
    try {
         // do something
        failed = processGetRequest(request, response.getWriter());
    } catch (Exception e) {
        log.error("Error during collecting resource data -> redirect to root");
        failed = true;
    }

    if (failed) {
        response.setHeader("Location", "http://www.somewhere.de" );
        // 301 Moved Permanently
        // 307 Temporary Redirect
        response.setStatus( HttpServletResponse.SC_MOVED_PERMANENTLY);

    } else {
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

但是如果我在临时缓冲区中准备数据(替换 processGetRequest())并稍后打开编写器,它就可以工作.....

于 2012-05-22T17:27:40.307 回答
0

我正在重定向来自 CometD 的请求,它实际上并没有将我发送到任何地方。必须对 GET 请求进行重定向。

于 2012-05-23T18:16:17.510 回答