关闭

jetty 使用servlet

459人阅读 评论(0) 收藏 举报
分类:

在嵌入式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();  
	}

}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:313857次
    • 积分:8753
    • 等级:
    • 排名:第2259名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论