JSP Servlets – How to Call Servlet Through JSP Page
jspservlets
I would like to call a Servlet through a JSP page. What is the method to call?
Best Answer
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.
Best Answer
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.And put this line in
/WEB-INF/result.jsp
.Now call the Servlet by the URL which matches the URL pattern as defined in its
@WebServlet
annotation or in its<url-pattern>
configuration inweb.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
.Its
doPost()
method will then be called.See also: