Jetty配置到项目
- 拷贝lib/jsp和lib下的所有jar包到项目中。
- 在工程中创建文件夹jetty/etc、jetty/contexts
- 拷贝jetty包中的jetty.xml和webdefault.xml到etc中,拷贝contexts中的test.xml到contexts中(貌似这个步骤可以不要,以后再试试)
- 在项目中创建jsp目录
- 新建一个servlet,名称为MyServlet.java
- 新建一个类JettyDemo.java.
- 以上两个类内容如下,访问http://localhost:9999/ss.do测试servlet是否好用。访问http://localhost:9999/index.jsp测试jsp是否好用。
JettyDemo.java
package org.jetty.demo;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.webapp.WebAppContext;
public class JettyDemo {
public static void main(String[] args) {
Server server = new Server();
try {
Connector conn = new SocketConnector();
conn.setPort(9999);
server.setConnectors(new Connector[]{conn});
ContextHandlerCollection handler = new ContextHandlerCollection();
ServletContextHandler servlethandler = new ServletContextHandler();
servlethandler.addServlet(MyServlet.class, "*.do");
handler.addHandler(servlethandler);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setResourceBase("./jsp");
webapp.setDefaultsDescriptor("./jetty/etc/webdefault.xml");
handler.addHandler(webapp);
server.setHandler(handler);
// XmlConfiguration conf = new XmlConfiguration("./src/jetty/etc/jetty.xml");
// conf.configure(server);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyServlet.java
package org.jetty.demo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -6197211740957851460L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet");
resp.getWriter().write("hello");
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doPost");
super.doPost(req, resp);
}
}
以上完毕。