Pranav
Pranav

Reputation: 447

Tomcat server makes 3 requests to the servlet

Below is my doGet method

@WebServlet(
        name = "IndexServlet",
        urlPatterns={ "/", "/home" },
        initParams = { @WebInitParam(name = "sortBy", value = Constants.POPULAR) }
)
public class IndexServlet extends HttpServlet {

    private DataSource pool;

    @Override
    public void init() throws ServletException {
        String datasource_name = "jdbc/bookhive_db";
        try {
            //A JNDI Initial context to be able to lookup the DataSource
            InitialContext ctx = new InitialContext();
            pool = (DataSource) ctx.lookup("java:comp/env/" + datasource_name);
            if (pool == null)
                throw new ServletException("Unknown DataSource '" + datasource_name + "'");
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (NumberFormatException e) {
            page = 1;
        }

        String sortBy = request.getParameter("sortBy");
        if (sortBy == null || sortBy.isEmpty())
            sortBy = this.getInitParameter("sortBy");

        String query = getQuery(sortBy);
        Object[] params = {
                (page - 1) * Constants.RESULTS_PER_PAGE,
                Constants.RESULTS_PER_PAGE
        };

        JDBCService service = new JDBCService(pool);
        service.setQuery(query);
        service.setParams(params);
        List<Book> books = service.getBookDetails();


        System.out.println("HELLO");

        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
        dispatcher.forward(request, response);
    }
}

When I start the server (Tomcat), it opens http://localhost:8080 in browser and the doGet method gets called 3 times. It prints 'Hello' 3 times.

This only happen when I first start the server.

Any idea why this happens?

Upvotes: 1

Views: 245

Answers (2)

BalusC
BalusC

Reputation: 1108642

Tomcat will "ping" the root URL of the web application to verify if it's successfully deployed. If you're using an IDE to manage your server, then it may perform additional checks. It's however indeed strange that it's invoked three times and not one or perhaps two times.

What turns out?

@WebServlet(
    name = "IndexServlet",
    urlPatterns={ "/", "/home" },
    initParams = { @WebInitParam(name = "sortBy", value = Constants.POPULAR) })

With explicitly mapping it on the URL pattern of /, you made it the default servlet for the web application! Every single request which does not match the URL pattern of any explicitly registered servlet will end up in that servlet. Normally, it are those requests which hit static resources like CSS, JS and image files. Normally, the servletcontainer already provides a default servlet out the box. Tomcat for instance has the DefaultServlet for the very purpose.

So imagine that the index.jsp file is in turn referencing a CSS and a JS file, then a single request on /home will invoke the servlet three times (and the browser would for that CSS and JS file get the undigestable HTML output of the index.jsp instead of the desired CSS and JS output).

Get rid of the / URL pattern. This is the wrong way of having a "home page" servlet. Instead, add a <welcome-file>home</welcome-file> to the web.xml. Don't take over the default servlet job from the container unless you really know what you're doing.

See also:

Upvotes: 3

davidluckystar
davidluckystar

Reputation: 928

I think it may happen because you're starting your server from IDEA or Eclipse which checks whether your deployment is ok or not. I agree with Ulrich answer, you should call the url using curl or wget. And try starting the server not from IDE (if you are).

Upvotes: 1

Related Questions