jetty 使用servlet

在嵌入式Jetty中,有时候我们想运行一些的Servlet,此时就需要创建创建Context,然后让自己的Servlet运行在这些ServletContext中。

package hb.jetty;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


class MyServlet extends HttpServlet{
	@Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        System.out.println("doGet MyServlet");  
    }  
  
    @Override  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        System.out.println("doPost MyServlet");  
        super.doPost(req, resp);  
    }  
    
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    	System.out.println("MyServlet");
    }
}
package hb.jetty;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


class MyServlet2 extends HttpServlet{
	@Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        System.out.println("doGet MyServlet2");  
    }  
  
    @Override  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        System.out.println("doPost MyServlet2");  
        super.doPost(req, resp);  
    }  
    
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    	System.out.println("MyServlet2");
    }
}
package hb.jetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class ServletContextServer {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Server server = new Server(8080);  
		  
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);  
        //相当于工程目录,如果是myweb,则http://localhost:port/myweb/
        context.setContextPath("/");
        server.setHandler(context);  
  
        // http://localhost:8080/servlet1  
        context.addServlet(new ServletHolder(new MyServlet()), "/servlet1");  
        // http://localhost:8080/servlet1/2   
        context.addServlet(new ServletHolder(new MyServlet2()), "/servlet1/2");  
          
        server.start();  
        server.join();  
	}

}

猜你喜欢

转载自hbiao68.iteye.com/blog/1936895
今日推荐