How to forward the servlet output to jsp page?
That means the result will be displayed in the JSP page.
1) First create data at the server side and pass it to a JSP. Here a list of student objects in a servlet will be created and pass it to a JSP using setAttribute(). 2) Next, the JSP will retrieve the sent data using getAttribute(). 3) Finally, the JSP will display the data retrieved, in a tabular form.
If any type of exception occurs while executing an action, the servlet catches it, sets the javax. servlet. jsp. jspException request attribute to the exception object, and forwards the request to the error JSP page.
One best practice that combines and integrates the use of servlets and JSP pages is the Model View Controller (MVC) design pattern, discussed later in this article. Don't overuse Java code in HTML pages: Putting all Java code directly in the JSP page is OK for very simple applications.
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.
You normally don't use a servlet to generate HTML output. You normally use JSP/EL for this. Using out.write
and consorts to stream HTML content is considered bad practice. Better make use of request attribtues.
For example:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Object data = "Some data, can be a String or a Javabean";
request.setAttribute("data", data);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Map this in web.xml on an <url-pattern>
of for example /page
. Place the JSP in /WEB-INF
to prevent direct access. Then in the JSP you can use EL (Expression Language) to access scoped attributes:
<p>The data from servlet: ${data}</p>
Call the servlet by http://example.com/context/page
. Simple as that. This way you control the output and presentation at one place, the JSP.
getServletConfig().getServletContext()
.getRequestDispatcher("/jsp/myfile.jsp").forward(request,response);
is VOID
type, it can not return RequestDispatcher
rd.
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