Unit 4 We

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

IT3401 WEB ESSENTIALS

UNIT V - SERVLETS AND DATABASE CONNECTIVITY

Servlets: Java Servlet Architecture – Servlet Life cycle- Form GET and POST actions -
Sessions – Cookies – Database connectivity – JDBC Creation of simple interactive
applications – Simple database applications

5.1 Servlets: Java Servlet Architecture


• Java Servlets are programs that run on a Web or Application server
and act as a middle layer between a request coming from a Web
browser or other HTTP client and databases or applications on the
HTTP server.
• Using Servlets, you can collect input from users through web page
forms, present records from a database or another source, and
create web pages dynamically.
• Java Servlets often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI). But
Servlets offer several advantages in com- parison with the CGI.
➢ Performance is significantly better.
➢ Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client
request.
➢ Servlets are platform-independent because they are written in Java.
➢ Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So, servlets are trusted.
➢ The full functionality of the Java class libraries is available to a
servlet. It can communicate with applets, databases, or other
software via the sock- ets and RMI mechanisms that you have seen
already.

5.1.1 Servlets Architecture


The following diagram shows the position of Servlets in a Web Application.

Fig: Servlet Architecture

5.1.2 Servlets Tasks


Servlets perform the following major tasks –
 Read the explicit data sent by the clients (browsers). This includes an HTML
form on a Web page or it could also come from an applet or a custom HTTP
client program.
 Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression scheme the browser
understands, and so forth.
 Process the data and generate the results. This process may require talking
to a database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being returned
(e.g., HTML), setting cookies and caching parameters, and other such tasks.
5.1.3 Servlets Packages
 Java Servlets are Java classes run by a web server that has an interpreter
that supports the Java Servlet specification.
 Servlets can be created using the javax.servlet and javax.servlet.http
packages, which are a standard part of the Java's enterprise edition, an
expanded version of the Java class library that supports large-scale
development projects.
 These classes implement the Java Servlet and JSP specifications. At the time
of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
 Java servlets have been created and compiled just like any other Java class.
After you install the servlet packages and add them to your computer's
Classpath, you can compile servlets with the JDK's Java compiler any other
current compiler.
5.2 SERVLET LIFE CYCLE
Basic Structure of a Servlet
public class
firstServlet extends
HttpServlet { public
void init() {
/* Put your initialization code in this method,
* as this method is called only once */
}
public void service() {
// Service request for Servlet
}
public void destroy() {
// For taking the servlet out of service, this method is called only once
}
}

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a 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.

Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method


• The init method is called only once. It is called only when the servlet
is created, and not called for any user requests afterwards. So, it is
used for one-time initializations, just as with the init method of
applets.
• The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.
• When a user invokes a servlet, a single instance of each servlet gets
created, with each user request resulting in a new thread that is
handed off to doGet or doPost as appropri- ate.
• The init() method simply creates or loads some data that will be
used throughout the life of the servlet.
• The init method efinition looks like this –

public void init() throws ServletException


{
// Initialization code
}

The service() Method

• The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method
to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
• Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
• The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
• Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException
{
// service code
}

• The service () method is called by the container and service method


invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.
So you have nothing to do with service() method but you override
either doGet() or doPost() depending on what type of request you
receive from the client.
• The doGet() and doPost() are most frequently used methods with in
each service request. Here is the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Servlet code
}

The destroy() Method

 The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities.
 After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this −
public void destroy()
{
// Finalization code...
}

Architecture Diagram

 The following figure depicts a typical servlet life-cycle scenario.


 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of
the servlet.

5.3 FORM GET AND POST ACTIONS

5.3.1GET Method

 The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ?
(question mark) symbol as follows −

http://www.test.com/hello?key1 = value1&key2 = value2


The GET method is the default method to pass information from browser
to web server and it produces a long string that appears in your browser's
Location:box. Never use the GET method if you have password or other
sensitive information to pass to the server. The GET method has size
limitation: only 1024 characters can be used in a request string.

 This information is passed using QUERY_STRING header and will be


accessible through QUERY_STRING environment variable and Servlet
handles this type of requests using doGet() method.

5.3.2 POST Method

 A generally more reliable method of passing information to a backend program


