Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Java Serverletes

Java serverlets

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Java Serverletes

Java serverlets

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java serverletes:

Background

the background and advantages of servlets


1. Web Browsers and Servers Cooperation:
o When a user enters a Uniform Resource Locator (URL) into a browser, the browser
generates an HTTP request to the appropriate web server.
o The web server maps this request to a specific file and returns it in an HTTP response
to the browser.
o The HTTP header in the response indicates the content type using Multipurpose
Internet Mail Extensions (MIME). For example, HTML pages have a MIME type of
text/html.
2. Dynamic Content and Database Interaction:
o Dynamic content involves generating web pages on-the-fly based on real-time data.
o Consider an online store that stores information (items, prices, availability, orders) in
a database.
o To make this information accessible to customers, the web pages must be
dynamically generated to reflect the latest database data.
3. Common Gateway Interface (CGI) and Its Limitations:
o In the early days of the Web, servers used CGI to dynamically construct pages.
o CGI involved creating a separate process for each client request, which was resource-
intensive (CPU and memory).
o CGI programs were written in languages like C, C++, or Perl.
o However, CGI suffered from performance issues due to process creation overhead
and database connection management.
4. Advantages of Servlets:
o Performance: Servlets execute within the web server’s address space, avoiding the
need for separate processes per request.
o Platform Independence: Servlets are written in Java, making them platform-
independent.
o Security: The Java security manager enforces restrictions to protect server resources.
o Full Java Functionality: Servlets can use Java class libraries, communicate with
applets, databases, and other software via sockets and RMI.
In summary, servlets offer improved performance, platform independence, security, and access to
Java’s rich functionality compared to CGI. They are a powerful tool for building dynamic web
applications.

Life cycle of a servlet based on the provided text:

1. Initialization (init( )):


o When a servlet is first loaded into memory, the server invokes the init( ) method.
o Initialization parameters can be passed to the servlet during this phase for
configuration.
o This method sets up any necessary resources for the servlet.
2. Request Processing (service( )):
o Upon receiving an HTTP request, the web server maps it to a specific servlet.
o The server then calls the service( ) method of that servlet.

1
o In this phase:
▪ The servlet processes the HTTP request.
▪ It can read data provided in the request (e.g., query parameters, form data).
▪ It formulates an HTTP response to send back to the client.
▪ The servlet remains in the server’s address space and handles subsequent
requests.
▪ The service( ) method is called for each HTTP request.
3. Cleanup and Unloading (destroy( )):
o If the server decides to unload the servlet (based on server-specific algorithms), it
calls the destroy( ) method.
o The destroy( ) method releases any allocated resources (e.g., file handles).
o Important data may be saved to a persistent storage before the servlet is removed.
In summary, the servlet life cycle involves initialization, request processing, and eventual cleanup.
Servlets provide dynamic functionality within the server’s address space, handling client requests
efficiently.

Servlet development options:


1. Servlet Containers:
o To create servlets, you need access to a servlet container or server.
o Two popular options are:
▪ Glassfish: Provided by Oracle as part of the Java EE SDK. It is supported by
NetBeans.
▪ Tomcat: An open-source product maintained by the Apache Software
Foundation. It can also be used with NetBeans.
o Both Glassfish and Tomcat are widely available and serve as platforms for running
servlets.
2. IDEs and Command-Line Tools:
o While Integrated Development Environments (IDEs) like NetBeans and Eclipse can
streamline servlet development, this chapter focuses on command-line tools.
o IDEs differ in how they handle servlet development and deployment.
o For consistency, the instructions here assume the use of command-line tools, which
work for most readers regardless of their development environment.
3. Tomcat Usage:
o Tomcat is chosen for the examples in this chapter due to its simplicity for running
servlets using only command-line tools and a text editor.
o It is widely available and doesn’t require downloading and installing an IDE just for
servlet experimentation.
o Even if you’re using an environment like Glassfish, the fundamental concepts
presented here still apply, albeit with minor differences in testing preparation.
In summary, servlet development options include choosing a servlet container (such as Glassfish or
Tomcat) and deciding whether to use IDEs or command-line tools. Regardless of the environment,
understanding the core concepts remains essential.

