Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

servlet result display in jsp page

Tags:

jsp

servlets

How to forward the servlet output to jsp page?

That means the result will be displayed in the JSP page.

like image 968
pavan Avatar asked Dec 01 '09 06:12

pavan


People also ask

How can we retrieve data from servlet and display in 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.

How can a servlet call a JSP page?

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.

Can we use servlet and JSP together?

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.

How servlet and JSP interact with each other?

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.


2 Answers

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.

like image 184
BalusC Avatar answered Sep 21 '22 07:09

BalusC


getServletConfig().getServletContext()
    .getRequestDispatcher("/jsp/myfile.jsp").forward(request,response);

is VOID type, it can not return RequestDispatcher rd.

like image 41
mika Avatar answered Sep 22 '22 07:09

mika