Address of this article: http://blog.csdn.net/kongxx/article/details/7218776
One of the most common usages of Jetty is to embed Jetty into its own Java application. At this time, Jetty runs as a background servlet container and accepts http requests from users. The following is the simplest usage of embedding Jetty.
1. First use Maven to create a java project
mvn archetype:generate -DgroupId=com.google.code.garbagecan.jettystudy -DartifactId=jettystudy -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
2. Modify the pom file, add or modify the compilation and dependency parts
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.google.code.garbagecan.jettystudy</groupId> <artifactId>jettystudy</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>jettystudy</name> <url>http://maven.apache.org</url> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <inherited>true</inherited> <configuration> <source>1.6</source> <target>1.6</target> <debug>true</debug> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.eclipse.jetty.aggregate</groupId> <artifactId>jetty-all</artifactId> <version>8.0.4.v20111024</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
3. Create a Server class to start the Jetty server and process the request sent by the browser through a HelloHandler;
package com.google.code.garbagecan.jettystudy.sample1; import org.eclipse.jetty.server.Server; public class MyServer { public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler (new HelloHandler ()); server.start(); server.join(); } }
4. Create a Handler class to handle all client requests
package com.google.code.garbagecan.jettystudy.sample1; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; public class HelloHandler extends AbstractHandler { public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled (true); response.getWriter().println("<h1>Hello World</h1>"); response.getWriter().println("Request url: " + target); } }
5. Run the MyServer class, and then visit http://localhost:8080/ through the browser, you can see "Hello World!" and the requested url.