2
The process of setting up and using Tomcat for servlet development
1. Downloading and Installing Tomcat:
o To create and test servlets, you’ll need a servlet container or server like Apache
Tomcat.
o Extract the downloaded zip file to a suitable location on your system.
2. Compiling Servlets:
o Tomcat provides a .jar file called servlet-api.jar containing necessary class files for
servlet development.
o Locate servlet-api.jar in the TOMCAT_HOME\lib directory (where TOMCAT_HOME is
the Tomcat installation directory).
o Compile your servlets using the javac command. For example:
o javac HelloWorldServlet.java -classpath "C:\apache-tomcat-7.0.47-windows-
x64\apache-tomcat-7.0.47\lib\servlet-api.jar"
o This generates the .class file containing the bytecode for your servlet.
3. Setting Up the Directory Structure:
o Create the following directory structure under the webapps subdirectory of Tomcat:
o TOMCAT_HOME\webapps\net\WEB-INF\classes
o Place the compiled HelloWorldServlet.class file in the
TOMCAT_HOME\webapps\net\WEB-INF\classes directory.
4. Configuring web.xml:
o Edit the web.xml file located in:
o TOMCAT_HOME\webapps\net\WEB-INF
o Add the servlet’s name and mapping:
o <servlet>
o <servlet-name>HelloServlet</servlet-name>
o <servlet-class>HelloServlet</servlet-class>
o </servlet>
o <servlet-mapping>
o <servlet-name>HelloServlet</servlet-name>
o <url-pattern>/servlet/HelloServlet</url-pattern>
o </servlet-mapping>
5. Running the Servlet:
o Start Tomcat by running the startup.bat or startup.sh script in the bin directory.
o Access the servlet using the URL:
o http://localhost:8080/net/servlet/HelloServlet
By following these steps, you’ll be able to create, compile, and deploy servlets using Tomcat. Feel
free to experiment with the sample servlets provided by Tomcat to get started!

simple servlet
1. Creating and Compiling the Servlet Source Code:
o A servlet is a Java program executed within a web container (such as Apache
Tomcat).
o It handles client requests and server responses.
o The example servlet, HelloServlet, is a subclass of GenericServlet.
o The service() method (inherited from GenericServlet) processes requests.
o It takes a ServletRequest (for reading client data) and a ServletResponse (for
formulating the response).

3
o The setContentType("text/html") sets the MIME type for the HTTP response (HTML
in this case).
o The getWriter() method obtains a PrintWriter to write content to the client.
o The servlet responds with a simple HTML message: <B>Hello!</B>.
2. Deployment and Configuration:
o Compile the HelloServlet.java source code.
o Place the HelloServlet.class file in the proper Tomcat directory (as described earlier).
o Add HelloServlet to the web.xml file (deployment descriptor) to configure its
behavior.
3. Starting Tomcat:
o Ensure that Tomcat is running before executing the servlet.
4. Requesting the Servlet:
o Open a web browser and enter the URL:
▪ http://localhost:8080/examples/servlets/servlet/HelloServlet
o Alternatively, use the IP address 127.0.0.1:
▪ http://127.0.0.1:8080/examples/servlets/servlet/HelloServlet
o The browser will display the output of the servlet, showing the bolded string
“Hello!”.

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!</B>");
pw.close();
}
}

In summary, servlets provide a powerful way to handle client-server communication, and the
example demonstrates a basic servlet setup and execution.

Reading Servlet Parameters


When building web applications using Java servlets, it’s common to need information from client
requests. The ServletRequest interface provides methods to read the names and values of
parameters included in a client request. Let’s break down the process using an example.

Example Overview

1. We have two files for this example:

o PostParameters.html: Defines an HTML form with two labels (Employee and Phone)
and corresponding text fields. The form submits data to a servlet via an HTTP POST
request.

o PostParametersServlet.java: A servlet that processes client requests and extracts


parameter values.

4
2. HTML Form (PostParameters.html):
o <html>
o <body>
o <center>
o <form name="Form1" method="post"
action="http://localhost:8080/examples/servlets/servlet/PostPar
ametersServlet">
o <table>
o <tr>
o <td><b>Employee</td>
o <td><input type="textbox" name="e"
size="25" value=""></td>
o </tr>
o <tr>
o <td><b>Phone</td>
o <td><input type="textbox" name="p"
size="25" value=""></td>
o </tr>
o </table>
o <input type="submit" value="Submit">
o </form>
o </center>
o </body>
o </html>
o

o The form specifies an action URL


(http://localhost:8080/examples/servlets/servlet/PostParametersServlet) where the
servlet will handle the submitted data.

o Users can input an employee name and phone number.

3. Servlet (PostParametersServlet.java):

o The service() method is overridden to process client requests.

o We retrieve an enumeration of parameter names using


request.getParameterNames().

o For each parameter, we output its name and value to the client.

4. Testing the Example:


o import java.io.*;
o import java.util.*;
o import javax.servlet.*;
o
o public class PostParametersServlet extends GenericServlet {
o public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
o // Get the PrintWriter to write the response.
o PrintWriter pw = response.getWriter();
o
o // Get an enumeration of parameter names.
o Enumeration<String> parameterNames = request.getParameterNames();
o
o // Display parameter names and values.
o while (parameterNames.hasMoreElements()) {
o String paramName = parameterNames.nextElement();
o pw.print(paramName + " = ");
o String paramValue = request.getParameter(paramName);

5
o pw.println(paramValue);
o }
o
o pw.close();
o }
o }
o

