How to use RequestDispatcher include method


 

How to use RequestDispatcher include method

In this tutorial you will come to know that how include method of RequestDispatcher is used.

In this tutorial you will come to know that how include method of RequestDispatcher is used.

Description:

The interface RequestDispatcher object receive requests from the client and sends to file like servlet, html or jsp on the server.

There are two method of the RequestDispatcher one is forward and other is include. So forward send a request from a servlet to another resource like servlet, jsp, or html on the server and on the other hand the include method includes resource of file like servlet, jsp or html in the response.

Code :

MyServlet .java

package package1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("currently in the MyServlet ");

RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.include(request, response);

out.println("back to the MyServlet ");
out.println("</body>");
out.println("</html>");
}
}

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsp</title>
</head>
<body>
<h3> Message from the index.jsp </h3>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>package1.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>MyServlet</welcome-file>
</welcome-file-list>
</web-app>

Output:

currently in the MyServlet
Message from the index.jsp
back to the MyServlet

Ads