2
我有一個Java應用程序,打開瀏覽器並瀏覽到執行一些重定向的遠程servlet。另外,java應用程序在開放端口上實例化Jetty服務器,並等待servlet將瀏覽器重定向到它。我已經驗證了servlet指示瀏覽器重定向到的URL是正確的(即類似於http://localhost:54321/callback),但我從來沒有在實現接收重定向的具體AbstractHandler的請求處理程序中遇到斷點。我在Windows環境下運行,但我不知道這是什麼引起我的悲哀......在Windows中的碼頭
下面是我使用的LocalServerReceiver實現:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
public class LocalServerReceiver {
class CallbackHandler extends AbstractHandler {
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
if (!CALLBACK_PATH.equals(target)) {
return;
}
writeLandingHtml(response);
response.flushBuffer();
((Request) request).setHandled(true);
String error = request.getParameter("error");
if (error != null) {
// TODO Do something.
}
synchronized (LocalServerReceiver.this) {
LocalServerReceiver.this.notify();
}
}
private void writeLandingHtml(HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println("<body>");
doc.println("<script type='text/javascript'>");
doc.println("window.setTimeout(function() {");
doc.println(" window.open('', '_self', ''); window.close(); }, 1000);");
doc.println("if (window.opener) { window.opener.checkToken(); }");
doc.println("</script>");
doc.println("</body>");
doc.println("</html>");
}
}
private static final String CALLBACK_PATH = "/callback";
private Server _server;
public String getRedirectUrl() throws Exception {
int port = getUnusedPort();
_server = new Server(port);
for (Connector c : _server.getConnectors()) {
c.setHost("localhost");
}
_server.addHandler(new CallbackHandler());
_server.start();
return "http://localhost:" + port + CALLBACK_PATH;
}
public void waitForResponse() {
try {
wait();
} catch (InterruptedException e) {
// Should not happen
}
}
public void stop() throws Exception {
if (_server != null) {
_server.stop();
_server = null;
}
}
private static int getUnusedPort() throws IOException {
Socket s = new Socket();
s.bind(null);
try {
return s.getLocalPort();
} finally {
s.close();
}
}
}
如果您直接從瀏覽器訪問http:// localhost:54321/callback,您是否在擊中斷點? – Santosh 2012-02-19 04:49:15
不幸的是,不 - 我曾嘗試過,但無濟於事...... – hatboyzero 2012-02-19 14:10:39