o Compile the servlet and copy it to the appropriate directory.

o Update the web.xml file as needed.

o Follow these steps:

1. Start Tomcat (if not already running).

2. Open the web page (PostParameters.html) in a browser.

3. Enter an employee name and phone number in the text fields.

4. Submit the form.

5. Result:

o The browser will display a dynamically generated response by the servlet, showing
the parameter names and their corresponding values.

Remember, this example demonstrates how to read parameters from an HTTP POST request. You can
adapt this approach to handle other types of data in your servlets.

handling HTTP GET requests


1. Handling HTTP GET Requests:
o When a user submits a form on a web page, an HTTP GET request is triggered.
o The example consists of two files: ColorGet.html (the web page) and
ColorGetServlet.java (the servlet).
o In ColorGet.html, a form is defined with a select element (dropdown) and a submit
button. The form’s action parameter specifies a URL, which identifies the servlet to
process the GET request.
o The servlet, ColorGetServlet.java, overrides the doGet() method to handle any
incoming HTTP GET requests.
o It uses the getParameter() method of HttpServletRequest to retrieve the user’s
selection (in this case, the chosen color).
o The servlet then formulates a response.
2. ColorGet.html (Web Page):
o The HTML form contains:
▪ A select element (<select>) for choosing a color (options: Red, Green, Blue).
▪ A submit button (<input type="submit">).
o The form’s action points to the servlet’s URL:
http://localhost:8080/examples/servlets/servlet/ColorGetServlet.
3. ColorGetServlet.java (Servlet):
o The doGet() method processes HTTP GET requests:
▪ Retrieves the selected color using request.getParameter("color").
▪ Sets the response content type to “text/html”.

6
▪ Writes the selected color to the response using PrintWriter.
▪ Closes the writer.
o Compile the servlet, copy it to the appropriate directory, and update the web.xml
file.
4. Testing the Example:
o Start Tomcat (if not already running).
o Open the web page in a browser.
o Select a color (e.g., Red).
o Submit the form.
o The browser displays the dynamically generated response from the servlet.
o The URL sent to the server includes the query string:
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color=Red.
Remember that parameters for an HTTP GET request are part of the URL’s query string. In this case,
the user’s selection (e.g., “Red”) is included in the URL when submitting the form.

<!DOCTYPE html>
<html>
<head>
<title>Color Selection</title>
</head>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>

Serverlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ColorGetServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();

7
pw.println("<b>The selected color is: " + color + "</b>");
pw.close();
}
}

Handling HTTP POST requests


1. Handling HTTP POST Requests:
o When a user submits a form on a web page, an HTTP POST request is triggered.
o The example consists of two files: ColorPost.html (the web page) and
ColorPostServlet.java (the servlet).
o ColorPost.html is similar to ColorGet.html, but with a few differences:
▪ The method parameter in the form tag explicitly specifies the POST method.
▪ The action parameter points to a different servlet:
http://localhost:8080/examples/servlets/servlet/ColorPostServlet.
o The servlet, ColorPostServlet.java, overrides the doPost() method to handle
incoming HTTP POST requests.
o It uses the getParameter() method of HttpServletRequest to retrieve the user’s
selection (in this case, the chosen color).
o The servlet then formulates a response.
2. ColorPost.html (Web Page):
o The HTML form contains:
▪ A select element (<select>) for choosing a color (options: Red, Green, Blue).
▪ The form’s method attribute specifies POST.
▪ The form’s action points to the servlet’s URL.
3. ColorPostServlet.java (Servlet):
o The doPost() method processes HTTP POST requests:
▪ Retrieves the selected color using request.getParameter("color").
▪ Sets the response content type to “text/html”.
▪ Writes the selected color to the response using PrintWriter.
▪ Closes the writer.
4. Testing the Example:
o Compile the servlet.
o Perform the same steps as described in the previous section to test it (start Tomcat,
open the web page, select a color, and submit the form).
o The browser will display the dynamically generated response from the servlet.
Remember that parameters for an HTTP POST request are included in the request body, rather than
the URL. In this case, the user’s selection (e.g., “Red”) is sent as part of the form data when
submitting the form.

<!DOCTYPE html>
<html>
<head>
<title>Color Selection</title>
</head>
<body>
<center>

8
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlets/servlet/ColorPostServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ColorPostServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<b>The selected color is: " + color + "</b>");
pw.close();
}
}

