How to call a servlet on jsp page load?

java, jsp, servlets

Solution

You should do it the other way round. Call the servlet by its URL and let it present the JSP. That's also the normal MVC approach (servlet is the controller and JSP is the view).

First put the JSP file in `/WEB-INF` folder so that the enduser can never "accidently" open it by directly entering its URL in browser address bar without invoking the servlet. Then change the servlet's `doGet()` accordingly that it forwards the request to the JSP.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...

    request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}

Open it by

http://localhost:8080/contextname/HelloServlet

Note that you can of course change the URL pattern in servlet mapping to something like `/hello` so that you can use a more representative URL:

http://localhost:8080/contextname/hello

See also:

- Our Servlets tag info page

Problem

I have below servlet. I would like to call the servlet on `jsp` page load. How can I do that? servlet: `SomeServlet.java` ``` <servlet> <servlet-name>Hello</servlet-name> <servlet-class>SomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> ``` How can I write corresponding jsp to invoke the servlet on jsp page load. Also I need to get the result from servlet and display in the same jsp. Can I send result back to `jsp`? Thanks!

Original source

Related problems