I would like to call a Servlet through a JSP page. What is the method to call?
In this mode, JSP pages are used for the presentation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page. The controller is also responsible for deciding to which JSP page to forward the request.
JSP(s) are compiled into Servlet(s); every JSP is-a Servlet. Does it work when you move intro. jsp into the WebContent folder and change to request.
Calling a Servlet Programmatically To include another servlet's output, use the include() method from the RequestDispatcher interface. This method calls a servlet by its URI and waits for it to return before continuing to process the interaction. The include() method can be called multiple times within a given servlet.
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.
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
.
there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.
Example: web.xml:
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:
<jsp:forward page="/hello"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With