Can I call a servlet from JSP file without using a HTML form?
You can use the doGet()
method of the servlet to preprocess a request and forward the request to the JSP. Then just request the servlet URL instead of JSP URL by browser.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Do your preprocessing task here.
// Then display JSP (with results?).
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
If you map this servlet in web.xml
on an url-pattern
of /someurl
, then you can invoke the servlet and display the JSP by http://example.com/context/someurl.
See also
You will need to use RequestDispatcher's Methods forward/include depending on your requirement to achieve same.
In JSP you need to use following tags:
The element allows you to include either a static or dynamic file in a JSP file. The results of including static and dynamic files are quite different. If the file is static, its content is included in the calling JSP file. If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP file.
e.g.
<jsp:include page="/HandlerServlet" flush="true">
The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. The lines in the source JSP file after the element are not processed.
e.g.
<jsp:forward page="/servlet/ServletCallingJsp" />
Check Advanced JSP Sample : JSP-Servlet Communication:
http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html
Sure you can, simply include it in your action
in the form
. But you have to write the correct doPost
or doGet
to handle the request!
If you want to call a particular servlet method than you also use Expression Language. For example, you can do something like:
Servlet
ForexTest forexObject = new ForexTest();
request.setAttribute("forex", forexObject);
JSP
<body bgcolor="#D2E9FF">
Current date : ${forex.rate}
</body>