我有一个Jetty WebServlet,可以连接用C#和android编写的各种客户端。这当前使用简单的HTTP工作,但我有兴趣将其升级到HTTPS。为了尝试这样做,我正在创建这样的服务器:
public static void main(String[] args){
SslContextFactory contextFactory = new SslContextFactory();
contextFactory.setKeyStorePath("keystore.jks");
contextFactory.setKeyStorePassword("********");
SslConnectionFactory connectionFactory = new SslConnectionFactory(contextFactory, org.eclipse.jetty.http.HttpVersion.HTTP_2_0.toString());
Server server = new Server(8080);
ServerConnector connector = new ServerConnector(server, connectionFactory);
connector.setPort(8443);
server.addConnector(connector);
ServletContextHandler servletCH = new ServletContextHandler();
servletCH.setContextPath("/");
servletCH.addServlet(ScheduleWebSocketServlet.class, "/schedule");
server.setHandler(servletCH);
server.start();
server.join();
}
这似乎是错误的。 ScheduleWebSocketServlet类如下:
@WebServlet(name = "Schedule WebSocketServlet", urlPatterns = {"/schedule"})
public static class ScheduleWebSocketServlet extends WebSocketServlet{
private static final long serialVersionUID = 5838283767965540728L;
public void doGet(HttpServletRequest request, HttpServletResponse response){
try {
response.getWriter().println("<h1>Hello World</h1>");
} catch (IOException e) {
Main.LogError(e);
}
}
@Override
public void configure(WebSocketServletFactory arg0) {
arg0.register(ScheduleWebSocket.class);
}
}
所以我的问题是将WebServlet与HTTPS一起使用的正确方法是什么?
非常感谢您的帮助
答案 0 :(得分:0)
好的,我的问题原来是我必须创建带有http和https配置的ServerConnections,给他们详细信息并将它们分配给服务器。毕竟,我只需要启动它们,这应该在服务器启动后完成
Server server = new Server();
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
HttpConfiguration https_config = new HttpConfiguration();
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
SslContextFactory contextFactory = new SslContextFactory();
contextFactory.setKeyStorePath("keystore.jks");
contextFactory.setKeyStorePassword("changeit");
SslConnectionFactory connectionFactory = new SslConnectionFactory(contextFactory, org.eclipse.jetty.http.HttpVersion.HTTP_1_1.toString());
ServerConnector https = new ServerConnector(server, connectionFactory, new HttpConnectionFactory(https_config));
https.setPort(8443);
https.setIdleTimeout(50000);
server.setConnectors(new Connector[]{http, https});
ServletContextHandler servletCH = new ServletContextHandler();
servletCH.setContextPath("/");
servletCH.addServlet(ScheduleWebSocketServlet.class, "/schedule");
server.setHandler(servletCH);
server.start();
http.start();
https.start();
server.join();