Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doGet called twice jetty server

Tags:

java

jetty

i am using an embedded jetty server within the java application. But the doGet() method is being called twice. Also it is being called as a result of this (method.equals(METHOD_GET)) condition within the service method of the httpservlet class.

I tried to do a request using both the chrome and explorer but I had the same result.

can anyone see the reason for the doget being called twice..

public class HelloServlet extends HttpServlet{
  private String greeting="Hello World";
    public HelloServlet(){}
    public HelloServlet(String greeting)
    {
        this.greeting=greeting;
        System.out.println("started the server" + greeting);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>"+greeting+"</h1>");
        response.getWriter().println("session=" + request.getSession(true).getId());
        count = count+1;
        System.out.println(count);
        response.getWriter().println("count=" + count);
        response.flushBuffer();
    }
}

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

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    System.out.println("about to start the servlets");
    context.addServlet(new ServletHolder(new HelloServlet()),"/*");
   context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
   context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");

    server.start();
    System.out.println("started the servlets");
    server.join();
}
}
like image 227
vjk Avatar asked Jul 21 '11 22:07

vjk


1 Answers

When you request a page with a browser, it also requests an icon. For instance, a request to http://foo.com would also request http://foo.com/favicon.ico. That's what puts the little icon in your address bar to help you identify sites. It's also the source of your second request to the servlet. Try adding this line to your servlet:

System.out.println("request URI=" + request.getRequestURI());
like image 181
Ryan Stewart Avatar answered Nov 06 '22 03:11

Ryan Stewart