Unit-III Final Java Servlets and XML Notes
Unit-III Final Java Servlets and XML Notes
The entire life cycle of a Servlet is managed by the Servlet container which uses the
javax.servlet.Servlet interface to understand the Servlet object and manage it
Let's see the life cycle of the servlet
1. The servlet is initialized by calling the init() method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
//init() method
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException
{
//initialization code
}
}
3. Request handling using - service() method
The service() method of the Servlet is invoked to inform the Servlet about the client requests.
● This method uses ServletRequest object to collect the data requested by the client.
● This method uses ServletResponse object to generate the output content.
The deployment descriptor is an xml file From which Web Container gets the information about the
servlet to be invoked.
web.xml file
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
Servlets handles form data parsing automatically using the following methods depending on the
situation
1. getParameter() −
a. Retrieves the value of a single request parameter as a String. If the parameter does not
exist, it returns null.
b. You call the request.getParameter() method to get the value of a form parameter.
c. This method should be used on the parameter that has only one value
Example :
HTML CODE :
<input type="text" name="name" />
<input type="text" name="phone" />
HTML OUTPUT :
Example :
HTML CODE Here language common name to all Checkbox
<input type="checkbox" name="language" value="java" />Java
<input type="checkbox" name="language" value="python" />Python
<input type="checkbox" name="language" value="sql" />SQL
<input type="checkbox" name="language" value="php" />PHP
HTML OUTPUT :
3. getParameterNames() −
a. Retrieves an Enumeration of all parameter names in the request. This can be useful
for iterating over all parameters.
b. Call this method if you want a complete list of all parameters in the current request.
Note :
1. Parameters are always treated as String values.
2. If you need to handle other data types, you will need to convert or parse them manually (e.g.,
using Integer.parseInt() for integer values).
HelloForm.html
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form> </body>
</html>
HelloForm.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/HelloForm ")
public class HelloForm extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Web.xml
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class> HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
1. Create the HelloForm.html into Apache Tomcat Server under the folder
<Tomcat-installationdirectory>/webapps/ROOT directory.
2. Compile the HelloForm.java servlet after the compilation HelloForm.class file is created which
would have to copy this class file in under
Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes
Compile the Program using the servlet package as below from command prompt
1. Session is a conversational state between client and server and it can consist of multiple requests
and responses between client and server.
2. Sessions are used to track user interactions and maintain state across multiple requests.
3. The HttpSession interface provides a way to store and retrieve data for a particular user during
their interaction with a web application.
1. Cookies
1. Cookies are small pieces of data sent from the server and stored on the client's browser.
2. They are a common method for session tracking and are automatically included with each
request to the server.
3. Each web client can be assigned a unique session ID by a web server.
4. Cookies are used to manage the ongoing user session.
How It Works:
● The server sends a cookie containing the session ID to the client's browser.
● The client's browser stores the cookie and sends it back with each subsequent request.
● The server reads the session ID from the cookie to identify the session.
● Cookie information is stored in the cache of the browser.Now, if a request is sent by the same
user, a cookie is added with the request by default. Thus the server recognizes the request
coming from the same user and the session is maintained.
1. Persistent – It is valid for multiple sessions. It is not removed from the browser each time
when the user closes the browser. It is removed only if the user logs out or signs out.
2. Non-persistent – It is valid for a single session only. It is removed each time the user closes the
browser.
Constructors
Cookie()
Cookie(String name, String value)
Method Description
public void setMaxAge(int expiry) Sets the max age of the cookie in seconds
1. Hidden form field is another technique which is used for session tracking of a client. In this
technique, a hidden field is used to store client state.
2. Hidden form field can also be used to store session information for a particular client.
3. Hidden form field is used to store session information of a client.
4. Hidden form fields are used to pass data from the client to the server without displaying it to the
user.
ServletOne.java
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/index")
public class ServletOne extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("user");
out.print("Welcome " + userName);
out.print("<form action='servletTwo'>");
out.print("<input type='hidden' name='uname' value='" + userName + "'><br>");
out.print("<input type='submit' value='Get Value from Hidden Field'>");
out.print("</form>");
out.close();
}
catch (Exception e)
{
System.out.println(e);
}
Web.xml
<web-app>
<servlet>
<servlet-class>ServletOne</servlet-class>
<servlet-name>servletOne</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>servletOne</servlet-name>
<url-pattern>/servletOne</url-pattern>
</servlet-mapping>
<servlet>
<servlet-class>ServletTwo</servlet-class>
<servlet-name>servletTwo</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>servletTwo</servlet-name>
<url-pattern>/servletTwo</url-pattern>
</servlet-mapping>
</web-app>
● URL rewriting is a technique used to maintain session state between a client and a server without
relying on cookies.
● Url rewriting is a process of appending or modifying any url structure while loading a page.
● In Java Servlets, URL rewriting is commonly used to pass session information when cookies are
not supported or disabled
● URL rewriting involves appending session information directly to the URL
● If your browser does not support cookies, URL rewriting provides you with another session
tracking alternative.
http://demo/servlet?Name=Nitin&Address=Nashik
Query string is a name value pair separated using an equal = sign, a name/value pair is separated
from another name/value pair using the ampersand (&). Query string always should start from
Question mark (?). From a Servlet, we can use getParameter(), getParameterNames() methods to
obtain a name value pair.
Example :
index.html
<html>
<body>
<form action="/FirstServlet" method="post">
Enter Personal Details:<br /> Name:<input type="text" name="name" /><br />
<input type="submit" value="go" />
/form>
</body>
</html>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/index")
public class FirstServlet extends HttpServlet {
From the above FirstServlet.java servlet program the url rewriting is done by appending the
name information into out.print("<form action='servlet2?name="+name+"' method='post'> ");
1. A session is simply the limited interval of time in which two systems communicate with each
other.
2. HttpSession is a Java class used in servlets to manage user sessions in a web application
3. It allows you to store user-specific data between HTTP requests, which is useful for maintaining
state and user-specific information across multiple interactions with the server.
How to create sessions with a unique session id for each user in java servlet.
For this, servlets provide an interface called ‘HttpSession’ Interface.
The following diagram explains how Http Sessions work in servlets:
Container creates a session id for each user.The container uses this id to identify the particular
user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
2. Storing Data: You can store data in the session using setAttribute(), where the data is stored
as key-value pairs.
Java Code :
session.setAttribute("username", "Nitin");
3. Retrieving Data: To retrieve data from the session, use getAttribute() with the key used when
storing the data.
Java Code :
String username = (String) session.getAttribute("username");
4. Invalidating a Session: You can invalidate a session when it is no longer needed (e.g., when a
user logs out) using the invalidate() method.
Java Code :
session.invalidate();
5. Session Timeout: Sessions have a timeout period which can be configured in the web
application's deployment descriptor (web.xml) or programmatically. The default timeout is
usually 30 minutes. After this period of inactivity, the session will be invalidated.
Web.xml
<session-config>
<session-timeout>15</session-timeout>
</session-config>
index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e); }
}
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet2</url-pattern>
</servlet-mapping>
</web-app>
To make sure that a servlet is thread safe, there are a few basic rules of thumb you must
follow:
Thread Safety:
● To ensure thread safety, servlets must be designed to handle concurrent access properly. This
often involves:
○ Avoiding the use of instance variables to store request-specific data, as multiple
threads might access and modify these variables simultaneously.
○ Using local variables within request-handling methods (e.g., doGet or doPost), as these
are thread-local and thus isolated from other threads.
○ Synchronizing access to shared resources, such as shared data structures or files, if they
are used.
SQL>USE testdb;
SQL> CREATE TABLE users (id INT, username VARCHAR(50), password VARCHAR(50);
Database (Mysql) and Java Servlet
Establish a database connection in a Java servlet, you'll need to follow several
steps.
2. Database Configuration
1. Store your database connection details, like URL, username, and password.
2. You can do this in a properties file or directly in your servlet for simplicity (though using a properties
file is more secure).
Database (Mysql) and Java Servlet
Index.html UI interface
<html>
<head>
<title>User Registration</title>
</head><body> <h1>User Registration</h1>
<form action="UserServlet" method="post">
<body>
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit"> Register </button>
</form>
</body>
</html>
Create a Servlet
Create a new Servlet to handle HTTP requests and interact with the MySQL database.
Here’s a simple example of a servlet that inserts a user into the users table:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/index")
public class UserServlet extends HttpServlet
{
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
private static final String JDBC_USER = "root"; // Your MySQL username
private static final String JDBC_PASSWORD = "password"; // Your MySQL password
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
PrintWriter out = response.getWriter();
// Execute the statement
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0)
{
out.println("User registered successfully!");
} else
{
out.println("User registration failed.");
}
// Clean up
statement.close();
connection.close();
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
University Question on XML Ask in Previous Years
Q. Explain XML with respect to XML declaration, DOM based XML Processing. 6M
i)XML namespace
ii)HTTP session
XML : XML documents and vocabularies
1. XML stands for Extensible Markup Language
2. XML was designed to store and transport data
3. XML was designed to be self-descriptive
4. XML is just information wrapped in tags
5. XML Does Not Use Predefined Tags
1. XML entities are special placeholders that represent characters that have specific meanings in
XML syntax or characters that cannot be easily typed.
2. They help ensure that the document is well-formed.
3. These are standard entities defined by XML that represent special characters:
All elements can have sub elements (child elements).
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
XML declaration
XML declaration
XML example
The following is an example of a simple XML file:
The programming interface to the DOM is defined by a set standard properties and
methods.
2. Methods are often referred to as something that is done (i.e. delete "book").
XML DOM Properties
These are some typical DOM properties:
CSS can be used to display the contents of the XML document in a clear and
precise manner.
In order to display the XML file using CSS, link XML file with CSS.
Below is the syntax for linking the XML file with CSS