我在java应用程序中使用嵌入式jetty服务器。但是doGet()方法被调用了两次。此外,它也是httpservlet类的服务方法中的(method.equals(METHOD_GET))条件的结果。
我尝试使用chrome和explorer进行请求,但结果相同。
任何人都可以看到doget被调用两次的原因..
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();
}
}
答案 0 :(得分:7)
当您使用浏览器请求页面时,它还会请求一个图标。例如,对http://foo.com的请求也会请求http://foo.com/favicon.ico。这就是将小图标放在地址栏中以帮助您识别网站的原因。它也是您对servlet的第二个请求的来源。尝试将此行添加到您的servlet:
System.out.println("request URI=" + request.getRequestURI());