is the POST method. This packages the information in exactly the same way
as GET method, but instead of sending it as a text string after a ? (question
mark) in the URL it sends it as a separate message. This message comes to
the backend program in the form of the standard input which you can parse
and use for your processing. Servlet handles this type of requests using
doPost() method.

5.3.3 Reading Form Data using Servlet

Servlets handles form data parsing automatically using the following methods
depending on the situation −
 getParameter() − You call request.getParameter() method to get the value
of a form parameter.
 getParameterValues() − Call this method if the parameter appears more
than once and returns multiple values, for example checkbox.
 getParameterNames() − Call this method if you want a complete list of all
parameters in the current request.

5.3.4 GET Method Example using URL


Here is a simple URL which will pass two values to HelloForm
program using GET method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

 Given below is the HelloForm.java servlet program to handle input given by


web browser. We are going to use getParameter() method which makes it very
easy to access passed information –

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class

public class HelloForm extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println(title);
out.println(“First Name:” + request.getParameter("first_name") + “ Last Name:“ +
+ request.getParameter("last_name")
}

 compile HelloForm.java as follows −

$ javac HelloForm.java

 If everything goes fine, above compilation would produce


HelloForm.class file. Next you would have to copy this class file in
<Tomcat installation directory>/webapps/ROOT/WEB-INF/classes
and create following entries in web.xml file located in
<Tomcat-installation- directory>/webapps/ROOT/WEB-INF/

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>

 Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI


in your browser's Location:box and make sure you already started tomcat
server, before firing above command in the browser. This would generate
following result –

Output
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI

5.3.5 GET Method Example Using Form

Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this input.

<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>

5.4 POST Method Example Using Form


 A generally more reliable method of passing information to a backend program
is the POST method.
 Let us do little modification in the above servlet, so that it can handle GET
as well as POST methods. Below is HelloForm.java servlet program to handle
input given by web browser using GET or POST methods.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String title = "Using GET Method to Read Form Data";
out.println(title);
out.println(“First Name:” + request.getParameter("first_name") + “ Last Name:“ +
+ request.getParameter("last_name")
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}

Now compile and deploy the above Servlet and test it using Hello.htm with the POST
method as follows −
<html>
<body>
<form action = "HelloForm" method = "POST">
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>

Get vs. Post

S.N GET POST


o
1 In case of Get request, only limited In case of post request, large amount
amount of data can be sent because of data can be sent because data is
data is sent in header. sent in body.
2 Get request is not secured because Post request is secured because data
data is exposed in is not exposed in URL bar.
URL bar.
3 Get request can be bookmarked. Post request cannot be bookmarked.
4 Get request is idempotent . It means
second request will be ignored until Post request is non-idempotent.
response of first request is delivered
5 Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.

Two common methods for the request-response between a server and client are:

o GET- It requests the data from a specified resource


o POST- It submits the processed data to a specified resource

Anatomy of Get Request

 The query string (name/value pairs) is sent inside the URL of a GET request:

GET/RegisterDao.jsp?name1=value1&name2=value2

 As we know that data is sent in request header in case of get request. It is


the default request type. Let's see what information is sent to the server.

 Some other features of GET requests are:

 It remains in the browser history


 It can be bookmarked
 It can be cached
 It have length restrictions
 It should never be used when dealing with sensitive data
 It should only be used for retrieving the data

Anatomy of Post Request

The query string (name/value pairs) is sent in HTTP message body for a POST
request:

POST/RegisterDao.jsp HTTP/1.1 Host: www. javatpoint.com


name1=value1&name2=value2

As we know, in case of post request original data is sent in message body.


Let's see how information is passed to the server in case of post request.
Some other features of POST requests are:
 This request cannot be bookmarked
 These requests have no restrictions on length of data
 These requests are never cached
 These requests do not retain in the browser history

5.5 SESSION HANDLING

➢ Session tracking is a mechanism that servlets use to maintain state about a


series of requests from the same user (that is, requests originating from the
same browser) across some period of time. It is also known as session
management in servlet.
➢ HTTP is a "stateless" protocol which means each time a client retrieves a
Web page, the client opens a separate connection to the Web server and the
server automatically does not keep any record of previous client request.

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

1. Cookies

• A webserver can assign a unique session ID as a cookie to each web


client and for subsequent requests from the client they can be
recognized using the received cookie.

• This may not be an effective way because many time browser does
not support a cookie, so I would not recommend to use this
procedure to maintain the sessions.