handling cookies
1. AddCookie.html (Web Page):
o This HTML page allows users to specify a value for the cookie named “MyCookie.”
o It contains:
▪ A text field where users can enter a value.
▪ A submit button.
o When the submit button is pressed, the value from the text field is sent to
AddCookieServlet via an HTTP POST request.

<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlet/AddCookieServlet">
<b>Enter a value for MyCookie:</b>
<input type="textbox" name="data" size="25" value="">

9
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
2. AddCookieServlet.java (Servlet for Setting Cookies):
o This servlet processes the submission from AddCookie.html.
o It retrieves the value of the parameter named “data” (the user’s input).
o Creates a Cookie object named “MyCookie” with the retrieved value.
o Adds this cookie to the header of the HTTP response using the addCookie() method.
o Writes a feedback message to the browser indicating that the cookie has been set.
o import java.io.*;
o import javax.servlet.*;
o import javax.servlet.http.*;
o
o public class AddCookieServlet extends HttpServlet {
o public void doPost(HttpServletRequest request, HttpServletResponse response)
o throws ServletException, IOException {
o String data = request.getParameter("data");
o // Create cookie.
o Cookie cookie = new Cookie("MyCookie", data);
o // Add cookie to HTTP response.
o response.addCookie(cookie);
o // Write output to browser.
o response.setContentType("text/html");
o PrintWriter pw = response.getWriter();
o pw.println("<B>MyCookie has been set to");
o pw.println(data);
o pw.close();
o }
o }
3. GetCookiesServlet.java (Servlet for Retrieving Cookies):
o This servlet displays cookie values.
o It invokes the getCookies() method to read any cookies included in the HTTP GET
request.
o For each cookie, it retrieves the name and value using the getName() and getValue()
methods.
o The servlet then writes these cookie names and values to the HTTP response.
o import java.io.*;
o import javax.servlet.*;
o import javax.servlet.http.*;
o
o public class GetCookiesServlet extends HttpServlet {
o public void doGet(HttpServletRequest request, HttpServletResponse response)
o throws ServletException, IOException {
o // Get cookies from header of HTTP request.
o Cookie[] cookies = request.getCookies();
o // Display these cookies.

10
o response.setContentType("text/html");
o PrintWriter pw = response.getWriter();
o pw.println("<B>");
o for (int i = 0; i < cookies.length; i++) {
o String name = cookies[i].getName();
o String value = cookies[i].getValue();
o pw.println("name = " + name + "; value = " + value);
o }
o pw.close();
o }
o }

4. Testing the Example:


o Compile the servlets.
o Copy them to the appropriate directory and update the web.xml file.
o Follow these steps to test the example:
1. Start Tomcat (if not already running).
2. Display AddCookie.html in a browser.
3. Enter a value for “MyCookie.”
4. Submit the web page.
o You’ll observe a feedback message displayed by the browser.
o Next, request the following URL via the browser:
http://localhost:8080/examples/servlets/servlet/GetCookiesServlet.
o The name and value of the cookie will be displayed in the browser.

Session tracking and how it’s implemented


1. Session Tracking:
o HTTP is a stateless protocol, meaning each request is independent, and the server
doesn’t inherently remember previous interactions.
o However, some applications require maintaining state information across multiple
requests from the same client.
o Sessions provide a mechanism to save and share data between interactions.
2. Using Sessions in Servlets:
o The getSession() method of HttpServletRequest creates or retrieves an HttpSession
object.
o An HttpSession can store bindings (associations) between names and objects.
o Key methods for managing session attributes:
▪ setAttribute(name, value): Binds an object to a name.
▪ getAttribute(name): Retrieves the object associated with a name.
▪ getAttributeNames(): Returns all attribute names.
▪ removeAttribute(name): Removes an attribute.
o Session state is shared among all servlets associated with a specific client.
3. Example: DateServlet
o The DateServlet illustrates session usage:
▪ It gets the current session using request.getSession(true). If no session
exists, a new one is created.
▪ Retrieves the date attribute (if it exists) associated with the name “date.”
▪ If the attribute exists, it displays the last access date and time.

11
▪ Creates a Date object representing the current date and time.
▪ Binds this new Date object to the “date” attribute using setAttribute("date",
date).
▪ Displays the current date and time.
4. Behavior:
o When you first request this servlet, the browser displays the current date and time.
o On subsequent invocations, two lines are displayed:
▪ The first line shows the date and time when the servlet was last accessed
(retrieved from the session attribute).
▪ The second line shows the current date and time (updated and stored in the
session).
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DateServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);

// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");

// Display date/time of last access.


Date date = (Date) hs.getAttribute("date");
if (date != null) {
pw.print("Last access: " + date + "<br>");
}

// Display current date/time.


date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

12

You might also like