How to call servlet through a JSP page

jsp, servlets

Solution

First put the JSP page anywhere in `/WEB-INF` folder so that it's impossible to accidentally open the JSP page individually without invoking the Servlet first. E.g. `/WEB-INF/result.jsp`.

Then create a Servlet which does something like following in `doGet()` method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

And put this line in `/WEB-INF/result.jsp`.

<p>The result is ${result}</p>

Now call the Servlet by the URL which matches the URL pattern as defined in its `@WebServlet` annotation or in its `<url-pattern>` configuration in `web.xml`, e.g. `/servletURL`: http://example.com/contextname/servletURL.

If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form `action`.

<form action="servletURL" method="post">

Its `doPost()` method will then be called.

See also:

- Servlets info page - Contains a hello world

- Generate an HTML Response in a Java Servlet

- How to call servlet class from HTML form

- Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

- How do I pass current item to Java method by clicking a hyperlink or button in JSP page?

- Design Patterns web based applications

Problem

I would like to call a Servlet through a JSP page. What is the method to call?

Original source

Related problems