Open Book

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

SYLLABUS Weightage : 15 Marks

Understanding Java EE
What is an Enterprise Application? What is java enterprise edition? Java EE
Technologies, Java EE evolution, Glassfish server.

Java EE Architecture, Server and Containers


Types of System Architecture, Java EE Server, Java EE Containers.

Introduction to Java Servlets


The Need for Dynamic Content, Java Servlet Technology, Why Servlets? What can
Servlets do?

Servlet API and Lifecycle


Java Servlet API, The Servlet Skeleton, The Servlet Life Cycle, A Simple Welcome
Servlet

Working with Servlets


Getting Started, Using Annotations Instead of Deployment Descriptor.

Working with Databases


What Is JDBC? JDBC Architecture, Accessing Database, The Servlet GUI and
Database Example.

Topics :
1.1 Understanding Java EE
1.2 Java EE Architecture, Server and Containers
1.3 Introduction to Java Servlets
1.4 Servlet API and Lifecycle
1.5 Working with Servlets
1.6 Working with Databases
1.1 UNDERSTANDING JAVA EE
1.1.1 Enterprise Application
Q.1 What is an Enterprise Application? Explain architecture of an enterprise
application.
OR
Explain the architecture of Java Enterprise application. [O-18]
Ans.: An enterprise applications are complex, distributed, scalable, component  based
and mission critical business application.
 It can be used on variety of platforms across internet, or extranets.

Architecture of an enterprise application :


 One of the key objectives of the Java EE platforms is to provide a standard
environment to develop Enterprise Applications.
 It is a distributed, multi-tiered, application model which can be described as
an enterprise application.
 Application logic is divided into components according to functions and the
various application component put together make up the enterprise application.
 These components are physically installed on different physical location,
depending on the tier in the multitired environment to which the application
component belongs.
 All components work together in harmony across the enterprise.
 Enterprise architecture is divided into the following tiers:
 Client tier services which run on the client machine.
 Web tier services run on the server
 Business tier services run on the server.
 Enterprise information system [EIS] tier software run on the EIS server.

1.1.2 Java Enterprise Edition


Q.2 What is Java Enterprise Edition?
OR
Explain Java EE.
Ans.: Java EE is a platform which is used to provide a standard environment to
develop enterprise applications :
 Java EE is a set of coordinated technologies and practices that enable
developing, deploying and managing multitier server centric enterprise
applications.
 It is a collection of standardised components, containers and services for
creating & deploying distributed applications within a well defined distributed
computing, architecture.
 Enterprise edition has brought in a powerful set of APIS that has helped the
develops not only reduce the development time and the application
complexity, but also improve the application performance.
 Java EE provides a collection of :
 Standardized compound that facilitate the crafting of such commercial
applications.
 Standard interfaces that define how the various application modules
interconnect.
 Standard services that define how the different software modules
communicate.
 Another major influence on the Java EE has been the internet, which has
created quite a demand for online enterprise systems and the technology
needed to implement them.
 For example, the status nature of hypertext transfer protocol (HTTP) ensures
that the client does not have a permanent connection with the server, has
serious implications on how state is managed between invocations.

1.1.3 Java EE Technologies


Q.3 What are different technologies provided by Java EE platform?
Ans.: Following are different technologies provided by the Java EE platform :
(a) Web Application Technologies
(i) Java Servlet : A servlet is an application present inside a web server, it
accept request from client, dynamically generate the response & then
send the response to the client. It can be done using various servlet API
(classes & interfaces).
(ii) Java Server Pages : A JSP is present inside web server, which is
mainly used to embed. Java is HTML. It is more easier for those web
designers who are more comfortable in scripting languages likes HTML.
(iii) Java Server Faces :JSP is an user interface framework for building web
applications. It is server side, user interface component framework for
building web applications.
(b) Enterprise Applications Technologies
(i) Enterprise Java Beans (EJB) : EJB are scalable, transactional,
reusable, secure building blocks which are present pride web server &
can be used by various web applications like servlet JSP etc.
(ii) Java persistence API (JPA) : JPA is a java standard based API for
object relational mapping, and it is a solution for persistence. Persistence
uses an ORM approach to bridge the gap between an object oriented
model & relational database.
(c) Web Services Technologies
(i) SOAP and RESTFUL : The Java API for RESTFUL web services
defines APIs for the development of such services built according to the
representational state transfer [KEST] architectural style.
(ii) Java API for XML registries [JAXR] : JAXR allow accessing business
and general purpose registries the web.
(d) Security Technologies
(i) Java authorization service provider contact for container [JACC] :
JACC defines a contract between a Java EE application server and an
authorization policy provider. All Java EE containers support the
contract.
(ii) Java Authentication since provider interface for containers
[JASPIC] : JASPIC specification defines a service provider interface [SPI]
by which authentication providers that implement message authentication
mechanism may be integrated indicator server message processing
containers or relations.
1.1.4 Java EE Evolution
Q.4 Explain Java EE evolution.
Ans.: Java platform, enterprise edition (Java EE), formely Java & platforms, enterprise
edition (J2EE), is a set of specifications, extending Java SE with specifications
for enterprise features such as distributed computing & web services :
 The platform was known as Java 2 platform, enterprise edition or J2EE from
