AJava 20MCA33 2022-Feb Solv.
AJava 20MCA33 2022-Feb Solv.
1.b. Write a java servlet program which reads 2 parameters from the web page which are of type integers and
finds the sum of 2 values and return back the result as a web page.
package j2ee.prg1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class program1
*/
@WebServlet("/pro1")
public class program1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public program1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// TODO Auto-generated method stub
// Setting the HTTP Content-Type response header to text/html
resp.setContentType("text/html");
// Returns a PrintWriter object that can send character text
//to the client.
PrintWriter pw=resp.getWriter();
//To retrieve the input values (num1) from HTML page
int n1=Integer.parseInt(req.getParameter("num1"));
// To retrieve the input values (num2) from HTML page
int n2=Integer.parseInt(req.getParameter("num2"));
//writing the output in the html format
pw.println("<html><body>");
pw.println("Sum is "+(n1+n2)+"<br>");
pw.println("</body></html>");
}
}
index.html
1.c. Write any four differences between get and post method.
2.a. Explain briefly any five methods of HTTPServletRequest. Illustrate with a simple program.
There are following methods which can be used to read HTTP header in your servlet program. These methods are
available with HttpServletRequest object.
∙ getCookies
The getCookies method returns the contents of the Cookie header, parsed and stored in an array of Cookie objects.
• getAuthType and getRemoteUser
The getAuthType and getRemoteUser methods break the Authorization header into its component pieces.
• getContentLength
The getContentLength method returns the value of the Content-Length header (as an int). getContentType
The getContentType method returns the value of the Content-Type header (as a String). • getDateHeader and
getIntHeader
The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values,
respectively.
• getHeaderNames
Rather than looking up one particular header, you can use the getHeaderNames method to get an Enumeration of all
header names received on this particular request. • getHeaders
In most cases, each header name appears only once in the request. Occasionally, however, a header can appear
multiple times, with each occurrence listing a separate value. • getMethod
The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and
DELETE are possible).
• getRequestURI
The getRequestURI method returns the part of the URL that comes after the host and port but before the form data.
For example, for a URL of
http://randomhost.com/servlet/search.BookSearch,
getRequestURI would return /servlet/search.BookSearch.
• getProtocol
Lastly, the getProtocol method returns the third part of the request line, which is generally HTTP/1.0 or HTTP/1.1.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class store
*/
@WebServlet("/store")
public class store extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public store() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
retrieve.java
package j2ee.prg4;
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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class retrieve
*/
@WebServlet("/retrieve")
public class retrieve extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public retrieve() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- send the form data to the url store and the post method is used -->
<form action="store" method="post">
<!-- Display the Radio button with three option -->
RED:<input type="radio" name="color" value="RED"/><br>
GREEN:<input type="radio" name="color" value="GREEN"/><br>
BLUE:<input type="radio" name="color" value="BLUE"/><br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Scriplet Tag:
In JSP JAVA code can be written inside the JSP page using Scriplet tag
Syntax:
<% java source code %>
Example:
<html>
<body>
<% out.print(“Hello world…”);%>
</body>
</html>
Expression Tag:
Code placed within expression tag is written to the output stream of the response. So, no need to write out.print() to
write data. It is mainly used to print values of variable or method
Syntax:
<%= Statement %>
Example:
<html>
<body>
<%= “Hello world…” %>
</body>
</html>
<% = new java.util.Date() %>
Note: Do not end statement with semicolon (;)
Declaration tag:
Used to declare fields and methods. The code written inside this tag is placed outside the service() method of auto
generated servlet .So it doesn’t get memory at each request
Syntax:
<%! Statement %>
Example:
<html>
<body>
<%! int data=60;%>
<%= “Value is: “ + data %>
</body>
</html>
3.b. With a neat diagram explain JSP architecture and life cycle phases of JSP.
User sends request through internet via web browser to Web server for a JSP page (extension .jsp).
As per the request, the Web server (here after called as JSP container) loads the page.
Then, loaded jsp page will be moved to the JSP Servlet Engine.
JSP Servlet Engine have two phase to handle the requested JSP page, they are Translation Phase Compilation or
Request processing Phase
(I) Translation Phase: JSP Servlet Engine translates the JSP file into Servlet source code file with extension .java.
This translation is normally done the first time the page is requested.
(II) Compilation Phase: After translated JSP Servlet Engine compiles the .java file of servlet by compiler and gets
converted into .class file.
5. The .class file of Servlet is executed and all the processes that happens in servlet is performed on JSP later like
initialization, output of execution is sent to the client as response.
6. In the end, a JSP is just a Servlet.
4.a. Explain briefly any five JSP implicit objects.
request: Reference to the current request
response: Response to the request
session: session associated with current request
application: Servlet context to which a page belongs
pageContext: Object to access request, response, session and application associated with a page
config: Servlet configuration for the page
out: Object that writes to the response output stream
page: instance of the page implementation class (this)
exception: Available with JSP pages which are error pages
4.b. Explain briefly three life cycle methods of JSP.
A JSP life cycle can be defined as the entire process from its creation till the destruction similar to a servlet life cycle
with an additional step of compiling a JSP into servlet.
The following are the paths followed by a JSP
Compilation – 3 steps
Parsing jsp
Turning the JSP into a servlet
Compiling the servlet
Initialization
Execution
Destroy
JSP Initialization:
- When a container loads a JSP it invokes the jspInit() method before servicing any requests.
- If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit()
{
// Initialization code...
}
- initialization is performed only once
- generally initialize database connections, open files, and create lookup tables in this method.
JSP Execution:
- Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the
_jspService() method in the JSP.
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
- This method is invoked once per request and is responsible for generating the response for that request
JSP Cleanup:
- The destruction phase when a JSP is being removed from use by a container.
- The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
- Override jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.
public void jspDestroy()
{
// Your cleanup code
}
4.c. Write a JSP program to perform arithmetic operation using scriptlet, declaration and expression tag.
<HTML>
<HEAD>
<TITLE>Addition and Subtraction</TITLE>
</HEAD>
<BODY>
<H1>Addition and Subtraction</H1>
<%!
int operand1 = 15, operand2 = 24, sum, difference;
!>
<% ou.print(“sum:”); %>
<%= operand1 + operand2 %>
<% ou.print(“Difference:”); %>
<%= (operand1 - operand2) %>
<%
prod = operand1 - operand2;
quo= operand1/operand2;
out.println(operand1 + " + " + operand2 + " = " + prod + "<BR>");
out.println(operand1 + " - " + operand2 + " = " + quo);
%>
</BODY>
</HTML>
1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to import keyword in
java class or interface.
Example of import attribute
<html>
<body>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.The
default value is "text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>
</body>
</html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of
Servlet interface.
Example of info attribute
<html>
<body>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default size of the
buffer is 8Kb.
Example of buffer attribute
<html>
<body>
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
5.b. Write a JSP program which uses <jsp:include> and <jsp:forward> standard action to display a web page.
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- send the form data to login.jsp and the get method is used -->
<form method="get" action="login.jsp">
UserName : <input type="text" name ="name"><br> Password : <input type="password" name ="pass"><br>
<input type="Submit" value ="Submit"/><br>
</form>
</body>
</html>
login.jsp
<%
}
else
{
<jsp:forward page="main.jsp"></jsp:forward>
out.println("Wrong Credentials Username and Password"+"<br>"); out.println("Enter Corrects Username and
Password.. Try again" +"<br><br>");%>
<jsp:include page="index.jsp"></jsp:include>
<%
}%>
</body>
</html>
main.jsp
class Instantiates the specified bean class (i.e. creates an object of the bean class)
type Provides the bean data type if the bean already exists in the scope.Mainly used with class or
beanName attribute other wise no bean is instantiated
beanName Instantiates the bean using the java.beans.Beans.instantiate() method
<jsp:plugin>
<jsp:plugin> is used to include components like applet.
6.b. Write a Java JSP program to get student information through a HTML and create JavaBean class,
populate Bean and display the same information through an other JSP.
student.java
package program8;
public class stud
{
public String sname;
public String rno;
//Set method for Student name
public void setsname(String name)
{
sname=name;
}
//Get method for Student name
public String getsname()
{
return sname;
}
//Set method for roll no
public void setrno(String no)
{
rno=no;
}
//Get method for roll no
public String getrno()
{
return rno;
}
}
display.jsp
first.jsp
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- send the form data to first.jsp -->
<form action="first.jsp">
Student Name : <input type="text" name = "sname">
Student Roll no : <input type="text" name = "rno">
<input type = "submit" value="Submit"/>
</form>
</body>
</html>
7.a. Explain briefly any 5 built-in annotations with a suitable example.
Built in Annotations:
Java defines many built-in annotations.
These four are the annotations imported from java.lang.annotation: @Retention, @Documented,
@Target,and @Inherited.
@Inherited
@Inherited is a marker annotation that can be used only on another annotation
declaration. it affects only annotations that will be used on class declarations.
@Inherited
causes the annotation for a superclass to be inherited by a subclass. Therefore, when a request
for a specific annotation is made to the subclass, if that annotation is not present in the
subclass,then its superclass is checked. If that annotation is present in the superclass, and if
it is annotated with @Inherited, then that annotation will be returned.
@Override
@Override is a marker annotation that can be used only on methods. A
method annotatedwith @Override must override a method from a superclass.
If it doesn’t, a compile-time error will result. It is used to ensure that a
superclass method is actually overridden, and not simply overloaded.
@Deprecated
@Deprecated is a marker annotation. It indicates that a declaration is obsolete
and has beenreplaced by a newer form.
@SuppressWarnings
@SuppressWarnings specifies that one or more warnings that might be issued by the
compiler are to be suppressed. The warnings to suppress are specified by name, in string
form. This annotation can be applied to any type of declaration.
When a driver class is first loaded, it registers itself with the driver Manager
Therefore, toregister a driver, just load it!
Example:
Ex:
jdbc:msql://foo.nowhere.com:4333/accou
nting
A Statement object is used for executing a static SQL statement and obtaining the
resultsproduced by it.
5. Execute a query
Execute a SQL query such as SELECT, INSERT, DELETE, UPDATE Example
The JDBC type BLOB represents an SQL3 BLOB (Binary Large Object).
A JDBC BLOB value is mapped to an instance of the Blob interface in the Java
programming language.
A Blob object logically points to the BLOB value on the server rather than containing its
binary data, greatly improving efficiency.
The Blob interface provides methods for materializing the BLOB data on the client
when that isdesired.
2. CLOB
The JDBC type CLOB represents the SQL3 type CLOB (Character Large Object).
A JDBC CLOB value is mapped to an instance of the Clob interface in the Java
programming language.
A Clob object logically points to the CLOB value on the server rather than containing its
character data, greatly improving efficiency.
Two of the methods on the Clob interface materialize the data of a CLOB object on the client.
3. ARRAY
4. DISTINCT
5. STRUCT
6. REF
7. JAVA_OBJECT
The JDBC type JAVA_OBJECT, makes it easier to use objects in the Java programming
language asvalues in a database.
JAVA_OBJECT is simply a type code for an instance of a class defined in the Java
programming language that is stored as a database object.
The JAVA_OBJECT value may be stored as a serialized Java object, or it may be stored in
some vendor-specific format.
The type JAVA_OBJECT is one of the possible values for the column DATA_TYPE in
the ResultSet objects returned by various DatabaseMetaData methods, including
getTypeInfo, getColumns, and getUDTs.
Values of type JAVA_OBJECT are stored in a database table using
the method PreparedStatement.setObject.
They are retrieved with They are retrived with the methods
ResultSet.getObject or CallableStatement.getObject and updated with the
ResultSet.updateObject method.
For example, assuming that instances of the class Engineer are stored in the column
ENGINEERS in the table PERSONNEL, the following code fragment, in which stmt is a
Statement object, prints out the names of all of the engineers.
Example-1:
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(“select * from Employee”);
OR
Example-2:
Example-3:
Statement stmt = con.createStatement();
stmt.executeUpdate(“Insert into employee values(„12345‟,‟sk‟,98453));
stmt.executeUpdate(“update employee set Mobile=89706 where Mobile=12345 );
OR
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:MyDataSource","khutub","");
Statement stmt;
} //end of main
} // end of class
PreparedStatement Object
1.6.
1 The preparedStatement object allows you to execute parameterized queries.
A SQL query can be precompiled and executed by using the PreparedStatement object.
Ex: Select * from publishers where pub_id=?
Here a query is created as usual, but a question mark is used as a placeholder for a value
that is inserted into the query after the query is compiled.
The preparedStatement() method of Connection object is called to return the
PreparedStatement object.
Ex:
PreparedStatement stat;
stat= con.prepareStatement(“select * from publisher where pub_id=?”)
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:MyDataSource","khutub","");
PreparedStatement pstmt;
ResultSet rs1=pstmt.executeQuery();
while(rs1.next()){
System.out.println(rs1.getString(2));
} //CallableStatement
end of try
1.6.
The CallableStatement
2 catch(Exception object is used to call} a stored procedure from within a J2EE
e){System.out.println("exception");
object.
A Stored
} //end of main procedure is a block of code and is identified by a unique name.
The type and style of code depends on the DBMS vendor and can be written in PL/SQL,
} // end of class
Transact-SQL, C, or other programming languages.
IN, OUT and INOUT are the three parameters used by the CallableStatement object to
call a stored procedure.
The IN parameter contains any data that needs to be passed to the stored procedure and
whose value is assigned using the setxxx() method.
The OUT parameter contains the value returned by the stored procedures. The OUT
parameters must be registered using the registerOutParameter() method, later retrieved by
using the getxxx()
The INOUT parameter is a single parameter that is used to pass information to the stored
procedure and retrieve information from the stored procedure.
Connection
con; try{
String query = "{CALL
LastOrderNumber(?))}"; CallableStatement
stat = con.prepareCall(query);
stat.registerOutParameter( 1
,Types.VARCHAR); stat.execute();
String lastOrderNumber =
stat.getString(1); stat.close();
}
catch (Exception e){}
9.a. With a neat diagram explain the life cycle of stateful session bean.
Below Figure illustrates the stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create method.The EJB container instantiates the bean and then
invokes the setSessionContext and ejbCreate methods in the session bean. The bean is now ready to have
its business methods invoked.
While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it
from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to
select a bean for passivation.) The EJB container invokes the bean's ejbPassivate method immediately
before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the
EJB container activates the bean, moving it back to the ready stage, and then calls the
bean's ejbActivate method.
At the end of the life cycle, the client invokes the remove method and the EJB container calls the
bean's ejbRemove method. The bean's instance is ready for garbage collection.
Your code controls the invocation of only two life cycle methods-the create and remove methods in the
client. All other methods in Figure are invoked by the EJB container. The ejbCreate method, for example,
is inside the bean class, allowing you to perform certain operations right after the bean is instantiated. For
instance, you may wish to connect to a database in the ejbCreate method.
Figure Life Cycle of a Stateful Session Bean
Stateful session beans (SFSBs) Stateful session beans differ from SLSBs in that every request
upon a given proxy reference is guaranteed to ultimately invoke upon the same bean instance.
SFSB invocations share conversational state. Each SFSB proxy object has an isolated session
context, so calls to one session will not affect another. Stateful sessions, and their corresponding
bean instances, are created sometime before the first invocation upon a proxy is made to its target
instance (Figure 2-3). They live until the client invokes a method that the bean provider has
marked as a remove event, or until the Container decides to remove the session.
Singleton beans Sometimes we don’t need any more than one backing instance for our business
objects. All requests upon a singleton are destined for the same bean instance, The Container
doesn’t have much work to do in choosing the target (Figure 2-4). The singleton session bean may
be marked to eagerly load when an application is deployed; therefore, it may be leveraged to fire
application lifecycle events. This draws a relationship where deploying a singleton
bean implicitly leads to the invocation of its lifecycle callbacks. We’ll put this to good
use when we discuss singleton beans.
9.c. List out the differences between stateless and stateful session bean.
Stateless:
1) Stateless session bean maintains across method and transaction
2) The EJB server transparently reuses instances of the Bean to service
different clients at the per-method level (access to the session bean is
serialized and is 1 client per session bean per method.
3) Used mainly to provide a pool of beans to handle frequent but brief
requests. The EJB server transparently reuses instances of the bean to
service different clients.
4) Do not retain client information from one method invocation to the next.
So many require the client to maintain client side which can mean more
complex client code.
5) Client passes needed information as parameters to the business methods.
6) Performance can be improved due to fewer connections across the network.
Stateful:
1) A stateful session bean holds the client session’s state.
2) A stateful session bean is an extension of the client that creates it.
If the service was restricted to a singular instance, all subsequent requests would
have to queueup until their turn was reached
EJB
Transactions
2.
Transactions provide a means for the developer to easily delegate the creation
and control oftransactions to the container.
When a bean calls createTimer(), the operation is performed in the scope of the
current transaction. If the transaction rolls back, the timer is undone and it’s not
created
The timeout callback method on beans should have a transaction attribute of
RequiresNew. This ensures that the work performed by the callback method is in
the scope of container- initiated transactions.
3.Security
Most enterprise applications are designed to serve a large number of clients,
and users arenot necessarily equal in terms of their access rights.
Figure 15-1. EJB security permitting access based upon the caller’s role
This allows the application developer to explicitly allow or deny access at a fine- grained
level based upon the caller’s identity
10.b. With a neat diagram explain the life cycle of Entity Bean.
The life cycle of an entity bean is controlled by the EJB container, not by your application.
However, you may find it helpful to learn about the life cycle when deciding in which method
your entity bean will connect to a database.
Fig shows the stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext method of the entity bean class.
The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the pooled
stage, the instance is not associated with any particular EJB object identity. All instances in the
pool are identical. The EJB container assigns an identity to an instance when moving it to the
ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the client invokes
the create method, causing the EJB container to call the ejbCreate and ejbPostCreate methods.
On the second path, the EJB container invokes the ejbActivate method. While in the ready stage,
an entity bean's business methods may be invoked.
There are also two paths from the ready stage to the pooled stage. First, a client may invoke
the remove method, which causes the EJB container to call the ejbRemove method. Second, the
EJB container may invoke the ejbPassivate method.
At the end of the life cycle, the EJB container removes the instance from the pool and invokes
the unsetEntityContext method.
In the pooled state, an instance is not associated with any particular EJB object identity. With
bean-managed persistence, when the EJB container moves an instance from the pooled state to
the ready state, it does not automatically set the primary key. Therefore,
the ejbCreate and ejbActivate methods must set the primary key. If the primary key is incorrect,
the ejbLoad and ejbStore methods cannot synchronize the instance variables with the database.
In the pooled state, the values of the instance variables are not needed. You can make these
instance variables eligible for garbage collection by setting them to null in
the ejbPasssivate method.