TYBSc - IT - EJ Paper Solution
TYBSc - IT - EJ Paper Solution
As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it
shifts to the end state.
f. Enlist and explain the steps of Database connectivity using JDBC API.
Fundamental Steps in JDBC
The fundamental steps involved in the process of connecting to a database and
executing a query consist of the following:
• Import JDBC packages.
• Load and register the JDBC driver.
• Open a connection to the database.
• Create a statement object to perform a query.
• Execute the statement object and return a query resultset.
• Process the resultset.
• Close the resultset and statement objects.
• Close the connection.
Q2. Attempt any three of the following: 15
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
b. Explain how java handles session management of a servlet application through
HTTPSession.
HttpSession interface
In such case, container creates a session id for each user.The container uses this
id to identify the particular user.An object of HttpSession can be used to perform
two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
c. What is cookie? Explain the need of the creation of the same. Explain the methods
of cookie class that facilitative the creation, manipulation and deletion of the
cookies.
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple
client requests.
A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
Channels
In Java NIO, the channel is a medium that transports the data efficiently between
the entity and byte buffers. It reads the data from an entity and places it inside
buffer blocks for consumption.
Channels act as gateway provided by java NIO to access the I/O mechanism.
Usually channels have one-to-one relationship with operating system file
descriptor for providing the platform independence operational feature.
f. Explain about the file uploading feature of a servlet.
A Servlet can be used with an HTML form tag to allow users to upload files to
the server. An uploaded file could be a text file or image file or any document.
Creating a File Upload Form
The following HTM code below creates an uploader form. Following are the
important points to be noted down −
• The form method attribute should be set to POSTmethod and GET
method can not be used
• The form enctype attribute should be set to multipart/form-data.
• The form action attribute should be set to a servlet file which would handle
file uploading at backend server. Following example is using
UploadServlet servlet to upload file.
• To upload a single file you should use a single <input .../> tag with attribute
type="file". To allow multiple files uploading, include more than one
input tags with different values for the name attribute. The browser
associates a Browse button with each of them.
a. What are directives in JSP? Explain page directive in detail. (With all its attributes)
These directives provide directions and instructions to the container, telling it how
to handle certain aspects of the JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
<%@ directive attribute = "value" %>
Directives can have a number of attributes which you can list down as key-value
pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the last
attribute and the closing %>, are optional.
There are three types of directive tag −
S.No. Directive & Description
buffer
1 Specifies a buffering model for the output stream.
autoFlush
2 Controls the behavior of the servlet output buffer.
contentType
3 Defines the character encoding scheme.
errorPage
Defines the URL of another JSP that reports on Java unchecked
4
runtime exceptions.
isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's
5
errorPage attribute.
extends
6 Specifies a superclass that the generated servlet must extend.
import
Specifies a list of packages or classes for use in the JSP as the Java
7
import statement does for Java classes.
info
Defines a string that can be accessed with the
8
servlet's getServletInfo() method.
isThreadSafe
9 Defines the threading model for the generated servlet.
language
10 Defines the programming language used in the JSP page.
session
Specifies whether or not the JSP page participates in HTTP
11
sessions
isELIgnored
Specifies whether or not the EL expression within the JSP page
12
will be ignored.
b. What is EL? Explain immediate EL, deferred EL, LValue and RValue in detail.
Expression Language (EL) is mechanism that simplifies the accessibility of the
data stored in Java bean component and other object like request, session and
application, etc.
Immediate Evaluation
All expressions using the ${} syntax are evaluated immediately. These
expressions can only be used within template text or as the value of a JSP tag
attribute that can accept runtime expressions.
The following example shows a tag whose value attribute references an
immediate evaluation expression that gets the total price from the session-scoped
bean named cart:
<fmt:formatNumber value="${sessionScope.cart.total}"/>
The JSP engine evaluates the expression, ${sessionScope.cart.total}, converts it,
and passes the returned value to the tag handler.
Immediate evaluation expressions are always read-only value expressions. The
expression shown above can only get the total price from the cart bean; it cannot
set the total price.
Deferred Evaluation
Deferred evaluation expressions take the form #{expr} and can be evaluated at
other phases of a page life cycle as defined by whatever technology is using the
expression. In the case of JavaServer Faces technology, its controller can
evaluate the expression at different phases of the life cycle depending on how the
expression is being used in the page.
The following example shows a JavaServer Faces inputText tag, which
represents a text field component into which a user enters a value.
The inputText tag’s value attribute references a deferred evaluation expression
that points to the name property of the customerbean.
<h:inputText id="name" value="#{customer.name}" />
For an initial request of the page containing this tag, the JavaServer Faces
implementation evaluates the #{customer.name} expression during the render
response phase of the life cycle. During this phase, the expression merely
accesses the value of name from the customerbean, as is done in immediate
evaluation.
<c:catch>
Catches any Throwable that occurs in its body and optionally
4
exposes it.
<c:if>
Simple conditional tag which evalutes its body if the supplied
5
condition is true.
<c:choose>
Simple conditional tag that establishes a context for mutually
6 exclusive conditional operations, marked
by <when> and <otherwise>.
<c:when>
Subtag of <choose> that includes its body if its condition evalutes
7
to 'true'.
<c:otherwise >
Subtag of <choose> that follows the <when> tags and runs only
8
if all of the prior conditions evaluated to 'false'.
<c:import>
9 Retrieves an absolute or relative URL and exposes its contents to
either the page, a String in 'var', or a Reader in 'varReader'.
<c:forEach >
10 The basic iteration tag, accepting many different collection types
and supporting subsetting and other functionality .
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. Enter User Name: <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
index.jsp
1. <form action="process.jsp">
2. No1:<input type="text" name="n1" /><br><br>
3. No2:<input type="text" name="n2" /><br><br>
4. <input type="submit" value="divide"/>
5. </form>
process.jsp
error.jsp
The JSP implicit config object is an instance of the java class that
implements javax.servlet.ServletConfig interface. It gives facility for a JSP
page to obtain the initialization parameters available.
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)pageContext.getAttribute("user",PageContext.SESSI
ON_SCOPE);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
1 Session Bean
Session bean stores data of a particular user for a single session. It
can be stateful or stateless. It is less resource intensive as
compared to entity bean. Session bean gets destroyed as soon as
user session terminates.
2 Entity Bean
Entity beans represent persistent data storage. User data can be
saved to database via entity beans and later on can be retrieved
from the database in the entity bean.
Understanding Messaging
Messaging is a technique to communicate applications or software components.
JMS is mainly used to send and receive message from one application to another.
Requirement of JMS
Generally, user sends message to application. But, if we want to send message
from one application to another, we need to use JMS API.
A message driven bean is like stateless session bean that encapsulates the
business logic and doesn't maintain state.
contextArgs.put( Context.INITIAL_CONTEXT_FACTORY,
"com.jndiprovider.TheirContextFactory" );
// The next argument is the URL specifying where the data store is:
contextArgs.put( Context.PROVIDER_URL, "jndiprovider-database" );
A context is then used to look up previously bound names in that context. For
example:
//just need to create initial context object, it will try to read jndi.properties file
from the classpath.
Context myCurrentContext = new InitialContext();
A context is then used to look up previously bound names in that context. For
example:
Resource injection
One of the simplification features of Java EE is the implementation of basic
Resource Injection to simplify web and EJB components.
Resource injection enables you to inject any resource available in the JNDI
namespace into any container-managed object, such as a servlet, an enterprise
bean, or a managed bean. For eg, we can use resource injection to inject data
sources, connectors, or any other desired resources available in the JNDI
namespace.
The type we’ll use for the reference to the instance happen to be injected is
usually an interface, which would decouple our code from the implementation of
the resource.
For better understanding of the above statement let’s take a look at the example.
The resource injection can be performed in the following three ways:
· Field Injection
· Method Injection
· Class injection
f. Explain the life cycle of an interceptor.
Interceptor classes and methods are defined using metadata annotations, or in the
deployment descriptor of the application containing the interceptors and target
classes.
Interceptor Lifecycle
Interceptor classes have the same lifecycle as their associated target class. When a
target class instance is created, an interceptor class instance is also created for each
declared interceptor class in the target class. That is, if the target class declares
multiple interceptor classes, an instance of each class is created when the target
class instance is created. The target class instance and all interceptor class
instances are fully instantiated before any @PostConstruct callbacks are invoked,
and any @PreDestroy callbacks are invoked before the target class and interceptor
class instances are destroyed.
Q5. Attempt any three of the following: 15
The following table describes each of the units shown in the above architecture.
Units 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
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.
An ORM system has the following advantages over plain JDBC −
Sr.No. Advantages
1 Let’s business code access objects rather than DB tables.