UNIT - 3 Server Side Programming - CCS375 New
UNIT - 3 Server Side Programming - CCS375 New
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.
• 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
request.getSession() is the method that creates new session object. Container generates new session ID for
present session and sends back to client.
Session objects are just hash tables that store user objects and associate user object with keys.
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
• 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.
• 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
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
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
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