MCA (5) /051/assign/2011: Datapage - JSP
MCA (5) /051/assign/2011: Datapage - JSP
MCA (5) /051/assign/2011: Datapage - JSP
There are eight questions in this assignment. Each question carries 10 marks. Rest 20
marks are for viva-voce. Answer all the questions. You may use illustrations and diagrams
to enhance the explanations. Please go through the guidelines regarding assignments given
in the Programme Guide for the format of presentation.
Question 1:
Write an application to create a XML document from a university employee database .The XML
document should contain the following:
i) Employee code
ii) Employee Name
iii) Designation
iv) Address
v) Department
vi) The last twelve month performance summary
Question 2:
Assume there is a student database in Oracle with the following fields:
Student enrollment No.
Student Name
Program
Address
School of Study
Write a code for Servelet which will display all the fields of the student database in the tabular manner.
Datapage.jsp
<%@page language="java" import="java.util.*" %>
<html>
<head>
<title>Data Page</title>
</head>
<body>
<table border="1" width="303">
<tr>
<td width="119"><b>ID</b></td>
<td width="168"><b>Message</b></td>
</tr>
<%Iterator itr;%>
%>
<tr>
<td width="119"><%=itr.next()%></td>
<td width="168"><%=itr.next()%></td>
</tr>
<%}%>
</table>
</body>
</html>
DataServelet.java
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
String page="DataPage.jsp";
throws ServletException{
this.config=config;
String connectionURL =
"jdbc:mysql://192.168.10.59/messagepaging";
Connection connection=null;
ResultSet rs;
response.setContentType("text/html");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
"root", "root");
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
dataList.add(rs.getString("message"));
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
request.setAttribute("data",dataList);
//Disptching request
RequestDispatcher dispatcher =
request.getRequestDispatcher(page);
if (dispatcher != null){
dispatcher.forward(request, response);
web.xml
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/DataServlet</url-pattern>
</servlet-mapping>
Question 3:
Write a web based student registration application where students can register online with their enrolment
number. The registered students should be able to log on to the site after getting registered. You are
required to use JSP, Servlet and JDBC.
StudentRegistration
│ index.html
│ login.html
│
└───WEB-INF
│ web.xml
│
└───classes
login.class
login.java
regform.class
regform.java
Index.html
<html>
<head>
<title>registration</title>
</head>
<body>
<form method="post" action="reg">
NAME:<input type="text"name="t1"/><br>
ENROLLMENT:<input type="text"name="t2"/><br>
PASSWORD:<input type="password"name="t3"/><br>
<input type="submit"value="send"/><br>
</form>
<a href='login.html'>if already registered plz login</a>
</body>
</html>
login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="login">
<h2>ENTER VALID USER NAME AND PASSWORD</h2>
<p><strong>USER NAME:</strong>
<input type="text"name="t1"/><br>
<strong>PASSWORD:</strong>
<input type="password"name="t2"/><br>
<input type="submit"value="Login"/><br>
</p>
</form>
<a href='index.html'>new user create account</a>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>regform</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
regform.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class regform extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String e=req.getParameter("t2");
String p=req.getParameter("t3");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("insert into student
values(?,?,?)");
st.clearParameters();
st.setString(1,n);
st.setInt(2,Integer.parseInt(e));
st.setString(3,p);
st.executeUpdate();
con.close();
}catch(Exception ex){
ex.printStackTrace(System.out);
}
out.write("ur account has been created, <a href='login.html'>u can login
now</a>");
}
}
login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String p=req.getParameter("t2");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("select * from student where
name=? and pass=?");
st.clearParameters();
st.setString(1,n);
st.setString(2,p);
ResultSet rs=st.executeQuery();
boolean b=rs.next();
if(b==true){
out.write("WELCOME");
}
else{
out.write("Login failed <a href='login.html'>TRY AGAIN</a>");
}
con.close();
}catch(Exception ex){
ex.printStackTrace(System.out);
}
}
}
Question 4:
For a shopping website you have to select Entity beans over stateful session beans. Justify your selection
criteria.
An entity bean represents data in a storage medium, such as a relational database. Each entity bean may
correspond to a table in a relational database, and each instance of the bean corresponds to a row in that
table. Entity beans are not limited to representing relational databases. They can represent data in other
types of data stores. But the majority of enterprise applications that use EJB technology access data in
relational databases, so this article focuses on that type of data store.
The emphasis here is on the word "represents." An entity bean in not part of a relational
database, but rather contains data that is loaded from the database at appropriate points in time.
The data is then written back to the database at other appropriate points in time.
While you are free to write your application and enterprise bean code according to your own needs, we do
recommend certain guidelines.
Keep the code in enterprise beans as "client-neutral" as possible. Enterprise beans are meant
to contain business logic that can be used by many client types. Methods in enterprise beans
that serve only one client type make any logic within that method inaccessible to other client
types. Code that is specific for a particular client type belongs with the software managing
that client type. In particular, Web-tier and HTTP-related functions and data do not belong in
an enterprise bean.
Keep as much business logic as possible in the EJB tier. By doing so, you take advantage of
the EJB container services and simplify your programming effort.
Use stateful session beans to manage conversational state rather than managing
conversational state in the client or Web tier. As with the previous point, this leverages the
advantages of enterprise beans.
In addition to the guidelines discussed previously for choosing specific bean types, there are
other design choices that you need to make when developing objects for the EJB tier. These
choices include the types of objects that should be enterprise beans, and the role an enterprise
bean may play in a group of collaborating components.
You may also need to consider the services provided by enterprise beans and the EJB container,
and decide whether these services benefit your application. You should take into consideration
these EJB services and advantages:
The EJB architecture handles such system services as transaction management, security,
scalability, persistent data access, distributed processing, and concurrency. An enterprise
bean developer does not have to include code to handle these services. As a developer, you
can focus on the application and business logic.
Enterprise beans support multiple types of components.
Enterprise beans support applications with a complex series of operations and accumulation
of conversation state over time.
Enterprise beans are portable across hardware platforms, operating systems, server
implementations, and databases .
Enterprise beans can be easily customized in the runtime environment.
Enterprise beans are reusable software modules.
A facade provides a unified interface to a set of interfaces. This section describes when and how to use a
session bean as a facade to entity beans.
Entity beans represent an object-oriented view of data and provide business logic to manipulate
this data. In an enterprise environment, entity beans often need to be shared among different
applications representing different tasks. In such cases, use of application-specific stateful
session beans to manage the interaction of various entity beans provides a simpler interface to
the client by giving the client a central point of entry. The client always interacts with this
session bean and is unaware of the existence of other entity beans in the system. However, if the
client interacts with only a few entity beans in a relatively simple way, the entity beans can be
exposed directly.
Stateful session beans are logical extensions of the client programs. The decision to use one or
many session bean facades depends on the types of clients the application supports. Since the
sample application has only a single type of client, the shopping client, the sample application
uses a single stateful session bean called ShoppingClientFacadeLocal. It's easy to
imagine another client that would provide administration functionality such as inventory and
order status monitoring. The work flow of such a client would be entirely different from a
shopping client. Therefore, it is advisable to define another stateful session bean that
encapsulates this administrative work flow. However, it is not recommended that a session bean
be created as a facade for every entity bean in the system, as that approach would waste server
resources.
An entity bean differs from a session bean in several ways. An entity bean can be shared (a session bean
cannot), that is, multiple clients can use the same entity bean. The gives multiple clients the ability to
access the same data that the bean represents. Of course, this is where the transaction management (and
its data integrity control) provided by the EJB container is important. In addition, entity beans are
persistent. This means that the entity bean's state exists even after the application that uses it ends. The
bean is persistent because the database that underlies it is persistent. For that matter, the entity bean's state
can be reconstructed even after a server crash (because the database can be reconstructed). Remember that
the state of a stateful session bean exists only for the life of the client-bean session, and for a stateless
session bean, only during the life of a method. Also, an entity bean can have relationships with other
entity beans, much like a table in a relational database can be related to another table. For example, in a
college enrollment application, an entity bean that represents data about students might be related to an
entity bean that represents data about classes. By comparison, a session bean cannot be related to other
session beans.
Question 5:
Why is XML more suitable than HTML for use in the web? With the help of an example briefly explain
the structure of XML documents and its components
XML stands for Extensible Markup Language (often written as extensible Markup Language to justify the
acronym). A markup language is a specification that adds new information to existing information while
keeping two sets of information separate and XML is a set of rules for defining semantic tags that break a
document into parts and identifies the different parts of the document. It is a meta-markup language that
defines a syntax that is in turn used to define other domain-specific, semantic, structured markup
languages. With XML we can store the information in a structured manner.
Comparison of HTML and XML
XML differs from HTML in many aspects. As, we already know, HTML is a markup language used for
displaying information, while XML markup is used for describing data of virtually any type. In other
words, we can say that HTML deals with how to present whereas XML deals with what to present.
Actually, HTML is a markup language whereas XML is a markup language and a language for creating
markup languages. HTML limits you to a fixed collection of tags and these tags are primarily used to
describe how content will be displayed, such as, making text bold or italiced or headings etc., whereas
with XML you can create new or any user defined tags. Hence, XML enables the creation of new markup
languages to markup anything imaginable (such as Mathematical formulas, chemical formulas or
reactions, music etc.)
Let us, understand the difference between HTML and XML with the help of an example. In HTML a
song might be described using a definition title, definition data, an unordered list, and list items. But none
of these elements actually have anything to do with music. The HTML might look something like this
<HTML>
<body>
<dt>Indian Classical </dt>
<dd> by HariHaran , Ravi shankar and Shubha Mudgal</dd>
<ul>
<li>Producer: Rajesh
<li>Publisher: T-Series Records
<li>Length: 6:20
<li>Written: 2002
<li>Artist: Village People
</ul>
<body>
</html>
<XML>
<SONG>
<TITLE>Indian Classical</TITLE>
<COMPOSER>Hariharan</COMPOSER>
<COMPOSER>Ravi Shankar</COMPOSER>
<COMPOSER>Shubha Mudgal</COMPOSER>
<PRODUCER>Rajesh</PRODUCER>
<PUBLISHER>T-Series</PUBLISHER>
<LENGTH>6:20</LENGTH>
<YEAR>2002</YEAR>
<ARTIST>Village People</ARTIST>
</SONG></XML>
Question 6:
Explain SSL and TLS with their working and security measures.
Secure Socket Layer (SSL) and Transport Layer Security (TLS), its successor, are cryptographic
protocols which provide secure communication on the Internet for as e-mail, internet faxing, and other
data transfers.
Description
SSL provides endpoint authentication and communication privacy over the Internet using cryptography.
In typical use, only the server is authenticated (i.e. its identity is ensured) while the client remains
unauthenticated; mutual authentication requires public key infrastructure (PKI) deployment to clients.
The protocols allow client/server applications to communicate in a way designed to prevent
eavesdropping, tampering, and message forgery.
During the first phase, the client and server negotiation uses cryptographic algorithms. Current
implementations support the following choices:
• For public-key cryptography: RSA, Diffie-Hellman, DSA or Fortezza;
• For symmetric ciphers: RC2, RC4, IDEA, DES, Triple DES or AES;
• For one-way hash functions: MD5 or SHA.
SSL working
The SSL protocol exchanges records. Each record can be optionally compressed, encrypted and packed
with a Message Authentication Code (MAC). Each record has a “content type” field that specifies which
upper level protocol is being used.
When the connection begins, the record level encapsulates another protocol, the handshake protocol. The
client then sends and receives several handshake structures:
• It sends a ClientHello message specifying the list of cipher suites, compression methods and the highest
protocol version it supports. It also sends random bytes
which will be used later.
• Then it receives a ServerHello, in which the server chooses the connection parameters from the choices
offered by the client earlier.
• When the connection parameters are known, client and server exchange certificates (depending on the
selected public key cipher). These certificates are currently X.509, but there is also a draft specifying the
use of OpenPGP based certificates.
• The server can request a certificate from the client, so that the connection can be mutually authenticated.
• Client and server negotiate a common secret called “aster secret”, possibly using the result of a Diffie-
Hellman exchange, or simply encrypting a secret with a public key that is decrypted with the peer’s
private key. All other key data is derived from this “master secret” (and the client- and server-generated
random values), which is passed through a carefully designed “Pseudo Random Function”.
TLS/SSL have a variety of security measures:
Numbering all the records and using the sequence number in the MACs.
Using message digest enhanced with a key.
Protection against several known attacks (including man in the middle attacks),
The message that ends the handshake (“Finished”) sends a hash of all the
The pseudo random function splits the input data in 2 halves and processes them
with different hashing algorithms (MD5 and SHA), then XORs them together.
This way it protects itself in the event that one of these algorithms is found to be
vulnerable.
Public key cryptography is a form of cryptography which generally allows users to
communicate securely without having prior access to a shared secret key. This is done
by using a pair of cryptographic keys, designated as public key and private key, which
The term asymmetric key cryptography is a synonym for public key cryptography
though a somewhat misleading one. There are asymmetric key encryption algorithms
that do not have the public key-private key property noted above. For these
algorithms, both keys must be kept secret, that is both are private keys.
In public key cryptography, the private key is kept secret, while the public key may be
widely distributed. In a sense, one key “locks” a lock; while the other is required to
unlock it. It should not be possible to deduce the private key of a pair, given the public
• Public key encryption keeping a message secret from anyone that does not
• Public key digital signature allowing anyone to verify that a message was
• Key agreement generally, allowing two parties that may not initially share a
Question 7:
What are the advantages of using an Entity Bean for database operations over directly using JDBC
API to do the same? When would I need to use one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API.
There are two types of Entity Beans - Container Managed and Bean Mananged. In a Container Managed
Entity Bean – Whenever, the instance of the bean is created, the container automatically retrieves the data
from the DB/Persistance storage and assigns to the object variables in the bean for the user to manipulate
or use them. For this, the developer needs to map the fields in the database to the variables in deployment
descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - the developer has to
specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be
called for, by the container when it instatiates a bean object. Similarly, in the ejbStore() the container
saves the object values back to the persistance storage. ejbLoad and ejbStore are callback methods and
can only be invoked by the container. Apart from this, when you are use Entity beans you do not need to
worry about database transaction handling, database connection pooling etc. which are taken care of by
the ejb container. But, in case of JDBC you have to explicitly take care of the above features. The great
thing about the entity beans is that container managed is, that, whenever the connection fail during
transaction processing, the database consistancy is mantained automatically. The container writes the data
stored at persistant storage of the entity beans to the database again to provide the database consistancy.
Whereas in jdbc api, developers need to maintain the consistency of the database manually.
Question 8:
Explain database handling in JSP using type 2 and type 4 drivers.
There are many possible implementations of JDBC drivers. These implementations are
categorized as follows:
Type 1: Drivers that implement the JDBC API as a mapping to another data access API,
such as ODBC (Open Database Connectivity). Drivers of this type are generally
dependent on a native library, which limits their portability. The JDBC-ODBC Bridge
driver is an example of a Type 1 driver.
Type 2: Drivers that are written partly in the Java programming language and partly in
native code. These drivers use a native client library specific to the data source to which
they connect. Again, because of the native code, their portability is limited. Oracle's OCI
(Oracle Call Interface) client-side driver is an example of a Type 2 driver.
Type 3: Drivers that use a pure Java client and communicate with a middleware server
using a database-independent protocol. The middleware server then communicates the
client's requests to the data source.
Type 4: Drivers that are pure Java and implement the network protocol for a specific data
source. The client connects directly to the data source.
The JDBC type 2 driver, also known as the Native-API driver is a database driver
implementation that uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API.
The type 2 driver is not written entirely in Java as it interfaces with non-Java code that
makes the final database calls.
The driver is compiled for use with the particular operating system. For platform
interoperability, the Type 4 driver, being
a full-Java implementation, is preferred over this driver.
A native-API partly Java technology-enabled driver converts JDBC calls into calls on the
client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge
driver, this style of driver requires that some binary code be loaded on each client machine.
However the type 2 driver provides more functionality and performance than the type 1
driver as it does not have the overhead of the additional ODBC function calls.
Type 2 drivers use a native API to communicate with a database system. Java native
methods are used to invoke the API functions that perform database operations. Type 2
drivers are generally faster than Type 1 drivers.
Type 2 drivers need native binary code installed and configured to work. A Type 2 driver
also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load
native code. A Type 2 JDBC driver may require some Database Management System
(DBMS) networking software to be installed.
The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.
Functions:
1. This type of driver converts JDBC calls into calls to the client API for that database.
2. Client -> JDBC Driver -> Vendor Client DB Library -> Database
Advantage
Disadvantages
1. The vendor client library needs to be installed on the client machine.
2. Cannot be used in internet due the client side software needed.
3. Not all databases give the client side library.
The JDBC type 4 driver, also known as the native-protocol driver is a database driver
implementation that converts JDBC calls directly into the vendor-specific database
protocol.
The type 4 driver is written completely in Java and is hence platform independent. It is
installed inside the Java Virtual Machine of the client. It provides better performance over
the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC
or database API calls. Unlike the type 1 and 2 drivers, it does not need associated
software to work.
A native-protocol fully Java technology-enabled driver converts JDBC technology calls into
the network protocol used by DBMSs directly. This allows a direct call from the client
machine to the DBMS server and is a practical solution for Intranet access. Since many of
these protocols are proprietary the database vendors themselves will be the primary
source for this style of driver. Several database vendors have these in progress.
A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the
protocols are usually proprietary, DBMS vendors are generally the only companies
providing a Type 4 JDBC driver.
Type 4 drivers are all Java drivers. This means that there is no client installation or
configuration. However, a Type 4 driver may not be suitable for some applications if the
underlying protocol does not handle issues such as security and network connectivity well.
The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API
is a pure Java networking protocol driver.
Functions
1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's
database through socket connections. No translation or middleware layers, are required,
improving performance.
2. The driver converts JDBC calls into the vendor-specific database protocol so that client
applications can communicate directly with the database server.
3. Completely implemented in Java to achieve platform independence.
4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which
connect to jdbc:oracle:thin URL format.
5. Client Machine -> Native protocol JDBC Driver -> Database server
Advantages
These drivers don't translate the requests into db request to ODBC or pass it to client api for the
db, nor do they need a middleware layer for request indirection. Thus the performance is
considerably improved.
Disadvantage