2. Hidden Form Fields

• A web server can send a hidden HTML form field along with a
unique session ID as fol- lows −

<input type = "hidden" name = "sessionid" value = "12345">

• This entry means that, when the form is submitted, the specified
name and value are auto- matically included in the GET or POST
data. Each time when web browser sends request back, then
session_id value can be used to keep the track of different web
browsers.

• This could be an effective way of keeping track of the session but


clicking on a regular (<A HREF...>) hypertext link does not result in a
form submission, so hidden form fields also cannot support general
session tracking.

3. URL Rewriting

• You can append some extra data on the end of each URL that
identifies the session, and the server can associate that session
identifier with data it has stored about that session.

• For example, with http://tutorialspoint.com/file.htm;sessionid =


12345, the session identifier is attached as sessionid = 12345 which
can be accessed at the web server to identify the client.

• URL rewriting is a better way to maintain sessions and it works even


when browsers don't support cookies.

• The drawback of URL re-writing is that you would have to generate


every URL dynamically to assign a session ID, even in case of a
simple static HTML page.

4. The HttpSession Object

• Apart from the above mentioned three ways, servlet provides


HttpSession Interface which provides a way to identify a user across
more than one page request or visit to a Web site and to store
information about that user.

• The servlet container uses this interface to create a session between


an HTTP client and an HTTP server. The session persists for a
specified time period, across more than one connection or page
request from the user.

• You would get HttpSession object by calling the public method


getSession() of HttpServle- tRequest, as below −

HttpSession session = request.getSession();

• request.getSession() before you send any document content to the client.


Session Tracking Example

• This example describes how to use the HttpSession object to find


out the creation time and the last-accessed time for a session. We
would associate a new session with the re- quest if one does not
already exist.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Create a session object if it is already not created.

HttpSession session = request.getSession(true);


// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());


String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");


String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
else
{
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

// Set response content type response.setContentType("text/html");


PrintWriter out = response.getWriter();
out.println(“Session Information :” + session.getId() +
+ createTime + lastAccessTime);
out.println(“UserID : “ + userID + “Number of visits” + visitCount);
}
}

Deleting Session Data

When you are done with a user's session data, you have several options

• Remove a particular attribute − You can call public void


removeAttribute(String name) method to delete the value associated
with a particular key.

• Delete the whole session − You can call public void invalidate()
method to discard an en- tire session.

• Setting Session timeout − You can call public void


setMaxInactiveInterval(int inter- val) method to set the timeout for a
session individually.

• Log the user out − The servers that support servlets 2.4, you can
call logout to log the client out of the Web server and invalidate all
sessions belonging to all the users.
• web.xml Configuration − If you are using Tomcat, apart from the
above mentioned meth- ods, you can configure session time out in
web.xml file as follows.

<session-config>
<session-timeout>15</session-timeout>
</session-config>

• The timeout is expressed as minutes, and overrides the default


timeout which is 30 min- utes in Tomcat.

• The getMaxInactiveInterval( ) method in a servlet returns the timeout


period for that ses- sion in seconds. So if your session is configured
in web.xml for 15 minutes, getMaxInac- tiveInterval( ) returns 900.

5.6 COOKIES

Cookies are text files stored on the client computer and they are kept for
various information tracking purpose. Java Servlets transparently supports HTTP
cookies.

There are three steps involved in identifying returning users –


 Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server
then it sends those cookies information to the server and
server uses that information to identify the user.

The Anatomy of a Cookie


➢ Cookies are usually set in an HTTP header (although JavaScript can
also set a cookie directly on a browser). A servlet that sets a cookie
might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /;
domain = test.com
Connection: close
Content-Type: text/html

Setting Cookies with Servlet

Creating a Cookie object − You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.

Cookie cookie = new Cookie(“key”,”value”);

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
String data=req.getParameter("cdata");
Cookie cookie=new Cookie("MyCookie",data);
res.addCookie(cookie);
PrintWriter pw=res.getWriter();
pw.println("MyCookie has been set to:");
pw.println(data);
pw.close();
}
}
Addcookie.html
<html>
<head>
<title>COOKIES PROGRAM</title>
</head>
<body>
<h1> COOKIE PROGRAM </h1>
<form method="post" action="http://localhost:8080/examples/addc">
Enter cookie Data: <input type="text" name="cdata">
<input type="submit" value="Submit">
</form>
</body>
</html>

