是否可以在没有web.xml文件的情况下在jetty上运行servlet?

时间:2014-07-08 13:28:00

标签: java servlets jetty embedded-jetty

我想使用Jetty运行servlet,但只能使用java代码(嵌入式jetty)。 这是我的两个班级:

ExampleServer.java:

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;

/**
 * Created by Administrator on 7/8/14.
 */
public class ExampleServer {

    public static void main(String[] args) throws Exception {
        Server server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);

        server.setConnectors(new Connector[]{connector});

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/hello");
        context.addServlet(HelloServlet.class, "/");

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
        server.setHandler(handlers);

        server.start();
        server.join();
    }
}

HelloServlet.java:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 7/8/14.
 */
public class HelloServlet extends HttpServlet{

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>Hello from HelloServlet</h1>");
        response.getWriter().println("session=" + request.getSession(true).getId());
    }
}

现在,当我尝试访问http://localhost:8080/hello时,我收到以下错误:

HTTP错误:500

访问/ hello /时遇到问题。原因是:

java.lang.IllegalStateException: No SessionManager

关于如何解决这个问题的任何想法? 谢谢。

1 个答案:

答案 0 :(得分:1)

你好像错过了一步,

context.addServlet(HelloServlet.class, "/");
context.setSessionHandler(new org.eclipse.jetty.server.session.SessionHandler());

通常,配置文件用于默认设置(或使用JDBCSessionManager表示集群)。此外,您只需要这个,因为您调用了request.getSession(true).getId()