Servlets and JDBC
Servlets and JDBC
Servlets and JDBC
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
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.
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>
</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
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.
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
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.
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.
8. Design a JDBC program that connects to a dept table of emp database and prints the
details of all the departments.