web.xml
<!-- Cookie Example -->
<web-app>
<servlet>
<servlet-name>cookie</servlet-name>
<servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookie</servlet-name>
<url-pattern>/addc</url-pattern>
</servlet-mapping>
</web-app>

Open addcookie.html in a browser and enter cookie data in the textbox and submit
the data.

Servlet Cookies Methods


Sr.No. Method & Description
1 public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.

2 public String getDomain()


This method gets the domain to which cookie applies, for example tutorialspoint.com.

3 public void setMaxAge(int expiry)


This method sets how much time (in seconds) should elapse before the cookie
expires. If you don't set this, the cookie will last only for the current session.

4 public int getMaxAge()


This method returns the maximum age of the cookie, specified in seconds, By
default,
-1 indicating the cookie will persist until browser shutdown.
5 public String getName()
This method returns the name of the cookie. The name cannot be changed
after creation.

6 public void setValue(String newValue)


This method sets the value associated with the cookie

7 public String getValue()


This method gets the value associated with the cookie.

8 public void setPath(String uri)


This method sets the path to which this cookie applies. If you don't specify a path,
the cookie is returned for all URLs in the same directory as the current page as well
as all subdirectories.

9 public String getPath()


This method gets the path to which this cookie applies.

10 public void setSecure(boolean flag)


This method sets the boolean value indicating whether the cookie should only be
sent over encrypted (i.e. SSL) connections.

11 public void setComment(String purpose)


This method specifies a comment that describes a cookie's purpose. The comment
is useful if the browser presents the cookie to the user.

12 public String getComment()


This method returns the comment describing the purpose of this cookie, or null if
the cookie has no comment.

Reading Cookies with Servlet

➢ To read cookies, you need to create an array of


javax.servlet.http.Cookie objects by calling the getCookies() method
of HttpServletRequest. Then cycle through the array, and use
getName() and getValue() methods to access each cookie and
associated value.
Delete Cookies with Servlet

➢ To delete cookies is very simple. If you want to delete a cookie


then you simply need to follow up following three steps –
• Read an already existing cookie and store it in Cookie object.
• Set cookie age as zero using setMaxAge() method to delete an
existing cookie
• Add this cookie back into response header.

5.7 Java Database Connectivity with MySQL

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a wide
range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & modifying the resulting records.

All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application –
Common JDBC Components

The JDBC API provides the following interfaces and classes −


 DriverManager − This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
 Driver − This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the
details associated with working with Driver objects.
 Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
 Statement − You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
 ResultSet − These objects hold data retrieved from a database after you execute
an SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
 SQLException − This class handles any errors that occur in a database
application.

Database connectivity

To connect Java application with the MySQL database, we need to follow 5 following
steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP
address, 3306 is the port number and sonoo is the database name. We may use
any database, in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to
create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;
class MysqlCon
{
public static void main(String args[]){
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“select * from emp”);
while(rs.next())
System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+rs.getString(3));
con.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}

Write a servlet program to create and insert records for employee details using JDBC

EmployeeData.java
-----------------
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class EmployeeData extends HttpServlet


{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();

try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

// Initialize the database


con = DriverManager.getConnection(“jdbc:odbc.employee”, ””, ””);
stmt = con.createStatement();
String sql = “CREATE TABLE employee_table(empid INTEGER not NULL, firstname
VARCHAR(20), lastname VARCHAR(25), PRIMARY KEY(empid))”;
stmt.executeUpdate(sql);

System.out.println("Inserting records into the table...");


String sql = “INSERT INTO employee_table VALUES (100, 'Zara', 'Ali')”;
stmt.executeUpdate(sql);
rs = stmt.executeQuery(“SELECT * FROM employee_table”);

//displaying records
Response.setContentType(“text/html”);
out.println(“<html>”);
out.println(“<body>”);
out.println(“<h1>Employee Details <h1>”);

while(rs.next())
{
out.print(rs.getInt(1) + “ “ + rs.getString(2) + “ “ + rs.getString(3));
}
out.print(“</body></html>);
}
catch(SQLException e) { }
rs.close();
stmt.close();
con.close();
out.close();
}
}

OUTPUT

Employee Details
100, 'Zara', 'Ali'

You might also like