Tomcat服务器向Servlet发出3个请求

Tomcat服务器向Servlet发出3个请求

本文介绍了Tomcat服务器向Servlet发出3个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的doGet方法

@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);
    }
}

当我启动服务器(Tomcat)时,它将在浏览器中打开http://localhost:8080,并且doGet方法被调用了3次.它会打印"Hello" 3次.

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.

知道为什么会这样吗?

推荐答案

Tomcat会"ping"该邮件. Web应用程序的根URL,以验证其是否已成功部署.如果您使用IDE来管理服务器,则它可能会执行其他检查.但是,它被调用了3次却没有一两次,也许确实很奇怪.

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.

结果如何?

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

通过将其显式映射到/的URL模式上,您使其成为了Web应用程序的默认servlet !每个与任何显式注册的servlet的URL模式都不匹配的请求都将在该servlet中结束.通常,这些请求会击中CSS,JS和图像文件之类的静态资源.通常,servlet容器已经提供了默认的servlet.举例来说,Tomcat具有 DefaultServlet

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.

因此,假设index.jsp文件又引用了CSS和JS文件,那么对/home的单个请求将调用servlet 3次(浏览器将对该CSS和JS文件获取不可消化的信息index.jsp的HTML输出,而不是所需的CSS和JS输出.

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).

摆脱/ URL模式.这是拥有主页"的错误方式. servlet.而是将<welcome-file>home</welcome-file>添加到web.xml.除非您真的知道自己在做什么,否则不要从容器中接管默认的Servlet作业.

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.

  • Difference between / and /* in servlet mapping url pattern
  • How load servlet on index.jsp

这篇关于Tomcat服务器向Servlet发出3个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:21