Enterprise Java: Time: 2 HRS.) (Marks: 75
Enterprise Java: Time: 2 HRS.) (Marks: 75
V
Enterprise Java
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
-1-
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
object.
3. Initialization :
Web server Servlet process
In this when a servlet gets its first request, web delegates the the request using
server initializes that servlet using init( ). request to a the service( )
servlet
4. Service :
Once the servlet gets initialized it accepts the
request and provides the response to client by using Servlet
Servlet waits
service( ) provides the
for the other
responses to the
The same servlet will wait for some other request request
client
and generate responses for them.
5. Destruction :
In this if a servlet does not get request, a web Web server
Web server
server will destroy that servlet using destroy( ), to destroys servlet
unloads the
memory of the
unload its memory so that the same memory can be using destroy( )
servlet.
used for some other purpose.
-2-
Prelim Question Paper Solution
//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(c.equals("rm"))
{
correct++;
-3-
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
}
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();
}
}
}
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.
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.
-4-
Prelim Question Paper Solution
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.
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.
Q.1(f) Write a program to accept details of a person & using servlet store those details [5]
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
{
-5-
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
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();
}
}
//login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
-6-
Prelim Question Paper Solution
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String s=req.getParameter("p");
if(s.equals("servlet"))
{
RequestDispatcher rd=req.getRequestDispatcher("welcomeservlet");
rd.forward(req, res);
}
else
{
pw.println("Sorry username or password error !!!");
}
pw.close();
}
}
//welcomeservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
-7-
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
Q.2(c) Create a servlet that uses cookies to store number of times an user has visited [5]
servlet.
Ans.: //index.jsp
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<form method="post" action="VisitServlet">
<h1>Hello World!</h1>
<input type="submit" value="Count">
</form>
</body>
</html>
//VisitServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VisitServlet extends HttpServlet
{
static int i=1;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("Welcome");
}
else
{
out.println("You visited "+i+" times");
}
i++;
}
}
-8-
Prelim Question Paper Solution
Working :
1) When a client first time sends a request to a servlet, client sends only the request
packet.
2) Servlet processes the request, creates a session memory generate session ID and send
that session ID along with a response.
3) Next time if a same client wants to send a request to the same servlet, it sends the
request packet along with session ID.
4) Using that session ID, servlet recognizes a particular session memory update that
session memory, generate new ID and sends it along with the response.
1. http request
2. http response with session Web
Client
3. http request with session Server
//FileUploadServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/FileUploadServlet"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = retrieveFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
-9-
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
- 10 -
Prelim Question Paper Solution
out.println("<body>");
out.println("<h1>File Uploaded Successfully</h1>");
out.println("<a href='index.jsp'>Click here to upload more files</a>");
out.println("</body>");
out.println("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileToDownload = request.getParameter("filename");
System.err.println("Downloading file now...");
downloadFile(request, response, fileToDownload);
}
private void downloadFile(HttpServletRequest request, HttpServletResponse response,
String fileName) throws ServletException, IOException
{
int lenght = 0;
ServletOutputStream outputStream = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
response.setContentType((context.getMimeType(fileName) != null) ?
context.getMimeType(fileName) : "application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
InputStream inputStream = context.getResourceAsStream("/" + fileName);
byte[ ] bytes = new byte[1024];
- 11 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
(ii) Include Directive Tag : It is used to include the contents of one JSP into the current
JSP.
Example :
<%@ include file = "abc.jsp"%>
(iii) Taglib Directive Tag : If we want to use some special tags other than html and jsp
inside jsp program, then those tags can be used with the help of taglib directive tag.
Example :
<% @ taglib uri = " www.w3.org"%>
2) Declaration Tag : If we want to declare certain variables inside JSP page then it can
be declared using declaration tag.
Example :
<%!int a = 0 %>
4) Scriptlets Tag : If we want to write a java code inside jsp page, so that it will get
exeulted like a java then it can be written using scriptlets tag.
- 12 -
Prelim Question Paper Solution
Example :
<%
_______
_______
Java code
_______
_______
%>
5) Comment Tag : If we want to display a comment inside JSP then it can get displayed
using comment tag.
Example :
< % comment % >
3) useBean :
It is mainly used to use a particular Bean (a Java class) inside the JSP application.
By using a Bean we can use or access property of that Bean without the object.
Example :
<jsp : useBean id = "abc" class = "A">
…
…
</jsp : useBean>
It has 2 parameters :
(a) name : It represents name of Bean.
(b) property : It represents name of the property.
- 13 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
Example :
<jsp:useBean id = "abc" class = "A">
<jsp: setProperty name = "abc"
property = "name" value = "sss"/>
<jsp: getProperty name = "abc"
property = "name"/>
</jsp: useBean>
Q.3(d) Create a registration and login.jsp application to register and authenticate [5]
the user based on username and password using JDBC.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="login.jsp">
<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>
//login.jsp
<html>
<body>
<%@page import="java.sql.*" %>
<%
String username = request.getParameter("u");
String password = request.getParameter("p");
out.println(username);
out.println(password);
Class.forName("com.mysql.jdbc.Driver");
Connection c=DriverManager.getConnection
("jdbc:mysql://localhost/jspdb","root","root");
PreparedStatement statement = c.prepareStatement("select firstname, password
from registration where firstname =? and password=?");
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
if(result.next())
{
out.println("Login Successful");
}
else
{
out.println("username and password are incorrect");
}
%>
</body>
</html>
- 14 -
Prelim Question Paper Solution
JSP EL allows us to create expressions both (a) arithmetic and (b) logical.
Within a JSP EL expression, we can use integers, floating numbers, strings, boolean values,
and null.
Simple Syntax :
When we specify an attribute value in a JSP tag, we simply use a string.
For example :
<jsp:setProperty name = "rectangle" property = "perimeter" value = "100"/>
Here expression specifies the expression itself. The most common operators in JSP EL
are . and []. These two operators allows us to access various attributes of Java Beans and
built-in JSP objects.
For example, the above syntax <jsp:setProperty> tag can be written with an expression like :
<jsp:setProperty name = "rectangle" property = "perimeter"
value = "${2*rectangle.width+2*rectangle.height}"/>
When the JSP compiler sees the ${} substitutes the value of expression.
We can also use the JSP EL expressions within template text for a tag.
For example, the <jsp:text> tag simply inserts its content within the body of a JSP. The
following <jsp:text> declaration inserts <h1>Hello!</h1>into the JSP output :
<jsp:text>
<h1>Hello!</h1>
</jsp:text>
We can now include a JSP EL expression in the body of a <jsp:text> tag (or any other tag)
with the same ${} syntax you use for attributes. For example :
<jsp:text>
Rectangle Perimeter is: ${2*rectange.width + 2*rectangle.height}
</jsp:text>
The valid values of this attribute are true and false. If it is true, EL expressions are
ignored and if it is false, EL expressions are evaluated by the container.
- 15 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
<body>
<c:if test="${pageContext.request.method=='POST'}">
<c:if test="${param.guess=='Java'}">You guessed it!
<br />
<br />
<br />
</c:if>
<br />
<br />
</c:if>
</c:if>
<br />
</form>
</body>
</html>
Characteristics :
1) It is a single (short) lived bean.
2) They are transaction oriented.
3) They cannot be create using data from the database but has the ability to change
the database.
4) They are synchronous in nature i.e. client and server needs to be connect while
accessing them.
5) They can be stateful or stateless.
6) They can be used with the help of home interface.
- 16 -
Prelim Question Paper Solution
(ii) Message driven beans : Those are the beans which will get used when a particular
event will get generated for those beans.
Characteristics :
1) It is single (short) lived beans.
2) They are transaction oriented.
3) They cannot be created using data from the database, but has the ability to change
the database.
4) They are a synchronous in nature.
5) They are stateless.
6) They cannot be used with the help of home interface.
- 17 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
// ConvertCurrencyServlet.java (Servlet)
import ejb.CurrencyConverterBean;
import java.io.*;
import java.io.PrintWriter;
import java.math.*;
import javax.ejb.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
public class ConvertCurrencyServlet extends HttpServlet
{
@EJB
CurrencyConverterBean converterBean;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String amount = request.getParameter("amount");
if (amount != null && amount.length() > 0)
{
BigDecimal d = new BigDecimal(amount);
BigDecimal convertedAmount = converterBean.convert
(request.getParameter("From"), request.getParameter("To"), d);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Converted Currency</title>");
out.println("</head>");
out.println("<body>");
out.println(amount + " " + request.getParameter("From") + " = ");
out.println(convertedAmount + " " + request.getParameter("To"));
out.println("</body>");
out.println("</html>");
}
}
}
- 18 -
Prelim Question Paper Solution
else
{
BigDecimal toRate = findRate(to);
BigDecimal result = toRate.multiply(amount);
return result.setScale(2, BigDecimal.ROUND_UP);
}
}
The various state transitions as well as the methods available during the various states are
discussed below :
ejbCreate ejbPassivate
Does not Ready Passive
exist ejbActivate
ejbRemote
business method
- 19 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
Q.4 (d) Develop simple EJB application to demonstrate servlet hit count using singleton [5]
session beans.
Ans.: //index.jsp
<html>
<body>
<form method="post" action="ServletClient">
<input type="submit" value="Count">
</form>
</body>
</html>
//ServletClient.java (Servlet)
package servlet;
import ejb.*;
import java.io.*;
import javax.ejb.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ServletClient</title>");
out.println("</head>");
out.println("<body>");
- 20 -
Prelim Question Paper Solution
Q.4 (e) What different things an interceptor can do with request, also explain defining [5]
and interceptor.
Ans.: Every request with passes through each interceptor, An interceptor can,
Ignore the request
Process the request data
Short circuit the request and present the EJB class method from firing
Interceptors have to access the EJB class which is being executed as well as all
environmental variables & execution properties.
Defining an interceptors :
Interceptors methods can be used to intercept either a business method or lifecycle
plant.
An intercaptors that intercepts a business method is typically called an AroundInvoke
Method because it can be defined by annotating the method an @AroundInvoke
annotation.
An AroundInvoke method can be defined as :
- Enterprise bean class
- Interceptor class
An Interceptor class is a normal class which does not extend any class or implement any
interface.
- 21 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
Consider the following Java Class with proper constructors and associated public function :
public class Employee
{
private int id;
private String first_name;
private String last_name;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary)
{
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
- 22 -
Prelim Question Paper Solution
return first_name;
}
Second, loading and storing objects in a relational database exposes us to the following five
mismatch problems :
Mismatch Description
1 Granularity Sometimes you will have an object model, which has more classes
than the number of corresponding tables in the database.
2 Inheritance RDBMSs do not define anything similar to Inheritance, which is a
natural paradigm in object-oriented programming languages.
3 Identity An RDBMS defines exactly one notion of 'sameness': the primary
key. Java, however, defines both object identity (a==b) and
object equality (a.equals(b)).
4 Associations Object-oriented languages represent associations using object
references whereas an RDBMS represents an association as a
foreign key column.
5 Navigation The ways you access objects in Java and in RDBMS are
fundamentally different.
The Object-Relational Mapping (ORM) is the solution to handle all the above impedance
mismatches.
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming languages
such as Java, C#, etc.
- 23 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
Persistence
EntityManager
EntityTransactio
Factory
Quer
EntityManager
Criteri
Entity
The following table describes each of the units shown in the above architecture :
Class/ Interface Description
EntityManagerFactory This is a factory class of EntityManager. It creates and
manages multiple EntityManager instances.
EntityManager It is an Interface, it manages the persistence operations
on objects. It works like factory for Query instance.
Entity Entities are the persistence objects, stores as records in
the database.
EntityTransaction It has one-to-one relationship with EntityManager. For
each EntityManager, operations are maintained by
EntityTransaction class.
Persistence This class contain static methods to obtain
EntityManagerFactory instance.
Query It is mainly used to retrieve data from database using
SQL queries
Criteria It is mainly used to retrieve data from database using
different methods
Persistent
Object
Hibernate
(POJO)
Data base
- 24 -
Prelim Question Paper Solution
5. Query : To perform different operation if we want to use different sql queries, then
transaction will create query object.
6. Criteria : To perform different operation if we want to use java methods, then
transaction will create criteria object.
Q.5 (e) Explain structure of guestbook.hbm.xml file (Hibernate mapping file). [5]
Ans.: <?xml version=”1.0” encoding=”UTF8”?>
<hibernatemapping>
<class name=”guestbook” table=”guestbooktable”>
<property name=”name” type=”string”>
<column name=”username” length=”50” />
</property>
<property name=”message” type=”string”>
<column name=”usermessage” length=”100” />
</property>
</class>
</hibernatemapping>
Elements:
<hibernatemapping>….......</hibernatemapping>
It is the base tag which is used to write hibernate mapping file, which is used to map POJO
class with database table.
<class>….......</class>
It represents name of the class and database table which we want to map with each other.
It has 2 parameters:
name It represents name of the class
table It represents name of the database table
<property>….......</property>
It is used to write the property which we want to map with database column. It has 2
parameters:
name It represents name of the property
type It represents type of the property
<column>….......</column>
It is used to write the database column which we want to map with java class property. It
has 2 parameters:
name It represents name of the column
length It represents maximum length of a column value
Q.5 (f) Explain structure of hibernate.sfg.xml file (Hibernate configuration file). [5]
Ans.: <?xml version=”1.0” encoding=”UTF8”?>
<hibernateconfiguration>
<sessionfactory>
<property name=”hibernate.dialect”>
org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.connection.driver_class”>
com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>
jdbc:mysql://localhost/DBname</property>
- 25 -
Vidyalankar : T.Y. B.Sc. (IT) Enterprise Java
<property name=”hibernate.connection.username”>
root</property>
<property name=”hibernate.connection.password”>
root</property>
<mapping resource=”guestbook.hbm.xml”/>
</sessionfactory>
</hibernateconfiguration>
Elements:
hibernate.dialect : It represents the name of the SQL dialect for the database.
hibernate.connection.driver_class : It represents the JDBC driver class for the specific
database.
hibernate.connection.url : It represents the JDBC connection to the database.
hibernate.connection.username : It represents the user name which is used to connect
to the database.
hibernate.connection.password : It represents the password which is used to connect to
the database.
guestbook.hbm.xml : It represents the name of mapping file.
- 26 -