임베디트 부두 서버를 시작하는 가장 짧은 코드
-
06-07-2019 - |
문제
내장 된 부두 서버가 시작된 예제 코드를 작성하고 있습니다. 서버는 정확히 하나의 서블릿을로드하고 모든 요청을 서블릿에 보내고 LocalHost에서 듣습니다 : 80
지금까지 내 코드 :
static void startJetty() {
try {
Server server = new Server();
Connector con = new SelectChannelConnector();
con.setPort(80);
server.addConnector(con);
Context context = new Context(server, "/", Context.SESSIONS);
ServletHolder holder = new ServletHolder(new MyApp());
context.addServlet(holder, "/*");
server.start();
} catch (Exception ex) {
System.err.println(ex);
}
}
적은 코드/라인으로 똑같이 할 수 있습니까? (JETTY 6.1.0 사용).
해결책
static void startJetty() {
try {
Server server = new Server();
Connector con = new SelectChannelConnector();
con.setPort(80);
server.addConnector(con);
Context context = new Context(server, "/", Context.SESSIONS);
context.addServlet(new ServletHolder(new MyApp()), "/*");
server.start();
} catch (Exception ex) {
System.err.println(ex);
}
}
불필요한 공백을 제거하고 ServleTholder 생성을 인라인으로 이동했습니다. 5 줄이 제거되었습니다.
다른 팁
Spring ApplicationContext.xml에서 Jetty를 선언적으로 구성 할 수 있습니다.
http://roopindersingh.com/2008/12/10/spring-and-jetty-integration/
그런 다음 ApplicationContext.xml에서 서버 Bean을 검색하고 시작을 호출합니다.
((Server)appContext.getBean("jettyServer")).start();
부두와 관련된 통합 테스트에 유용합니다.
나는 도서관을 썼다. EasyJetty, 그것은 부두를 더 쉽게 포함시킬 수 있습니다. 그것은 Jetty API 위의 얇은 층일 뿐이며 실제로 가벼운 가중치입니다.
예제는 다음과 같습니다.
import com.athaydes.easyjetty.EasyJetty;
public class Sample {
public static void main(String[] args) {
new EasyJetty().port(80).servlet("/*", MyApp.class).start();
}
}
Jetty 8과 함께 작동 :
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext handler = new WebAppContext();
handler.setResourceBase("/");
handler.setContextPath("/");
handler.addServlet(new ServletHolder(new MyApp()), "/*");
server.setHandler(handler);
server.start();
}
}
Server server = new Server(8080);
Context root = new Context(server, "/");
root.setResourceBase("./pom.xml");
root.setHandler(new ResourceHandler());
server.start();
제휴하지 않습니다 StackOverflow