KEMBAR78
UNIT - 3 Server Side Programming - CCS375 New | PDF | Http Cookie | Databases
0% found this document useful (0 votes)
3 views47 pages

UNIT - 3 Server Side Programming - CCS375 New

The document covers server-side programming concepts, focusing on Java Servlets, their architecture, lifecycle, and session management. It explains the role of servlets in web applications, the advantages of server-side programming, and various session tracking methods such as cookies and URL rewriting. Additionally, it provides code examples and details on JDBC for database connectivity.

Uploaded by

Vishal V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views47 pages

UNIT - 3 Server Side Programming - CCS375 New

The document covers server-side programming concepts, focusing on Java Servlets, their architecture, lifecycle, and session management. It explains the role of servlets in web applications, the advantages of server-side programming, and various session tracking methods such as cookies and URL rewriting. Additionally, it provides code examples and details on JDBC for database connectivity.

Uploaded by

Vishal V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

WEB TECHNOLOGIES – CCS375

UNIT - 3
SERVER SIDE PROGRAMMING
Servlets :
• Java Servlet Architecture
• Servlet Life Cycle
• Form GET and POST actions
• Session Handing
• Understanding Cookies
• DATABASE CONNECTIVITY : JDBC (Java Data Base Connectivity)
WEB APPLICATION
• A web application is an application accessible form the web.
• A web application is composed of web components like
Servlet, JSP, Filter, etc.
• And other elements such as HTML, CSS , and JavaScript.
• The web components typically exeute in Web Server and
• Respond to the HTTP REQUEST.
Why server side programming APPLICATION
Advantages of server side programs
Types of server side programs
The following are the different types of server side programs :
• Active Server Pages (ASP)
• Java Servlets
• Java Server Pages(JSP)
• Enterprise JavaBeans(EJB)
• PHP
What are servlets ?
SERVER – SIDE SCRIPTING
• Server – side scripting acts as an interface for the client
and also limit the user access the resources on web
server
• It can also collects the user’s characteristics in order to
customize response..
Server – side programming
• The Combination of
- HTML
- JavaScript
- DOM
is sometimes referred to as Dynamic HTML
(DHTML)
➢Web Pages that include scripting are often
called dynamic pages (vs. static)
Server – side programming
Server – Overviews
Hello world! servlet
Helloservlet
package sam; protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
import java.io.IOException; throws ServletException, IOException {
import java.io.PrintWriter; response.setContentType("text/html;charset=UTF-8");
import jakarta.servlet.ServletException; try (PrintWriter out = response.getWriter()) {
import jakarta.servlet.http.HttpServlet; /* TODO output your page here. You may use following
import jakarta.servlet.http.HttpServletRequest; sample code. */
import jakarta.servlet.http.HttpServletResponse;
/** out.println("<!DOCTYPE html>");
* out.println("<html>");
* @author Sathiya Jeba Sundar out.println("<head>");
*/ out.println("<title>Servlet HelloServlet</title>");
public class HelloServlet extends HttpServlet { out.println("</head>");
/** out.println("<body>");
* Processes requests for both HTTP out.println("<h1>Servlet HelloServlet at " +
<code>GET</code> and <code>POST</code> request.getContextPath() + "</h1>");
* methods. out.println("</body>");
* out.println("</html>");
* @param request servlet request }
* @param response servlet response }
* @throws ServletException if a servlet-specific error
occurs
Server – Overviews
Dynamic content
The doGet() method of the HelloCounter servlet is executed by the web server. A counter variable visits will be incremented
and its value output as part of the HTML document produced by the servlet.
The web server starts it creates a single instance of the Hello Counter class and executes the doGet() method on this instance
to handle each request for the HelloCounter servlet.
Life cycle of a Servlet
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. So, before
creating a Servlet object, let’s first understand the life cycle of the Servlet object which is
actually understanding how the Servlet container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.
Let’s look at each of these stages in details:
Life cycle of a Servlet
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the
Servlet container. The Web container or Servlet Container can load the Servlet at either
of the following two stages :
▪ Initializing the context, on configuring the Servlet with a zero or positive integer
value.
▪ If the Servlet is not preceding stage, it may delay the loading process until the
Web container determines that this Servlet is needed to service a request.
• The Servlet container performs two operations in this stage :
• Loading : Loads the Servlet class.
• Instantiation : Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor
2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet
container initializes the instantiated Servlet object. The container initializes the Servlet
object by invoking the Servlet.init(ServletConfig) method which accepts ServletConfig
object reference as parameter.The Servlet container invokes
the Servlet.init(ServletConfig) method only once, immediately after
the Servlet.init(ServletConfig) object is instantiated successfully. This method is used
to initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
Life cycle of a Servlet
3. Handling request: After initialization, the Servlet instance is ready to
serve the client requests. The Servlet container performs the following
operations when the Servlet instance is located to service a request :
▪ It creates the ServletRequest and ServletResponse objects. In this case, if this is
a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
▪ After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the request
and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.

4. Destroying a Servlet: When a Servlet container decides to destroy the


Servlet, it performs the following operations,
▪ It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
▪ After currently running threads have completed their jobs, the Servlet container
calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all
the references of this Servlet instance so that it becomes eligible for
garbage collection.
Servlet Life Cycle Methods
• There are three life cycle methods of a
Servlet :
• init()
• service()
• destroy()
Servlet Life Cycle Methods
// Java program to show servlet example
// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class AdvanceJavaConcepts extends HttpServlet
{
private String output;
// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
// Requesting and printing the output
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}
public void destroy()
{
System.out.println("Over");
}
}
PARAMETER DATA

Almost all servlets access data contained in


the HTTP request sent ot the server from
the browser. As indicated earlier, a servlet
can access this data by calling methods on
the HttpServletRequest parameter supplied
to the servlet’s doGet() method. In this
Section we’ll focus on the methods for
accessing the most frequently used portion
of the HTTP request, the so-called
parameter data of the request.
Parameter data
Parameter data
Parameter data
Parameter data
Introduction to Servlet Session Management

• Servlet Session Management is a mechanism in Java used by Web


container to store session information. Session tracking is a way to
manage the data of a user, this is known as session management in
servlet. Session in Java are managed through different ways, such
as, HTTP Session API, Cookies, URL rewriting, etc.
• Session management or tracking is an important feature of modern
websites that allows server to remember clients. Before entering
into this topic, session is a conversation between server and client,
it contains series of continuous requests and responses.

Why is Session Maintained?

• When there are continuous request and responses from same client to server, so the server cannot identify
from which client are requests being sent. As HTTP is a Stateless protocol.

• Although there is an advantage of being stateless, some requests enforce in maintaining state in order to
maintain proper functionality.
Introduction to Servlet Session Management

• Session Management/ Tracking Methods


• User Authorization: It is one way where user provides Username and password or any authentication
credentials from login and then these are passed via server and client to maintain the servlet session. It is not
much effective as this does not work if same user is logged from different browsers.
• URL rewriting: User can append session identifier parameter with every request and response to keep track of
session. It is tedious as user needs to keep track of parameter in each response and to make sure, it does not
clash with other parameters.
• Hidden Fields: User has access to create unique field in HTML which is hidden, when user starts navigating,
user will be able to set the value uniquely to customer and have track over the session. This method is not used
with links as this needs form being submitted each time there is a request made from client to the server with
any hidden fields. It is not much secure as user can get this hidden field value from source code and use to hack
sessions.
• Session Tracking API: It is built on top of all other Tracking methods. This type of session tracking is used for
developers to minimize overhead of session tracking. Major disadvantage is that most of the time, user need not
have to track session, but need to store some data in the session that can be used in future requests.
• Cookies: Cookie is a key value pair of information sent by server to browsers. It is the most used technology for
session tracking. Cookie is a smallest piece of information sent by the web server in head tag and is stored as
browser cookie. When there is a further request, cookies get added to the requested header and can be utilized
to keep track of servlet session. If customer disables cookie, servlet session with cookie will not work.
• Two types in Cookies:
• Non-persistent Cookie: It is valid only for single session and is removed each time when browser gets closed.
• Persistent Cookie: It is valid for multiple sessions and is removed only when user logs out but not when browsers get closed.
• HTTP and SSL: Browsers that support Secure Socket Layer communication use SSL support via HTTPS to
generate unique session key as part of encrypted conversation. Modern sites like e-commerce, ticket booking,
Internet banking, etc., use HTTPs to securely transfer data and manage session.
Introduction to Servlet Session Management

How to Create New Session Object and Enable?

• Make a new session object.

request.getSession() is the method that creates new session object. Container generates new session ID for
present session and sends back to client.

HttpSession session = request.getSession();

• Store information in session object.

Session objects are just hash tables that store user objects and associate user object with keys.

• Look up for information associated with Servlet.

If session already exists, session code tells container to extract ID from cookies. Container uses this ID as key
to search table of previously created HttpSession objects. If there is a session found, user can access that
session by getAttribute(‘key’) method.
Introduction to Servlet Session Management

Key Method Used in HTTPSession

• isNew(): Returns true is user does not know about the session. If cookies are disabled, then session is new.

• getId(): Returns string that contains unique identifier that is assigned to this session. Is used while using URL
rewriting the session.

• getAttribute(): Returns the object bound in present session.

• setAttribute(): Binds object to present session, uses specified name.

• invalidate(): Expires current session and unbinds the object binded

• setMaxInactiveInterval(): Specifies time between client requests before servlet invalidates session. Negative
time indicates session shouldn’t timeout.

With this we shall conclude the topic ‘Servlet session Management’. We have seen what Servlet Session
Management means and the types of Session tracking or management methods such as User Authorization, Hidden
fields, HTTPS or SSL, URL Rewriting, Cookies, and Session tracking API. We have also seen How to create Session
Object and enable it, listed out some methods applicable to session objects.
Session Management in java - cookies

Session Management in Java - Cookies


Cookies are used a lot in web applications to personalize response based on your choice
or to keep track of session. Before moving forward to the Servlet Session Management
API, I would like to show how can we keep track of session with cookies through a small
web application. We will create a dynamic web application ServletCookieExample with
project structure like below image.
Deployment descriptor web.xml of the web application is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletCookieExample</display-name>
<welcome-file-list> Welcome page of our application is
<welcome-file>login.html</welcome-file>
</welcome-file-list>
login.html where we will get
</web-app> authentication details from user.
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title> </head> <body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
Session Management in java - cookies
Here is the LoginServlet that takes care of the login request
package com.journaldev.servlet.session; // get request parameters for userID and password
import java.io.IOException; String user = request.getParameter("user");
import java.io.PrintWriter; String pwd = request.getParameter("pwd");
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException; if(userID.equals(user) && password.equals(pwd)){
import javax.servlet.annotation.WebServlet; Cookie loginCookie = new Cookie("user",user);
import javax.servlet.http.Cookie; //setting cookie to expiry in 30 mins
import javax.servlet.http.HttpServlet; loginCookie.setMaxAge(30*60);
import javax.servlet.http.HttpServletRequest; response.addCookie(loginCookie);
import javax.servlet.http.HttpServletResponse; response.sendRedirect("LoginSuccess.jsp");
/** }else{
* Servlet implementation class LoginServlet RequestDispatcher rd =
getServletContext().getRequestDispatcher("/login.html");
*/
PrintWriter out= response.getWriter();
@WebServlet("/LoginServlet")
out.println("<font color=red>Either user name
public class LoginServlet extends HttpServlet {
or password is wrong.</font>");
private static final long serialVersionUID = 1L;
rd.include(request, response);
private final String userID = "Pankaj";
}
private final String password = "journaldev";
protected void doPost(HttpServletRequest request,
}
Session Management in java - cookies

Notice the cookie that we are setting to the response and then forwarding it to Notice that if we try to access the JSP directly, it will forward
LoginSuccess.jsp, this cookie will be used there to track the session. Also notice
that cookie timeout is set to 30 minutes. Ideally there should be a complex logic us to the login page. When we will click on Logout button, we
to set the cookie value for session tracking so that it won’t collide with any should make sure that cookie is removed from client browser.
other request.
Session Management in java - cookies

There is no method to remove the cookie but we can set the maximum age to 0
so that it will be deleted from client browser immediately. When we run above
application, we get response like below images.
Java servlet and jdbc example | insert data in mysql

What is JDBC?
JDBC is an acronym for Java Database Connectivity. It’s Why JDBC Come into Existence?
an advancement for ODBC ( Open Database As previously told JDBC is an advancement for
Connectivity ). JDBC is a standard API specification ODBC, ODBC being platform-dependent had a lot of
developed in order to move data from frontend to the drawbacks. ODBC API was written in C, C++, Python,
backend. This API consists of classes and interfaces and Core Java and as we know above languages
written in Java. It basically acts as an interface (not the (except Java and some part of Python )are platform-
one we use in Java) or channel between your Java dependent. Therefore to remove dependence, JDBC
program and databases i.e it establishes a link between
was developed by a database vendor which consisted
the two so that a programmer could send data from Java
code and store it in the database for future use. of classes and interfaces written in Java.
Illustration: Working of JDBC co-relating with real-time

Steps For Connectivity Between Java Program and


Database
1.Import the Packages
2.Load the drivers using the forName() method
3.Register the drivers using DriverManager
4.Establish a connection using the Connection class
object
5.Create a statement
6.Execute the query
7.Close the connections
Java servlet and jdbc example | insert data in mysql

What is JDBC?
JDBC is an acronym for Java Database Connectivity. It’s Why JDBC Come into Existence?
an advancement for ODBC ( Open Database As previously told JDBC is an advancement for
Connectivity ). JDBC is a standard API specification ODBC, ODBC being platform-dependent had a lot of
developed in order to move data from frontend to the drawbacks. ODBC API was written in C, C++, Python,
backend. This API consists of classes and interfaces and Core Java and as we know above languages
written in Java. It basically acts as an interface (not the (except Java and some part of Python )are platform-
one we use in Java) or channel between your Java dependent. Therefore to remove dependence, JDBC
program and databases i.e it establishes a link between
was developed by a database vendor which consisted
the two so that a programmer could send data from Java
code and store it in the database for future use. of classes and interfaces written in Java.
Illustration: Working of JDBC co-relating with real-time

Steps For Connectivity Between Java Program and


Database
1.Import the Packages
2.Load the drivers using the forName() method
3.Register the drivers using DriverManager
4.Establish a connection using the Connection class
object
5.Create a statement
6.Execute the query
7.Close the connections
Java servlet and jdbc example | insert data in mysql

Let us discuss these steps in brief before implementing by writing suitable code to illustrate Step 4: Create a statement
connectivity steps for JDBC/ Once a connection is established you can interact with the database. The
Step 1: Import the Packages JDBCStatement, CallableStatement, and PreparedStatement interfaces
Step 2: Loading the drivers define the methods that enable you to send SQL commands and receive
In order to begin with, you first need to load the driver or register it before using it in the data from your database.
program. Registration is to be done once in your program. You can register a driver in one of Use of JDBC Statement is as follows:
two ways mentioned below as follows: Statement st = con.createStatement();
2-A Class.forName() Note: Here, con is a reference to Connection interface used in previous step
Here we load the driver’s class file into memory at the runtime. No need of using new or .
create objects. The following example uses Class.forName() to load the Oracle driver as Step 5: Execute the query
shown below as follows: Now comes the most important part i.e executing the query. The query here
Class.forName(“oracle.jdbc.driver.OracleDriver”); is an SQL Query. Now we know we can have multiple types of
queries. Some of them are as follows:
2-B DriverManager.registerDriver() •The query for updating/inserting a table in a database.
DriverManager is a Java inbuilt class with a static member register. Here we call the •The query for retrieving data.
constructor of the driver class at compile time. The following example uses The executeQuery() method of the Statement interface is used to execute
DriverManager.registerDriver()to register the Oracle driver as shown below: queries of retrieving values from the database. This method returns the
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()) object of ResultSet that can be used to get all the records of a table.
Step 3: Establish a connection using the Connection class object The executeUpdate(sql query) method of the Statement interface is used to
After loading the driver, establish connections as shown below as follows: execute queries of updating/inserting.
Connection con = DriverManager.getConnection(url,user,password)
•user: Username from which your SQL command prompt can be accessed.
•password: password from which the SQL command prompt can be accessed.
•con: It is a reference to the Connection interface.
•Url: Uniform Resource Locator which is created as shown below: Pseudo Code:
String url = “ jdbc:oracle:thin:@localhost:1521:xe” int m = st.executeUpdate(sql); if (m==1)
Where oracle is the database used, thin is the driver used, @localhost is the IP Address System.out.println("inserted successfully : "+sql); else
where a database is stored, 1521 is the port number and xe is the service provider. All 3 System.out.println("insertion failed");
parameters above are of String type and are to be declared by the programmer before Here sql is SQL query of the type String
calling the function. Use of this can be referred to form the final code.
Java servlet and jdbc example | insert data in mysql

Here sql is SQL query of the type String


Class.forName(
// This code is for establishing connection with MySQL
// database and retrieving data "com.mysql.cj.jdbc.Driver"); // Driver name
// from db Java Database connectivity
Connection con = DriverManager.getConnection(
/* url, username, password);
*1. import --->java.sql System.out.println(
*2. load and register the driver ---> com.jdbc.
*3. create connection "Connection Established successfully");
*4. create a statement
*5. execute the query
Statement st = con.createStatement();
*6. process the results ResultSet rs
*7. close
*/ = st.executeQuery(query); // Execute query
rs.next();
import java.io.*; String name
import java.sql.*;
= rs.getString("name"); // Retrieve name
class GFG { from db
public static void main(String[] args) throws System.out.println(name); // Print result on
Exception
{ console
String url st.close(); // close statement
= "jdbc:mysql://localhost:3306/table_name";
// table details con.close(); // close connection
String username = "rootgfg"; // MySQL System.out.println("Connection Closed....");
credentials
String password = "gfg123"; }
String query }
= "select *from students"; // query to be
Java servlet and jdbc example | insert data in mysql

Here sql is SQL query of the type String

Step 6: Closing the connections


So finally we have sent the data to the specified
location and now we are on the verge of
completing our task. By closing the connection,
objects of Statement and ResultSet will be closed
automatically. The close() method of the
Connection interface is used to close the
connection. It is shown below as follows:
con.close();
Java servlet and jdbc example | insert data in mysql
Here sql is SQL query of the type String
// Connection class object
// Java Program to Establish Connection in JDBC Connection con = null;
// Importing database // Try block to check for exceptions
import java.sql.*; try {
// Importing required classes
import java.util.*; // Registering drivers
DriverManager.registerDriver(
// Main class new oracle.jdbc.OracleDriver());
class Main {
// Reference to connection interface
// Main driver method con = DriverManager.getConnection(url, user,
public static void main(String a[]) pass);
{
// Creating a statement
// Creating the connection using Oracle DB Statement st = con.createStatement();
// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe"; // Executing query
int m = st.executeUpdate(sql);
if (m == 1)
// Username and password to access DB System.out.println(
// Custom initialization "inserted successfully : " + sql);
String user = "system"; else
String pass = "12345"; System.out.println("insertion failed");
// Entering the data // Closing the connections
Scanner k = new Scanner(System.in); con.close();
System.out.println("enter name"); }
String name = k.next(); // Catch block to handle exceptions
System.out.println("enter roll no"); catch (Exception ex) {
// Display message when exceptions occurs
int roll = k.nextInt();
System.err.println(ex);
System.out.println("enter class"); }
String cls = k.next(); }
}
// Inserting data using SQL query
String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";
Java servlet and jdbc example | insert data in mysql
Java servlet program with jdbc connection
To start with interfacing Java Servlet Program with JDBC
Connection:
1.Proper JDBC Environment should set-up along with
database creation.
2.To do so, download the mysql-connector.jar file from the
internet,
3.As it is downloaded, move the jar file to the apache-tomcat
server folder,
4.Place the file in lib folder present in the apache-tomcat
directory.
5.To start with the basic concept of interfacing:
•Step 1: Creation of Database and Table in MySQL
As soon as jar file is placed in the folder, create a database
and table in MySQL,
mysql> create database demoprj;
Query OK, 1 row affected (4.10 sec)

mysql> use demoprj Database changed


Java servlet program with jdbc connection
Step 2: Implementation of required Web-pages
Create a form in HTML file, where take all the inputs required to insert data into the database. Specify the
servlet name in it, with the POST method as security is important aspects in database connectivity.
Java servlet program with jdbc connection

Step 3: Creation of Java Servlet program with JDBC


ConnectionTo create a JDBC Connection steps are
1.Import all the packages
2.Register the JDBC Driver
3.Open a connection
4.Execute the query, and retrieve the result
5.Clean up the JDBC Environment

Create a separate class to create a connection of


database, as it is a lame process to writing the same
code snippet in all the program. Create a .java file
which returns a Connection object.
Java servlet program with jdbc connection
Step 4: To use this class method, create an object in Java Servlet program
Below program shows Servlet Class which create a connection and insert the data in the demo table,
Java servlet program with jdbc connection
Step 5: Get the data from the HTML fileTo get the data from the HTML file, the request object is used which
calls getParameter() Method to fetch the data from the channel. After successful insertion, the writer object is created to display
a success message.
After insertion operation from Servlet, data will be reflected in MySQL Database
This article shows the basic
connection of JDBC with Java
Servlet Program, to insert
data in large volume then
proper validation should be
done as if any data which is
not in proper format will
encounter an error. All the
data inserting in Database
should be encrypted.

You might also like