version 1.2, until the name was changed to Java platform, enterprise edition
or Java EE in version 1.5. The current version is called Java EE 8.
Following are different versions of Java EE :
 J2EE 1.2
 J2EE 1.3
 J2EE 1.4
 Java EE 5
 Java EE 6
 Java EE 7
 Java EE 8
 Java EE is maintained by oracle under the Java community process.
 On September 2017, oracle corporation announced that it would Java EE to
the eclipse foundation.
 The eclipse foundation was forced to change the name of Java EE because
oracle owns the trademark for the name “Java”.
 On February 26, 2018, it was announced that the new name of Java EE will
be Jakarta EE.

1.1.5 Glassfish Server


Q.5 Write a short note on Glassfish server.
Ans.: Glassfish is an open source application server project started by
sumicrosystems for the Java EE platform and now sponsored by oracle
corporation. Features of such Glassfish enterprise server. Following are the
features of glassfish enterprise server :
(a) Enterprise features : Glassfish enterprise server support application
clusters for scalability & high availability.
(b) Java EE features : It offers access to the latest functionality in the Java EE
platform such as EJB 0.1 lite and Java server faces 2.0.
(c) Production support for lightweight web tier : It provides a lightweight Web
tier deployment platform with full production support. In addition glassfish
server in web tier & application tier used in enterprise wide architecture.
(d) Dynamic language support with reliable performance : Glassfish server
allows us to run development languages such as Java, Groory on Grails and
JRuby at the same time without sacrificing performance.
(e) Easy-to-use administration console : It offers a simple user interface with
point and click configuration, application deployment and installation of
additional compound from the update center.
(f) Rapid deployment technology : It simplifies the web development cycle of
java based applications to edit code, save and immediately refresh browser
with no loss of application state.
(g) Microsoft.NET Interpporability : Sun and Microsoft work closely to ensure
the Java EE and.NET platforms can introprate easily.
1.2 JAVA EE ARCHITECTURE, SERVER AND CONTAINERS
1.2.1 Java EE Server
Q.1 Explain the architecture of Java EE server with diagram.
Ans.: Java EE server is a server application that implement the Java EE platform APIS
and provides the standard Java EE servers.
Web Container

JSP JSF servlet

httprequest
Client EJB Container Database

httpresponse
EJB EJB

Java EE server

 Java EE server, sometimes also called as application servers because they


allow serving application data to client, just like Web servers since Web
pages to Web browsers.
 Java EE server provides services to different compound in the form of
container.
 During the deployment process, installation of java EE application
components takes place in the Java EE containers on the Java EE server.
 Java EE server is used as runtime portion for the execution of application,
which contains the EJB and Web containers.

1.2.2 Java EE Containers


Q.2 Explain different types of containers.
OR
Classify the EE Containers. Explain. [O-18]
Ans.: Containers are the interface between a component and the lowlevel platform
specific functionality that supports the component.
 Before a Web, enterprise bean, or application client component can be
executed, it must be assembled into a Java EE module, and deployed into its
container.
 The deployment process installs Java EE application compound in the Java
EE containers as illustrated in figure :
Web Container

JSP JSF servlet

httprequest
Client EJB Container Database

httpresponse
EJB EJB

Fig.: Java EE server & Containers


 Following are different types of containers :
1. EJB Container : Manages the execution of enterprise beans for Java EE
applications, enterprise beans and their container run on the Java EE server.
2. Web Container : Manages the executing of JSP page & servlet components for
Java EE applications. Web component & their container run on java EE server.
3. Application Client Container : Manages the execution of application client
components. Application client & their container run on the client.
4. Applet Container : Manages the execution of applets, consists of a Web
browser & java plug-in running on the client together.

1.3 INTRODUCTION TO JAVA SERVLETS


1.3.1 The Need of Dynamic Content
Q.1 Explain need of dynamic contents.
OR
Explain CGI with working & its disadvantages.
OR
Explain need of dynamic contents & describe working of CGI.
Ans.: Many of times, Web pages are static, it means user request a resource & the
server returns it.
However, with the growth of commercial activities on the Web and the rapid spread &
adoption of the world wide web as a report without geographical boundaries,
companies wanted to deliver dynamic content to their customers such as :
 Bank account details  Weather report
 News headlines  Cricket match scorecard

Common Gateway Interface (CGI)


CGI (Common Gateway Interface) is mainly used to provide dynamic response in
three-tier architecture.

Working :
 In this when a client sends a request to a web server, web server first checks
whether a client wants static response or dynamic response.
 If client wants dynamic response then web server forwards the request to
CGI, to handle that request CGI creates CGI process and it will get loaded
inside the web server.
 Now that CGI process is responsible for sending the dynamic response to a
client.
 Once the client gets the response web server unloads CGI process to
release its memory.
 This entire process will get repeated whenever a web server get a request for
dynamic response.
Disadvantages :
(i) CGI process are platform dependents because they are developed in C, C++
and pearl.
(ii) It increases the overhead of a web server.
(iii) It is difficult to implement.
(iv) Lack of scalability.
(v) It uses lots of web server resources.
(vi) lack of security.

1.3.2 Java Servlet Technology


Q.2 Explain working of servlet.
Ans.:
http request init( )
Client Servlet service( )
http response
destroy( )

Web container

Web server

 In case of servlet, web server creates the servlets and load it inside the web
container.
 When a particular client sends a request, first time for a particular servlet,
web server initialize that servlet using init( )
 Once the servlet gets initialized, it accept the request and provide the
dynamic response to a client using service( )
 This process will get repeated, whenever a client send a request for a
particular servlet.
 At one stage when there is no any request for a particular servlet, in that
case a web server destroys that servlet using destroy( )
 The destruction can be done, so that the memory occupied by that servlet
will get released.
 Initialisation and destruction can be done by the web server, but service is
provided by servlet itself.
 Initialisation and destruction can happen only once, but service will happen
many times whenever servlet get the request.

1.4 SERVLET API & LIFECYCLE


1.4.1 Java Servlet API
Q.1 Write a short note on Java servlet API.
Ans.: Servlet API :
It includes following two packages which contains different interfaces and
different classes used to handle servlet application.
javax.servlet :
 Interfaces :
(1) Servlet :
 It is the most basic interface of servlet.
 It is used to create servlet.

(2) ServletRequest :
 It is used to extract the required information from the HTTP request.

(3) ServletResponse :
 It is used to create or form a HTTP response so that it can be given
to client.

(4) Servletconfig :
 It is used to configure or initialize a servlet.

(5) ServletContext :
 It is used to provide the information about the environment of the
servlet i.e. web server of the servlet.

 Classes :
(1) GenericServlet :
 It is derived from Servlet interface.
 It is used to create servlet.

(2) ServletInputStream :
 It is used to accept a HTTP request from a client.

(3) ServletOutputStream :
 It is used to send a HTTP response to a client.

(4) ServletException :
 It is used to handle the exception generated in servlet application.

javax.servlet.http :
 Interfaces :
(1) HttpServletRequest :
 It is derived from ServletRequest interface.
 It is used to extract required information from the HTTP request.

(2) HttpServletResponse :
 It is derived from ServletResponse interface.
 It is used in create or form a HTTP response so that it can be sent to
the client.

(3) HttpSession :
 It is used to create a session between client and the servlet.
 Classes :
(1) HttpServlet :
 It is derived from GenericServlet class.
 It is used to create a servlet.

(2) HttpServletEvent :
 It is used to handle events generated by servlet application.

(3) Cookie :
 It is used to create a cookie.
 Cookie is a temporary storage created by servlet and stored inside
the client.

1.4.2 The Servlet Skeleton


Q.2 Explain the skeleton of servlet.
Ans.:  A servlet is an instance of a class which implement javax.servlet.servlet
interfaces or extends javax.servlet.Generic servlet and javax.servlet.
httpservlet.
 Implementing or extending servlet provides a framework for creating a servlet
as well as significant default functionality.
 The servlets code spec.must override at least one method when any custom
functionality is being implemented.
 In order to initialize a servlet, the Web server :
 Loads the servlet class & creates an instance by calling the noargs
constructor.
 Call the servlet init (ServletConfig) method
 init () is called only once when the servlet is loaded in memory for the
first time
 ServletConfig object supplies a result with information about is
initialization parameters. These parameters are given to the servlet
itself and are not associated with any single request. ServletConfig
object can be retrieved by calling the servlet is getServletConfig ()
method. This is handled by GenericServlet.
 Any java enabled web server automatically invokes servlets service () in
response to a client request, this means when a servlet is initialized, its
service (ServletRequest request, ServletResponse response) method is
called for every request to the servlet.
 If a servlet developer chooses not to override service (), there are other
methods that can be invoked in response to a client request.
 When the servlet needs to be unloaded, for example because a new version
should be loaded or the senior is shutting down, destroy () is called.
Example :
public class skeleton extends HttpServlet
{
public void init ()
{
// Initialization code
}
public void service ()
{
// processing work
}
public void destroy ()
{
// resources release code
}
}

1.4.3 The Servlet Life Cycle


Q.3 Explain life cycle of servlet with diagram.
OR
Explain the life cycle of a servlet application. [O-18]
Ans.: Life cycle of a servlet
The entire life cycle of servlet consists of
following phases : Web server
Web server
creates a
creates an
servlet and load
1. Creation and Loading : instance of the
it inside web
servlet.
 In this a web server creates a servlet container.
and load it inside the web container
(servlet pool).

2. Instantiation : Web servers Web servers


 In this web server creates the instance accepts the initializes the
request from servlet by using
i.e. object of a servlet, so that we can the client init( )
call its methods using that object.

3. Initialization :
 In this when a servlet gets its first
request, web server initializes that Web server Servlet process
delegates the the request
servlet using init( ). request to a using the
servlet service( )
4. Service :
 Once the servlet gets initialized it
accepts the request and provides the
response to client by using service( )
Servlet
 The same servlet will wait for some provides the
Servlet waits
other request and generate responses for the other
responses to
request
for them. the client

5. Destruction :
 In this if a servlet does not get request,
a web server will destroy that servlet Web server
using destroy( ), to unload its memory Web server
unloads the
destroys servlet
so that the same memory can be used using destroy( ) memory of the
for some other purpose. servlet.
1.4.4 A Simple Welcome Servlet
Q.4 Write a servlet program to display the simple sentence welcome along with
the name entered by the user through an HTML form.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="test">
<b>Enter Name </b>
<input type="text" name="n" value="" size="10">
<br>
<input type="submit" value="Display">
</form>
</body>
</html>
//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String s=req.getParameter("n");
pw.println("Welcome "+s);
pw.close();
}
}

1.5 WORKING WITH SERVLETS


Q.1 Create a simple calculator application using servlet.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="test">
<b>Number 1</b>
<input type="text" name="a" value="" size="10">
<br>
<b>Number 2</b>
<input type="text" name="b" value="" size="10">
<br>

<input type="submit" name="c" value="+">


<input type="submit" name="c" value="-">
<input type="submit" name="c" value="*">
<input type="submit" name="c" value="/">
</form>
</body>
</html>

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

public class test extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
int n1=Integer.parseInt(req.getParameter("a"));
int n2=Integer.parseInt(req.getParameter("b"));
String s=req.getParameter("c");
if(s.equals("+"))
{
pw.println("Addition="+(n1+n2));
}
else if(s.equals("-"))
{
pw.println("Subtraction="+(n1-n2));
}
else if(s.equals("*"))
{
pw.println("Multiplication="+(n1*n2));
}
else
{
pw.println("Division="+(n1/n2));
}
pw.close();
}
}

Q.2 Create a servlet for a login page. If the username & password are correct
then it says message “Hello” <username> else a message “login failed”.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="test">
<b>Username</b>
<input type="text" name="u" value="" size="10">
<br>
<b>Password</b>
<input type="password" name="p" value="" size="10">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String s1=req.getParameter("u");

String s2=req.getParameter("p");
if((s1.equals("servlet"))&&(s2.equals(“sss”)))
{
pw.println("Hello"+s1);
}
else
{
pw.println("Login Failed !!!");
}
pw.close();
}
}

Q.3 Develop simple servlet question answer application.


Ans.: //index.jsp
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<form method="post" action="Question">
<h4><u><center>Check Your Knowledge ........</center></u></h4>
<h4>What JSP stand for </h4>
<input type="radio" name="q1" value="Java Server Pages"><b>Java Server
Pages</b><br>
<input type="radio" name="q1" value="Java Server Programming"><b>Java
Server
Programming</b><br>
<input type="radio" name="q1" value="Java Service Pages"><b>Java Service
Pages</b><br>
<input type="radio" name="q1" value="Java Service Programming"><b>Java
Service
Programming</b><br>
<h4>Which of the following languages can be used to write server side scripting
in ASP.NET?</h4>
<input type="radio" name="q2" value="C#"><b>C#</b><br>
<input type="radio" name="q2" value="VB"><b>VB</b><br>
<input type="radio" name="q2" value="C++"><b>C++</b><br>
<input type="radio" name="q2" value="Both a and b"><b>Both a and b</b><br>
<h4>What command is used to remove files in Linux?</h4>
<input type="radio" name="q3" value="dm"><b>dm</b><br>
<input type="radio" name="q3" value="rm"><b>rm</b><br>
<input type="radio" name="q3" value="delete"><b>delete</b><br>
<input type="radio" name="q3" value="None of the above"><b>None of the
above</b><br>
<input type="Submit" name="btnsubmit">
</form></body></html>

//Question.java (Servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Question extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
int correct=0;
int incorrect=0;
String a=request.getParameter("q1");
String b=request.getParameter("q2");
String c=request.getParameter("q3");
if(a.equals("Java Server Pages"))
{
correct++;
}
else
{
incorrect++;
}

if(b.equals("Both a and b"))


{
correct++;
}
else
{
incorrect++;
}

if(c.equals("rm"))
{
correct++;
}
else
{
incorrect++;
}
PrintWriter out = response.getWriter();
try
{
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Question</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Result Of the Test</h1><br>");
out.println("<h3>Correct Answer :::"+correct+"</h3>");
out.println("<h3>Incorrect Answer :::"+incorrect+"</h3>");
out.println("</body>");
out.println("</html>");
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}

1.6 WORKING WITH DATABASES


1.6.1 JDBC
Q.1 Explain different types of JDBC drives.
Ans.: JDBC Drivers :
 JDBC Drivers are mainly used to convert Jdbc calls into database specific
calls and vice versa.
 Following are 4 types of JDBC drivers :
1. Type 1 Driver (JDBC / ODBC Bridge Driver) :
Database
JDBC ODBC specific calls
calls calls
JDBC Type 1 ODBC Database
application driver
 In this type 1 driver will convert JDBC calls in ODBC calls and vice versa.
 Advantage : It is free and easy to implement.
 Disadvantage : It is slower as compared to other types of drivers.

2. Type 2 Driver (Native APT Driver) :


JDBC Database
calls specific calls
Jdbc Type 2 Database
application

 Here Type 2 driver will convert JDBC calls into database specific call, but to
send those calls it uses native API.
 Advantage : It is faster as compared to type 1 and type 3 driver.
 Disadvantage : Just to send the calls it requires Native API.

3. Type 3 Driver (Network Protocol Driver) :


Middleware Database
JDBC server specific specific calls
calls calls
JDBC Type 3 Middle Database
application ware
server

 Here type 3 driver will convert JDBC calls into middleware server specific
calls and vice versa.
 Middleware server is normally used to implement different security and traffic
control mechanism.
 Advantage : It is comparatively secure among all other type of drivers.
 Disadvantage : It is slower as compared to type 2 and type 4 driver.

4. Type 4 Driver (Database Protocol Driver) :


Database
JDBC calls
specific calls
JDBC Type 4 Database
application

 Type 4 driver will directly convert JDBC calls into database specific calls and
vice versa, as well as it has the capability to send those calls.
 Advantage : It is the fastest of all drivers.
 Disadvantage : It is costliest of all drivers.
1.6.2 JDBC Architecture
Q.2 Explain JDBC architecture with diagram JDBC Architecture follows layered
Approach.
Ans.:
Driver Manager class

Driver
Layer
Driver Interface

Connection

Application
Layer Prepared Statement Statement Callable Statement Interface

Result Set ResultSet ResultSet

The architecture follows, following important JDBC classes/ interface in java.sql


packages.
1. Driver : It gives JDBC a launching point for database connectivity by
responding to DriverManager connection request.
2. DriverManager : It keeps a list of classes that implement the Driver interface.
When an application is run, DriverManager loads all the drivers found in the
memory.
3. Connection : This interface can be used to retrieve information regarding the
table in the database to which connection is opened.
4. Statement : It is used to pass to the database the SQL command for
execution and to retrieve output results from the database in the form of a
Resultset.

1.6.3 Accessing Database


Q.3 Write and explain the steps for Java database connectivity.
Ans.:  It is the mechanism by which we can access the database with the help of
Java program.
 Accessing a database includes performing following operations on a
database :
1) Inserting a new record in database.
2) Deleting an existing record.
3) Update a particular record.
4) Display the contents of database table.

 To perform all the operations we need to use following 7 steps of JDBC :


1. Importing a package : Following package we need to import to use classes
and interface of that package :
import java.sql.*;
2. Loading a drives : We need to load a driver of a particular database inside
the programs:
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
3. Establishing a connection : We need to establish a connection from a
program to a particular database.
Connection c = DriverManager.getConnection ("jdbc:odbc:dbname")
4. Creating a statement : In JDBC program, we need to create a statement to
perform different operations:
Statement s = (C.createStatement c);
5. Executing the statement : Following are different method which are used to
execute different sql queries on a database:
(i) s.executeUpdate( );
(ii) s.execute ( );
(iii) s.executeQuery ( );
ResultSet rs = s.executeQuery ( );
6. Retrieving a result : In this we need to retrieve a result from database to a
java program:
Resultset rs = s.getResultset ( );
7. Closing a connection : After performing all operations on database, it is
always better to close the connection :
rs.close ( );
s.close ( );
c.close ( );

Q.4 Write a program to establish a connection with database table and perform
following operations on table “employee” Assume following database
table.
(i) Insert a record in database table
(ii) Delete a particular row
(iii) Update a particular row
(iv) Display the contents of database table.

id name address
1 sss dadar
2 akn sion
Ans.: import java.sql.*;
class Main
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection(“jdbc:mysql://localhost/vcp”,
“root”,“root”);
s.execute("insert into employee values(3,'sdw','thane')");
System.out.println("Record Inserted");
s.execute("delete from employee where id=2");
System.out.println("Record Deleted");
s.executeUpdate("update employee set name='swapnil' where
address='dadar'");
System.out.println("Record Updated");
ResultSet rs=s.executeQuery("select * from employee");
while(rs.next())
{
System.out.println("ID="+rs.getInt(1));
System.out.println("Name="+rs.getString(2));
System.out.println("Address="+rs.getString(3));
}
rs.close();
s.close();
c.close();
}
catch(Exception e)
{
System.out.println("Exception Occur");
}
}
}

1.6.4 The Servlet GUI and Database Example


Q.5 Write a program to accept details of a person & using servlet store those
details in database.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="test">
Name
<input type="text" name="a" value="" size="10">
<br>
Password
<input type="password" name="b" value="" size="10">
<br>
Address
<textarea name="c" rows="4" cols="10"></textarea>
<br>
<input type="submit" value="Register">
</form>
</body>
</html>
//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse
res)throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String s1=req.getParameter("a");
String s2=req.getParameter("b");
String s3=req.getParameter("c");
Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection(“jdbc:mysqp://localhost/sss”,
“root”,“root”);
PreparedStatement ps=c.prepareStatement(“insert into employee values
(?,?,?)”);
ps.setString(1,s1);
ps.setString(2,s2);
ps.setString(3,s3);
ps.execute();
ps.close();
c.close();
pw.println("Record Inserted”);
pw.close();
}
}



You might also like