Jetty的入門html
1、開發環境web
Eclipse 4.3.1apache
Maven 3.1瀏覽器
Jetty 9.0.6.v20130930服務器
Jetty的下載地址:app
http://download.eclipse.org/jetty/eclipse
2、新建Maven項目webapp
一、新建webapp項目jettytest.maven
二、在Pom.xml中配置Jetty dependency和pluginide
<!-- Jetty begin --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>9.0.6.v20130930</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <version>9.0.6.v20130930</version> </dependency> <!-- Jetty end --> <plugins> <!-- compiler插件, 設定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <showWarnings>true</showWarnings> </configuration> </plugin> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> </plugin> </plugins>
3、新建SimpleServlet和JettyServer
一、新建一個簡單的Servlet:SimlpeServlet
public class ServletServer { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new SimpleServlet()), "/firstservlet"); context.addServlet(new ServletHolder(new SimpleServlet("Hello, this is my first Jetty servlet!")), "/secondservlet"); server.start(); server.join(); } }
二、新建JettyServer
public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = -8470943914753284049L; private String message = "Hello World!"; public SimpleServlet() { } public SimpleServlet(String message) { this.message = message; } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>" + message + "</h1>"); if (name != null) { response.getWriter().println("名字:" + name + "</br>"); } if (password != null) { response.getWriter().println("密碼:" + password + "</br>"); } } }
4、運行結果
一、運行JettyServer,啓動Jetty服務器。控制檯出現下列信息表示服務器啓動成功:
2013-10-12 22:20:36.281:INFO:oejs.Server:main: jetty-9.0.6.v20130930
2013-10-12 22:20:36.312:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@18c2661{/,null,AVAILABLE}
2013-10-12 22:20:36.406:INFO:oejs.ServerConnector:main: Started ServerConnector@838143{HTTP/1.1}{0.0.0.0:8080}
二、打開瀏覽器輸入地址:http://127.0.0.1:8080/firstservlet。出現下列運行結果:
三、還能夠輸入地址:http://127.0.0.1:8080/secondservlet。出現下列運行結果:
5、大功告成!