我们可以在Main方法Java类中运行HTTPServlet吗

Ash*_*hok 1 java servlets

我正在看Java中的简单Servlet的示例代码。

在此示例中,Servlet由WEB-INF / web.xml文件条目启动

<servlet-class>com.mkyong.ServletDemo1</servlet-class>



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>Servlet Name For Demo1</servlet-name>
        <servlet-class>com.mkyong.ServletDemo1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Servlet Name For Demo1</servlet-name>
        <url-pattern>/Demo1</url-pattern>
    </servlet-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)

我可以在main()方法中的Java应用程序中启动(com.mkyong.ServletDemo1),并调用一个方法。可能吗 ?

谢谢您的帮助。

van*_*nje 5

对的,这是可能的。您可以使用轻便的Servlet容器Jetty。可以像这样将Jetty嵌入您自己的应用程序中(此示例直接来自Jetty文档):

public class MinimalServlets
{
    public static void main( String[] args ) throws Exception
    {
        // Create a basic jetty server object that will listen on port 8080.
        // Note that if you set this to port 0 then a randomly available port
        // will be assigned that you can either look in the logs for the port,
        // or programmatically obtain it for use in test cases.
        Server server = new Server(8080);

        // The ServletHandler is a dead simple way to create a context handler
        // that is backed by an instance of a Servlet.
        // This handler then needs to be registered with the Server object.
        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);

        // Passing in the class for the Servlet allows jetty to instantiate an
        // instance of that Servlet and mount it on a given context path.

        // IMPORTANT:
        // This is a raw Servlet, not a Servlet that has been configured
        // through a web.xml @WebServlet annotation, or anything similar.
        handler.addServletWithMapping(HelloServlet.class, "/*");

        // Start things up!
        server.start();

        // The use of server.join() the will make the current thread join and
        // wait until the server is done executing.
        // See
        // http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
        server.join();
    }

    @SuppressWarnings("serial")
    public static class HelloServlet extends HttpServlet
    {
        @Override
        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>");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)