How to call servlet through a JSP page
You can use RequestDispatcher
as you usually use it in Servlet
:
<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
request.setAttribute("msg","HI Welcome");
rd.forward(request, response);
%>
Always be aware that don't commit any response before you use forward
, as it will lead to IllegalStateException
.
You could use <jsp:include>
for this.
<jsp:include page="/servletURL" />
It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. 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 in /WEB-INF/result.jsp
<p>The result is ${result}</p>
Now call the Servlet by the URL which matches its <url-pattern>
in web.xml
, e.g. http://example.com/contextname/servletURL.
Do note that the JSP file is explicitly placed in /WEB-INF
folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.
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
- How to call servlet class from HTML form
- How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
- Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
- Design Patterns web based applications