Back to: Java Servlets Tutorials
Java Servlet Communication with Examples
In this article, I am going to discuss Java Servlet Communication with Examples. Please read our previous article where we discussed how to Create Servlet Application using Eclipse IDE. At the end of this article, you will understand the following pointers in detail.
- Why Servlet Communication?
- Browser-Servlet Communication
- Sending Error Messages
- Request Redirection
- Request Redirection by using Hyperlinks
- Request Redirection by setting Response Headers
- Request Redirection by using Send Redirect Mechanisms
- Web Component Communication
- Applet Servlet Communication
Servlet Communication in Java Based Web Application
In general, web application deployment is not at all suggestible to provide the complete application logic within a single web resource, it is suggestible to distribute the complete application logic over multiple web resources.
In the above context, to execute the application we must require communication between all the web resources, for this, we have to use Servlet Communication. In the web application, we are able to provide servlet communication in the following three ways:
Browser-Servlet Communication
In web applications, we will use a browser as a client at the client machine, from the browser we will send a request to a servlet available at the server, where the servlet will be executed and generate some response to the client browser.
In the above process, we have provided communication between the client browser and servlet. So that sending a normal request from the client to the server and getting a normal response from the server to the client is an example of Browser-Servlet Communication.
Sending Error Messages
As part of the web application execution, if the container identifies any exception or error then the container will send the respective error message to be a client in its standalone template.
As part of our application, if we want to send our own messages to the client in the container defined template, we have to use the following method from the response.
public void sendError(int statuscode, String description) where statuscode may be 5xx.
Program: Send Error App
Registrationform.html
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <font color='red'> <h2>Registration Form</h2> </font> <form method="POST" action="./reg"> <table> <tr> <td>User Name</td> <td><input type="text" name="uname" /></td> </tr> <tr> <td>User Age</td> <td><input type="text" name="uage" /></td> </tr> <tr> <td>User Email</td> <td><input type="text" name="uemail" /></td> </tr> <tr> <td>User Mobile</td> <td><input type="text" name="umobile" /></td> </tr> <tr> <td><input type="submit" name="Registration" /></td> </tr> </table> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>senderrorapp</display-name> <welcome-file-list> <welcome-file>Registrationform.html</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>ServletExample</display-name> <servlet-name>RegistrationServlet</servlet-name> <servlet-class>com.servlet.RegistrationServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegistrationServlet</servlet-name> <url-pattern>/reg</url-pattern> </servlet-mapping> </web-app>
RegistrationServlet.java
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RegistrationServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType ("text/html"); PrintWriter out = response.getWriter (); String uname = request.getParameter ("uname"); int uage = Integer.parseInt (request.getParameter ("uage")); String uemail = request.getParameter ("uemail"); String umobile = request.getParameter ("umobile"); if (uage < 18 || uage > 30) { response.sendError (504,"User Age is not sufficient for this requirement!"); } else { out.print ("<body>"); out.print ("<font color='red'>"); out.print ("<h2>Registration Form</h2>"); out.print ("</font>"); out.print ("<table border='1'>"); out.print ("<tr><td>User Name</td><td>" + uname + "</td></tr>"); out.print ("<tr><td>User Age</td><td>" + uage + "</td></tr>"); out.print ("<tr><td>User Email</td><td>" + uemail + "</td></tr>"); out.print ("<tr><td>User Mobile</td><td>" + umobile + "</td></tr>"); out.print ("</table></body></html>"); } } catch (Exception e) { e.printStackTrace (); } } }
Output
Insert your details here
If you will enter age < 18, then you will get the following output
Request Redirection
The process of bypassing the request from one web application to another web application is called Request Redirection. In web applications, we are able to achieve Request Redirection in the following 3 ways:
- Request Redirection by using Hyperlinks.
- Request Redirection by setting Response Headers.
- Request Redirection by using Send Redirect Mechanism.
Request Redirection by using Hyperlinks:
In this mechanism, when we send a request to the first application some resources will be executed and generated a hyperlink at the client browser as a response. By getting a hyperlink at the client browser we have to click on it and we have to send another request to the new web application. By executing some resources at the new web application, the required response will be generated to the client browser.
Drawback:
In this Request Redirection mechanism, the user may or may not click the generated hyperlink at the client browser after sending the first request. So that this mechanism won’t provide a guarantee to achieve Request Redirection.
Request Redirection by setting Response Headers:
In this mechanism, first, we will send a request to the first web application, where the first web application will set the Redirectional Status Code to Status Line field and new web application URI to Location Response Header.
When the Response Format reached the client, then the client will pick up Redirectional status code value from the Status-Line field, with this client browser will pick up Location Response Header value i.e. new web application URL then the client browser will send a new request to the new web application. By executing some resources at the new web application, the required response will be generated at the client machine.
To represent Request Redirection HttpServletResponse has introduced the following two constants:
public static final int SC_MOVED_TEMPORARILY;
public static final int SC_MOVED_PERMANENTLY;
To set a particular status code value to Response Header we will use the following method.
public void setStatus(int statuscode)
To set a particular Response Header value in Response Format we have to use the following method.
public void setHeader(String header_name, String value)
Drawback:
To perform Request Redirection, if we use this approach then every time, we have to set Redirectional status code and new web application URL to Location Response Header.
Request Redirection by using Send Redirect Mechanisms
To perform Request Redirection, if we use Send Redirect Mechanism no need to use Hyperlinks, not required to set status code and Response Header values to the Response Format, but we need to use the following method.
public void sendRedirect(String url)
Program: Send Redirect App
welcome.html
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body bgcolor='red'> <center><b><font size='7' color='black'> <br><br> Welcome to Vodafone </font> </b></center> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>sendredirectapp</display-name> <welcome-file-list> <welcome-file>welcome.html</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>ServletExample</display-name> <servlet-name>HutchServlet</servlet-name> <servlet-class>com.servlet.HutchServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HutchServlet</servlet-name> <url-pattern>/hutch</url-pattern> </servlet-mapping> </web-app>
HutchServlet.java
package com.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HutchServlet */ @WebServlet ("/HutchServlet") public class HutchServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect ("http://localhost:8081/vodafone/welcome.html"); } }
Output
Web Component Communication
The process of providing communication between more than one web component available at the server machine is called Web Component Communication.
In general, web-component communication is available in between Servlet-Servlet, Servlet-Jsp, Servlet-HTML, Jsp-Jsp, Jsp-Servlet, Jsp-HTML, and so on. In web applications, we are able to achieve web-component communication in the following 2 ways:
- Include Mechanism
- Forward Mechanism
If we want to perform the above mechanisms internally, we must use the RequestDispatcher object. So that both include and forward mechanisms are commonly called Request Dispatching Mechanisms.
To achieve web-component communication in web applications we have to use the following 2 steps:
- Get the RequestDispatcher object.
- Apply either include or forward mechanism by using the respective methods.
Step-1: Request Dispatcher object:
Request Dispatcher is an object, it will provide a very good environment either to include the target resource response into the present resource or to forward the request from the present resource to the target resource. To get the RequestDispatcher object we will use the following two ways:
ServletContext
getRequestDispatcher(_)method
getNamedDispatcher(_)method
ServletRequest
getRequestDispatcher(_)method
Step-2: Apply either Include mechanism or Forward mechanism to achieve Web-Component Communication:
To represent Include and Forward mechanisms RequestDispatcher has provided the following methods:
public void include(ServletRequest req, servletResponse res) throws SE, IOE
public void forward(ServletRequest req, servletResponse res) throws SE, IOE
Applet Servlet Communication
In general, in a web application, we will use the browser as a client, we will send request from the client browser to a servlet available at the server, by executing the respective servlet some response will be sent back to the client browser.
Similarly, in the case of Applet Servlet Communication, we will use the applet as a client, from the applet only we will send requests to the respective servlet available at the server machine, whereby executing the respective servlet the required response will be generated and send back to the applet.
In the above situation, the communication which we provided between applet and servlet is called Applet-Servlet communication. If we want to achieve Applet-Servlet Communication in web applications we have to use the following steps:
Step-1: Prepare a URL object with the respective URL.
URL u = new URL(“http://localhost8081/loginapp/login?uname=abc&upwd=abc123”);
Step-2: Establish a connection between applet and server by using URLConnetion object.
URLConnection uc = u.openConnection();
Step-3: Send a request from an applet to the servlet.
uc.setDoInput(true);
uc.setDoOutput(true);
Note: If we do the above step a request will be sent to the servlet from the applet where the container will execute the respective servlet, generate the response and send that response to the applet client. But the response is available on the URLConnection object.
Step-4: Get InputStream from URLConnection
InputStream is = uc.getInputStream();
Step-5: Read the response from InputStream.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String res = br.readLine();
In the next article, I am going to discuss the ServletRequest Interface. Here, in this article, I try to explain Servlet Communication in Java. I hope you enjoy this Servlet Communication in Java article.