简体   繁体   中英

Embedded jetty 9 doesn't work for @Webservlet

I'm using java 11 and embedded jetty 9 foor my javaEE application,I'm trying to use @Websevlet annotation to publish my servlet but it doesn't work i don't know why. My start class java

import org.eclipse.jetty.annotations.AnnotationConfiguration;

import org.eclipse.jetty.server.Server;

import org.eclipse.jetty.webapp.*;

public class Start  {

    public static  void main(String[] args) throws Exception {
        Server server = new Server(80);

        WebAppContext wacHandler = new WebAppContext();
        wacHandler.setConfigurations(new Configuration[]
                {
                        new AnnotationConfiguration(),
                        new WebInfConfiguration(),
                        new WebXmlConfiguration(),
                        new MetaInfConfiguration(),
                        new FragmentConfiguration(),
                        new JettyWebXmlConfiguration()
                });
        server.setHandler(wacHandler);

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

My hello world class

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( "/getservlet")
public class ServletX extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hi there..</h1>");
    }

}

I don't have a web.xml configuration ,Should i do?

If ServletX is in the war file, meaning it's in WEB-INF/classes/ archive directory, then the configuration you have declared (specifically the AnnotationConfiguration ) will perform a bytecode scan of the WAR file and load the @WebServlet annotation.

Also note that the WebAppContext will need point to this WAR file, which your code examples do not do.

WebAppContext wacHandler = new WebAppContext();
waxHandler.setWar("/path/to/myapp.war");
// ... more setup

But! if the ServletX is not in the WAR file, but is instead housed with your embedded-jetty Start class, then you'll need to expose the servlet container to be scanned by the bytecode scanning step.

You can always turn on DEBUG/FINE level logging for the named logger org.eclipse.jetty and see the activity being performed with regards to the deployment and bytecode scanning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM