Servlets and JDBC

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

1.

Name the different APIs for the development of JAVA EE Applications and explain about
Java EE platform architecture with a neat sketch.

Java EE Architecture

The Java EE architecture is a component-based and platform-independent that makes


Java EE applications easy to write because business logic is organized into reusable components
and the Java EE server provides underlying services in the form of a container for every
component type.

Containers and Services

Containers are the place holders for the components installed during deployment and
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 application and deployed into its container.

The container also manages non-configurable services such as enterprise bean and
servlet life cycles, database connection resource pooling, data persistence, and access to the
Java EE platform APIs described in Java EE APIs.
Container Types
The deployment process installs Java EE application components in the following types of Java
EE containers. The Java EE components and container addressed in the figure1below.
An Enterprise JavaBeans (EJB) container manages the execution of all enterprise beans for one
Java EE application. Enterprise beans and their container run on the Java EE server.
A web container manages the execution of all JSP page and servlet components for one Java EE
application. Web components and their container run on the Java EE server.
An application client container manages the execution of all application client components for
one Java EE application. Application clients and their container run on the client machine.
An applet container is the web browser and Java Plug-in combination running on the client
machine.
java EE APIs
The Java 2 Platform, Standard Edition (J2SE) SDK is required to run the Java EE SDK and provides
core APIs for writing Java EE components, core development tools, and the Java virtual
machine1. The Java EE SDK provides the following APIs to be used in Java EE applications.
Enterprise JavaBeans Technology 2.0
Enterprise bean as a building block that can be used alone or with other enterprise
beans to execute business logic on the Java EE server. An enterprise bean is a body of code with
fields and methods to implement modules of business logic.
JDBC 2.0 API
The JDBC API lets you invoke SQL commands from Java programming language methods.
Java Servlet Technology 2.3
Java Servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the
capabilities of servers that host applications accessed by way of a request-response
programming model.
JavaServer Pages (JSP)
JSP pages technology lets you put combine snippets of Java programming language code with
static markup in a text-based document.

Java Message Service (JMS) 1.0


The JMS API is a messaging standard that allows Java EE application components to create,
send, receive, and read messages. It enables distributed communication that is loosely coupled,
reliable, and asynchronous.
Java Transaction API (JTA) 1.0
The JTA API provides a standard demarcation interface for demarcating transactions. The Java
EE architecture provides a default auto commit to handle transaction commits and roll backs.
JavaMail
Many Internet applications need to send email notifications so the Java EE platform includes
the JavaMail API with a JavaMail service provider that application components can use to send
Internet mail.
SERVLETS

2. Explain the life cycle of a servlet and the way a request to a servlet is handled by the
servlet container with a flow chart.

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded : - The classloader is responsible to load the servlet class. The
servlet class is loaded when the first request for the servlet is received by the web
container.
2. Servlet instance is created:- The web container creates the instance of a servlet after
loading the servlet class. The servlet instance is created only once in the servlet life
cycle.
3. init method is invoked:- The web container calls the init method only once after
creating the servlet instance. The init method is used to initialize the servlet. It is the life
cycle method of the javax.servlet.Servlet interface.
4. service method is invoked:- The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it follows the first three
steps as described above then calls the service method. If servlet is initialized, it calls the
service method. Notice that servlet is initialized only once.
5. destroy method is invoked:- The web container calls the destroy method before
removing the servlet instance from the service. It gives the servlet an opportunity to
clean up any resource for example memory, thread etc.

3. Code a web.xml and servlet that reads two servlet initialization parameters and returns
them to the client as response.

Web.xml

<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
DemoServlet

import java.io.IOException;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String uname=config.getInitParameter("username");
out.print("username is: "+uname);
String psw=config.getInitParameter("password");
out.print("username is: "+psw);
out.close();
}
}

4. Code a servlet that takes Regd.No. and the Name of a student and inserts in the rolls
table of student database.

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>Add New student</h1>


<form action="InsertServlet" method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
<tr><td>Registered
No:</td><td><input type="text" name="regdno"/></td></tr>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>

</table>
</form>
<br/>
</body>
</html>

InsertServlet.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/InsertServlet")
public class SaveServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse res
ponse) throws ServletException, IOException {
String dbURL = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "secret";
try
{
Connection conn = DriverManager.getConnection(dbURL, username,
password);
if (conn != null)
{
System.out.println("Connected");
}
}
catch (SQLException ex)
{
ex.printStackTrace();
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();

String rno=request.getParameter("regdno");
String name=request.getParameter("name");
String sql = "INSERT INTO Users (regno, name) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, rno);
statement.setString(2, name);
if(status>0){
out.print("<p>Record inserted successfully!</p>");
request.getRequestDispatcher("index.html").include(request, response);

}else{
out.println("Sorry! unable to save record");
}

out.close();
}
}
JDBC

5. Explain the classes and interfaces needed to code a JDBC application.

JDBC API is available in two packages java.sql, core API and javax.sql JDBC optional packages.
Following are the important classes and interfaces of JDBC.

Class/interface Description

DriverManager This class manages the JDBC drivers. You need to register your
drivers to this.
It provides methods such as registerDriver() and getConnection().

Driver This interface is the Base interface for every driver class i.e. If you
want to create a JDBC Driver of your own you need to implement
this interface. If you load a Driver class (implementation of this
interface), it will create an instance of itself and register with the
driver manager.

Statement This interface represents a static SQL statement. Using the


Statement object and its methods, you can execute an SQL
statement and get the results of it.
It provides methods such as execute(), executeBatch(),
executeUpdate() etc. To execute the statements.

PreparedStatement This represents a precompiled SQL statement. An SQL statement is


compiled and stored in a prepared statement and you can later
execute this multiple times. You can get an object of this interface
using the method of the Connection interface named
prepareStatement(). This provides methods such as
executeQuery(), executeUpdate(), and execute() to execute the
prepared statements and getXXX(), setXXX() (where XXX is the
datatypes such as long int float etc..) methods to set and get the
values of the bind variables of the prepared statement.

CallableStatement Using an object of this interface you can execute the stored
procedures. This returns single or multiple results. It will accept
Class/interface Description

input parameters too. You can create a CallableStatement using


the prepareCall() method of the Connection interface.
Just like Prepared statement, this will also provide setXXX() and
getXXX() methods to pass the input parameters and to get the
output parameters of the procedures.

Connection This interface represents the connection with a specific database.


SQL statements are executed in the context of a connection.
This interface provides methods such as close(), commit(),
rollback(), createStatement(), prepareCall(), prepareStatement(),
setAutoCommit() setSavepoint() etc.

ResultSet This interface represents the database result set, a table which is
generated by executing statements. This interface provides getter
and update methods to retrieve and update its contents
respectively.

ResultSetMetaData This interface is used to get the information about the result set
such as, number of columns, name of the column, data type of the
column, schema of the result set, table name, etc
It provides methods such as getColumnCount(), getColumnName(),
getColumnType(), getTableName(), getSchemaName() etc.

6. Code a JDBC program that creates books table in the library database with bid and
bname as the columns.

public class CreateTable


{
public static void main(String[] args) throws Exception
{
String driver="org.apache.derby.jdbc.ClientDriver";
String url="jdbc:derby://localhost:1527/library";
String user="ram";
String psw="ram";
Class.forName(driver);
Connection con=DriverManager.getConnection(url,user,psw);
Statement st=con.createStatement();
String sql = "CREATE TABLE books " +
"(bid INTEGER not NULL, " +
" bname VARCHAR(255))";

st.executeUpdate(sql);
System.out.println("successfully created");
}

}
7. Code a JDBC program that deletes a book from the books table in the library database.

public class DeleteTable


{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.println(“Enter book id to delete”);


int bid= Integer.parseInt(br.readLine());
String driver="org.apache.derby.jdbc.ClientDriver";
String url="jdbc:derby://localhost:1527/library";
String user="ram";
String psw="ram";
Class.forName(driver);
Connection con=DriverManager.getConnection(url,user,psw);
Statement st=con.createStatement();

System.out.println(“Enter book id”);


String sql = "DELETE FROM books " + "WHERE id =”+bid;
st.executeUpdate(sql);
System.out.println("deletion successful ");
}
}

8. Design a JDBC program that connects to a dept table of emp database and prints the
details of all the departments.

public class DisplayTable


{
public static void main(String[] args) throws Exception
{
String driver="org.apache.derby.jdbc.ClientDriver";
String url="jdbc:derby://localhost:1527/emp";
String user="ram";
String psw="ram";
Class.forName(driver);
Connection con=DriverManager.getConnection(url,user,psw);
Statement st=con.createStatement();
String sql = "select * from dept";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", name: " + name);
System.out.println();
}
rs.close();
}
}

You might also like