You are on page 1of 45

JDBC

1. What are statement objects ? Briefly explain the three types of statement
objects.

The JDBC statement objects define the methods and properties that enable you
to send SQL commands and receive data from your database.

The three types of Statement objects are:

Statement: The Statement object is used to execute query immediately


without first having the query compiled. It has three execute methods:
executeQuery(), execute(), executeUpdate().
PreparedStatement: A SQL query can be precompiled and executed by
using PreparedStatement object. After the query is compiled a question
mark is inserted as a placeholder for a value which changes each time the
query is executed.It has these methods: preparedStatement(), setxx(),
executeQuery(), execute(), executeUpdate().
CallableStatement: It is used when you want to use database stored
procedures. The CallableStatement interface can also accept runtime input
parameters.

2. State the steps for JDBC process for connecting to a DBMS

The JDBC process is divided into 5 routines:

Loading the JDBC driver: The Class.forName() method is used to load the
JDBC driver.
Ex:To load JDBC/ODBC Bridge driver called sun.jdbc.odbc.JdbcOdbcDriver,
following code segment is used:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connect to the DBMS: The DriverManager.getConnection() method is used
establish connection with the DBMS. It is passed the URL of the database
and the user id and password if required. The URL string object has the
driver name and the name of the database being accessed.
Ex:
Connection con=DriverManager.getConnection( "jdbc:odbc:CustomerInfor
mation","system","password");
Create and Execute SQL statement: The next step is to send SQL query to
DBMS for processing. The Connect.createStatement() method is used to
create Statement object. The Statement Object is used to execute a query
and return the ResultSet object which contains the response from the
DBMS. The executeQuery() method is used to execute the query.
Ex:
Statement DataRequest;
ResultSet Results;
try{........
.......DataRequest=Db.createStatement();
Results=DataRequest.executeQuery(query);}
Process Data returned by the DBMS: The java.sql.ResultSet object is
assigned the results received from the DBMS after the query has been
processed.
Terminate the connection: The connection to the DBMS is terminated using
the close() method.
Ex: Db.close();

3. UPDATE the student with Rol1No=205 from 'Student' database.

Ans.

import java.sql.*;

public class JDBCExample {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/Student";


static final String USER = "username";

static final String PASS = "password";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to a selected database...");

conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Connected database successfully...");

System.out.println("Creating statement...");

stmt = conn.createStatement();

String sql = "UPDATE student SET age = 30 WHERE rno=205";

stmt.executeUpdate(sql);

sql = "SELECT rno, first, last, age FROM student";

ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){

int id = rs.getInt("rno");

int age = rs.getInt("age");

String first = rs.getString("first");

String last = rs.getString("last");

//Display values

System.out.print("Rno: " + id);

System.out.print(", Age: " + age);

System.out.print(", First: " + first);

System.out.println(", Last: " + last);

rs.close();

}catch(SQLException se){

se.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}finally{

try{

if(stmt!=null)

conn.close();

}catch(SQLException se){
}

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

4. Describe the various components of JDBC.

Ans.

JDBC has following components :

1. The JDBC API

The JDBC API gives access of programming data from the Java. To use this,
applications can execute SQL statements and retrieve results and updation to the
database. The JDBC API is part of the Java platform, it includes the Java Standard
Edition.

2. JDBC Driver Manager

The JDBC DriverManager is the class in JDBC API. The objects of this class can
connect Java applications to a JDBC driver. DriverManager is the very important
part of the JDBC architecture.
3. JDBC Test Suite

The JDBC driver test suite helps JDBC drivers to run your program. They are not
exhaustive,they do exercise with important features in the JDBC API.

4. JDBC-ODBC Bridge

The Java Software bridge provides JDBC access via ODBC drivers.You have to load
ODBC binary code for client machines for using this driver. This driver is very
important for application server code has to be in Java in a three-tier architecture.

5. What are the steps involved in establishment of a JDBC connection?

Ans.
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.

6.Explain JDBC and its uses in Database programming with the help of Java code
segment.

Ans.
Java Database Connectivity (JDBC) is an application program interface (API)
specification for connecting programs written in Java to the data in
popular databases. Java data objects have methods that open a connection to a
Database Management System(DBMS) and then transmit messages(queries) to
insert, retrieve, modify, or delete data stored in a database.

Java programmers could use high level java data objects defined in the JDBC API
to write routine into low level messages that conform to the JDBC driver
specification and send them to the JDBC driver.

Java code is also extended to implementation of the SQL queries. SQL queries are
passed from the JDBC API through the JDBC driver to the dbms without validation.

import java.sql.*;

public class demo

public static void main(String args[]) throws Exception

String url="jdbc:mysql://localhost:3306/xm";

String uname="root";

String pass=" ";

String query="select Name from student where Rno=101";

try

Class.forName("com.mysql.jdbc.Driver");

catch(ClassNotFoundException error)
{

System.err.println("Unable to load the driver"+error.getMessage());

System.exit(1);

Connection cn=DriverManager.getConnection(url,uname,pass);

Statement st=cn.createStatement();

ResultSetrs=st.executeQuery(query);

rs.next();

String name=rs.getString("Name");

System.out.println(name);

pst.close();

cn.close();

Ans:

The first statement in the second try {} block creates a query that calls the stored
procedure LastOrderNumber, which retrieves the most recently used order
number. The stored procedure requires one parameter that is represented by a
question mark placeholder. This parameter is an OUT parameter that will contain
the last order number following the execution of the stored procedure. Next, the
preparedCall() method of the Connection object is called and is passed the query.
This method returns a CallableStatement object, which is called cstatement. Since
an OUT parameter is used by the stored procedure, the parameter must be
registered using the registerOutParameter() of the CallableStatement object. The
registerOutParameter() method requires two parameters. The first parameter is
an integer that represents the number of the parameter, which is 1, meaning the
first parameter of the stored procedure. The second parameter to the
registerOutParameter() is the data type of the value returned by the stored
procedure, which is Types.VARCHAR. The execute() method of the
CallableStatement object is called next to execute the query. The execute()
method doesnt require the name of the query because the query is already
identified when the CallableStatement object is returned by the prepareCall()
query method. After the stored procedure is executed, the getString() method is
called to return the value of the specified parameter of the stored procedure,
which in this code is the last order number.

JavaScript
1. Write the code to set a HTML document's background color in
JavaScript.
<html>
<body>
<script type="text/javascript">
document.body.bgColor="blue";
</script>
</body>
</html>

2. What is the output of the following JavaScript code ? (1)


<script type="text/javascript">
function x()
{
document. write (8+9+8);
}
</script>
Output:178

3. Write a JavaScript code block, which validates a username and password


against hard coded values.
(a)If the name or password field is not entered, display an error
message showing "You forgot one of the required fields. Please Try
Again".
(b)In case the fields entered do not match the hard coded values, display
an error message showing "Please enter valid username and password".
(c ) If the values entered match, display the message : "Welcome
(username)".

<html>

<body>

<form name="login">

Username<input type="text" name="userid"/>

Password<input type="password" name="pswrd"/>

<input type="button" onclick="validate(this.form)" value="Login"/>

<input type="reset" value="Cancel"/>

</form>

<script language="javascript">

function validate(form)

if(form.userid.value == " " && form.pswrd.value == "")

alert("You forgot one of the required fields. Please try again.");


}

if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")

alert("Welcome" + form.userid.value)

else

alert("Error Password or Username")/*displays error message*/

</script>

</body>

</html>

4. Write a JavaScript code that repeatedly zooms-in and zooms-out an image


on the screen.

<html>
<head>
<script type="text/javascript">
function zoomin(){
var myImg = document.getElementById("img");
var currWidth = myImg.clientWidth;
if(currWidth == 500){
alert("Maximum zoom-in level reached.");
} else{
myImg.style.width = (currWidth + 50) + "px";
}
}
function zoomout(){
var myImg = document.getElementById("sky");
var currWidth = myImg.clientWidth;
if(currWidth == 50){
alert("Maximum zoom-out level reached.");
} else{
myImg.style.width = (currWidth - 50) + "px";
}
}
</script>
</head>
<body>
<p>
<button type="button" onclick="zoomin()">Zoom In</button>
<button type="button" onclick="zoomout()">Zoom Out</button>
</p>
<img src="img.jpg" id="img" width="250" alt=">
</body>
</html>

5. What is the difference in the operators "= =" and "= = =" ? Explain with the
help of an example.

Ans.

By using == you check if something is equal to something else. This is not strict

By using === you check if something is equal to something else. This is strict.

What strict does, is that it checks not only the equality of the two values, it
compares the types of the two values too.
Example:

float x = 2 //x equals 2

x == 1 //is x equal to 1? (False)

x == 2 //is x equal to 2? (True)

x === 1 //is x equal to 1? (False)

x === 2 //is x equal to 2? (False)

6. What is the join() method in JavaScript ? Explain the use of join() method with
the help of an example.

Ans.

The join() adds all the elements of an array separated by the specified separator
string.

Syntax: arrayObj.join([separator])

Example:

var a, b;

a = new Array(0,1,2,3,4);

b = a.join("-");

document.write(b);

Output:

0-1-2-3-4
7. Write a Java Script code which will greet user according to Current time.

Ans.

<html>

<body>

<script type=text/javascript>

var d=new Date();

var time=d.getHours();

if(time<12)

document.write(<b>GOOD MORNING!</b>);

If(time>12)

document.write(<b>GOOD AFTERNOON!</b>);

If(time==12)

document.write(<b>LUNCH TIME!<b>);

</script>

</body>

</html>
8.Write a java script to validate an email address.

Ans.

<script type=text/javascript>

function validateEmail()

var email=document.getElementById(txtEmail);

varreg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w)*$/

if(!reg.test(email.value))

alert(Please provide a valid email address);

email.focus;

return false;

</script>

9.Write a java script to validate phone number.

Ans.

<script type=text/javascript>
function validate(inputtxt)

varpno=/^\d{10}$/;

if(inputtxt.value.match(pno))

return true;

else

alert(Please provide a valid mobile number);

return false;

Q10. Explain alert method of window object in java script with suitable example

Ans:

The alert() method displays an alert box with a specified message and an OK
button.

An alert box is often used if you want to make sure information comes through to
the user.

Example:

<!DOCTYPE html>

<html>
<body>

<button onclick="myFunction()">Alert</button>

<script>

function myFunction() {

alert("You just got an alert.");

</script>

</body>

</html>

Q11. How does the use of data types in the context of variables differ in Java
Script and Java?

Ans:In Java there is different datatypes like int, float, string, etc and you have to
specify datatype with variable while declaring.

While, in JavaScript there is var keyword is used to define variable and according
to value it takes datatype of that variable automatically.

Q12. Describe the input tag and write the form elements used in Java Script.

Ans.

The <input> tag specifies an input field where the user can enter data. <input>
elements are used within a <form> element to declare input controls that allow
users to input data.

Form elements used in Java Script are:


1. Radio
2. Check box
3. Submit
4. Reset
5. Button
6. Date
7. Password
8. Text box

Java

1. Rewrite the following loop without using for each construct. (2)
for (x : data) sum = sum + x;

for(int i=0;i<data.length;i++)
sum=sum+data[i];
2.Write a loop that reads 10 strings and insert them into an arraylist. Write a
second loop that prints out the strings in the opposite order from which they
were entered.

ArrayList <String> read = new ArrayList <String>();


for (int i = 0; i < 10; i++) {
String currentString;
//Read in a String and assign it to currentString
read.add(currentString);
}
//For reverse
for(int i=9;i>=0;i--)
{
System.out.println(read.get(i));
}
3 .Write the difference b/w Accessor and Mutator methods. Name two accessor
and mutator methods of the rectangle class.

Ans.

Accessor methods only let you look at data--they don't change it. Think of them as
read-only.Accessor methods are methods that do NOT change any variable of the
object

Mutator methods are methods that change the value in one or more variables of
the object. Mutator methods let you change data.To put this a different way,
they're read-write capable.

Example:

Accessor Methods:

return the width value of the Rectangle


int getWidth()
object

return the height value of the Rectangle


int getHeight()
object

Mutator Methods:

Sets the size of this Rectangle to the specified


void setSize(int width, int height)
width and height.

void translate(int x, int y) Translates this Rectangle the indicated distance,


to the right along the x coordinate axis, and
downward along the y coordinate axis.

4. Why is Java known as Platform independent language.

Ans.

Java is both compiler & interpreter based language. Once the java code also
known as source code is compiled, it gets converted to native code known as
BYTE CODE which is portable & can be easily executed on all operating systems
having java installed in them.

5.Explain data type conversion and casting feature of java with example.

Ans.

Data Type Conversion:Changing a value from one data type to another type is
known as data type conversion.If the data types are compatible, then Java will
perform the conversion automatically known as Automatic Type Conversion.

Ex: int num1=4;

double num2;

double d=num1/num2; //num1 is also converted to double

Type Casting: In some cases changes do not occur on its own, the programmer
needs to specify the type explicitly.This is called casting.However,conversion and
casting can be performed, only if they are compatible with the some rules
defined.

Syntax for Casting: Identifier2=(type) Indentifier1;

Ex: num1=(int)num2;
6.Write about NEW operator in Java.

Ans.

The 'new' operator in java is responsible for the creation of new object or we can
say instance of a class.
Actually, it dynamically allocates memory in the heap with the reference we
define pointed from the stack.

Syntax: var-name=new class-name();

Ex: //instantiation via new operator and

//initialization via default constructor of class Box

mybox= new Box();

JSP

1. What is the purpose of JSP? Explain the three types of JSP elements.
JavaServer Pages (JSP) is a technology for developing Webpages that
supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags.
The three types of java scripting elements are:
JSP Expressions: It is a small java code which you can include into a JSP
page. The syntax is <%= some java code %>
JSP Scriptlet: The syntax for a scriptlet is <% some java code %>. You can
add lines of Java code in here.
JSP Declaration: The syntax for declaration is <%! Variable or method
declaration %>, in here you can declare a variable or a method for use
later in the code.

2.Illustrate HTTP Request/ Response model with the help of diagram.

The HTTP Request/Response Model is based on a simple communication model.


It's a stateless request-response based communication protocol. It's used to send
and receive data on the Web i.e., over the Internet. A client, typically a web
browser, sends a request for a resource to the server, and the server sends back a
response corresponding to the resource.

3.What is the purpose of Custom Tag Library? Give an example


A custom tag is a user-defined JSP language element. When a JSP page
containing a custom tag is translated into a servlet, the tag is converted to
operations on an object called a tag handler. The Web container then invokes
those operations when the JSP page's servlet is executed.
JSP tag extensions lets you create new tags that you can insert directly into a
JavaServer Page.
Ex:

To create a custom JSP tag, you must first create a Java class that acts as a tag
handler. Let us now create the HelloTag class as follows :

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;

public class HelloTag extends SimpleTagSupport {

public void doTag() throws JspException, IOException {

JspWriter out = getJspContext().getOut();

out.println("Hello Custom Tag!");


}

Let us now use the above defined custom tag Hello in our JSP program as follows

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>

<head>

<title>A sample custom tag</title>

</head>

<body>

<ex:Hello/>

</body>

</html>

4.How can the standard action element of JSP be used to set the property of a
Java Bean? Explain with the help of suitable example.

The jsp:useBean is used to get the bean object. It is used to get the java bean
object from given scope or to create a new object of java bean.

We can use jsp:setProperty to set the property values of a java bean like below.

<jsp:setProperty name="myBeanAttribute" property="count" value="5" />

If we want to set the property only if jsp:useBean is creating a new instance, then we
can use jsp:setProperty inside the jsp:useBean to achieve this, something like below
code snippet.
<jsp:useBean id="myBeanAttribute" class="com.journaldev.MyBean" scope="request">

<jsp:setProperty name="myBeanAttribute" property="count" value="5" />

</jsp:useBean>

5.Describe various components in the following statement.

<jsp:usebean id=msg

class=com.ora.jsp.beans.motd.MixedMessageBean/>.

Ans.

The jsp:useBean action tag is used to locate or instantiate a bean class.

id: is used to identify the bean in the specified scope.Here id is msg.

class: instantiates the specified bean class (i.e. creates an object of the bean class)
but it must have no-arg or no constructor and must not be abstract.Here package
is com.ora.jsp.beans.motd and class name is MixedMessageBean.

6.What are Java Server Pages (JSP) ? What are the advantages of using JSP ?

Ans.

Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based
applications. JSP have access to the entire family of Java APIs, including the JDBC
API to access enterprise databases.
Advantages:

1.JSP supports both scripting- and element-based dynamic content, and allows
developers to create custom tag libraries to satisfy application-specific needs.

2.JSP pages are compiled for efficient server processing.

3.JSP pages can be used in combination with servlets that handle the business
logic, the model favored by Java servlet template engines.

4.JSP is a specification, not a product. This means vendors can compete with
different implementations, leading to better performance and quality.

5.JSP is an integral part of J2EE, a complete platform for enterprise class


applications. This means that JSP can play a part in the simplest applications to
the most complex and demanding.

7.What is the difference between GET and POST request methods in HTTP
request ?

Ans.

GET POST

1) In case of Get request, only limited In case of post request, large amount
amount of data can be sent because data is of data can be sent because data is
sent in header. sent in body.

2) Get request is not secured because data is Post request is secured because data
exposed in URL bar. is not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means


second request will be ignored until Post request is non-idempotent.
response of first request is delivered
5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.

8.Give two ways to read and insert Bean properties in a JSP page.

Ans.

The setProperty and getProperty action tags are used for developing web
application with Java Bean.The jsp:setProperty action tag sets a property value or
values in a bean using the setter method.

Example.<jsp:setProperty name="bean" property="username" value="Kumar" />

The jsp:getProperty action tag returns the value of the property.

Example.<jsp:getProperty name="obj" property="name"/>

9.What are the Directive? And explain different types of directives available in
JSP?

Ans.

The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive: <%@ directive attribute="value" %>


JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive: <%@ page attribute="value" %>

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so
it will be better to include static resource).
Advantage of Include directive

Code Reusability

Syntax of include directive: <%@ include file="resourceName" %>

JSP Taglib directive

he JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag
section we will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive:


<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

10.Why do I need JSP technology if I already have servlets?

Ans.
JSP pages are compiled into servlets, so theoretically you could write servlets to
support your web-based applications. However, JSP technology was designed to
simplify the process of creating pages by separating web presentation from web
content. In many applications, the response sent to the client is a combination of
template data and dynamically-generated data. In this situation, it is much easier
to work with JSP pages than to do everything with servlets.
11.What are the different types of JSTL tag? Explain each the suitable example.

Ans.

JSTL stands for JSP Standard Tag Library. JSTL is the standard tag library that
provides tags to control the JSP page behaviour. JSTL tags can be used for
iteration and control statements, internationalisation, SQL etc.

JSTL Tags

There JSTL mainly provides 5 types of tags:

JSTL Core Tags

The JSTL core tag provides variable support, URL management, flow control etc.
The syntax used for including JSTL core library in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

JSTL Function Tags

The JSTL function provides a number of standard functions, most of these


functions are common string manipulation functions. The syntax used for
including JSTL function library in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>


JSTL Formatting tags

The formatting tags provide support for message formatting, number and date
formatting etc. The JSTL formatting tags are used for internationalized web sites
to display and format text, the time, the date and numbers. The syntax used for
including JSTL formatting library in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>


JSTL XML tags

The JSTL XML tags are used for providing a JSP-centric way of manipulating and
creating XML documents.

The xml tags provide flow control, transformation etc. The JSTL XML tag library
has custom tags used for interacting with XML data. The syntax used for including
JSTL XML tags library in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

JSTL SQL Tags

The JSTL SQL tags provide SQL support. The SQL tag library allows the tag to
interact with RDBMSs (Relational Databases) such as Microsoft SQL Server,
mySQL, or Oracle. The syntax used for including JSTL SQL tags library in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

12.What are the advantages of JSP over Pure Servlets?

Ans.

Advantages of JSP over Servlets

1. Servlets use println statements for printing an HTML document which is


usually very difficult to use. JSP has no such tedius task to maintain.
2. JSP needs no compilation, CLASSPATH setting and packaging.
3. In a JSP page visual content and logic are seperated, which is not possible
in a servlet.
4. There is automatic deployment of a JSP, recompilation is done
automatically when changes are made to JSP pages.
5. Usually with JSP, Java Beans and custom tags web application is
simplified.

Q13. What is jsp:usebean. What are the scope attributes & difference between
these attributes.
Ans: The jsp:useBean action tag is used to locate or instantiate a bean class. If
bean object of the Bean class is already created, it doesn't create the bean
depending on the scope. But if object of bean is not created, it instantiates the
bean.

There are 4 scopes application, session, request and page in the order of thier
significance.

Application represent the ServletContext. The scope is accesiblethrought out the


application.

session represents HTTPSession object. This is valid till the user requests the
application.

Request represent the HTTPServletRequest and valdi to a particular request. A


request may span a single JSP page or multiple depending upon the situations.

Page is the least valid scope. It is valid to the particular JSP page only This is some
thing like private variable

Q14. Explain the life cycle of JSP.

A JSP life cycle is defined as the process from its creation till the destruction. This
is similar to a servlet life cycle with an additional step which is required to
compile a JSP into servlet.
The steps in the life cycle of jsp page are:

1. Translation
2. Compilation
3. Loading
4. Instantiation
5. Initialization
6. RequestProcessing
7. Destruction

Q15. How does a servlet communicate with a JSP page?

Ans:

A Servlet can communicate with JSP by using the


RequestDispatchermechanism.RequestDispatching is the process hand overing
the request to another web component,and this component takes the response
of generating the response.This mechanism or interface having two methods
1)forward()
2)include()
First we need to get the rerference of the component,and then we need to use
the corresponding methods according to our requirement...
Example:
RequestDispatcherrd=request.getRequestDispatcher("/Home.jsp");
rd.forward(request,response);

Q16. How does JSP handle run-time exceptions?

Ans
JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.
To set up an error page, use the <%@ page errorPage = "xxx" %> directive.
The error-handling page includes the directive <%@ page isErrorPage = "true"
%>. This directive causes the JSP compiler to generate the exception instance
variable.
We can make use of JSTL tags to write an error page . This page has almost same
logic, with better structure and more information .
Q17. What are Custom tags. Why do you need Custom tags. How do you create
Custom tag?

Ans:

A custom tag is a user-defined JSP language element. When a JSP page containing
a custom tag is translated into a servlet, the tag is converted to operations on an
object called a tag handler. The Web container then invokes those operations
when the JSP page's servlet is executed.

To write a custom tag, you can simply extend SimpleTagSupport class and
override the doTag() method, where you can place your code to generate content
for the tag.

Q18. What is the difference between include directive &jsp:include ?

Ans:

Difference between include directive and jsp:include are:

1) Include directive includes the file at translation time (the phase of JSP life
cycle where the JSP gets converted into the equivalent servlet) whereas the
include action includes the file at runtime.

2) If the included file is changed but not the JSP which is including it then the
changes will reflect only when we use include action tag. The changes will not
reflect if you are using include directive as the JSP is not changed so it will not be
translated (during this phase only the file gets included when using directive) for
request processing and hence the changes will not reflect.

3) Syntax difference: Include directive: <%@ include file="file_name" %> whereas


include action has like this <jsp:include page="file_name" />

4) When using include action tag we can also pass the parameters to the included
page by using param action tag but in case of include directive its not possible.
Q19. Write a JSP program (.jsp file) to capture the parameter value using a bean,
from the input form submitted by the user as shown below:

Ans: <html>

<head>

<title>Echoing HTML Request Parameters</title>

</head>

<body>

<h3>Choose an author:</h3>

<form method="get">

Name <input type="text" name="name"><br>

Birth date <input type="date" name="birthdate"><br>

Email Id <input type="text" name="email"><br>


Gender

<input type="radio" name="gender"> Male <br>

<input type="radio" name="gender"> Female<br>

Hobbies

<input type="checkbox" name="hobby> Music>br>

<input type="checkbox" name="hobby">Sports<br>

<input type="checkbox" name="hobby">Reading Books<br>

<input type="submit" value=Send Data">

</form>

<jsp:useBean id="userInfo"
class="com.ora.jsp.beans.userinfo.UserInfoBean"><jsp:setProperty
name="userInfo" property="*" />

</jsp:useBean> You entered:<br> Name: <c:out value="${userInfo.name}" /><br>

Birth Date:<c:out value="${userInfo.birthdate}" /><br>

Email Address: <c:out value="${userInfo.email}" /><br>

Gender: <c:out value="${userInfo.gender}" /><br>

Hobbies: <c:forEach items="${userInfo.hobby}" var="current"><c:out


value="${current}" />&nbsp; </c:forEach></body></html>
JavaBeans

1.What are Java Beans? How are these useful and used? Explain with example.

A Java Bean is a software component that has been designed to be reusable in a


variety of different environments.

It is a reusable software component. A bean encapsulates many objects into one


object, so we can access this object from multiple places. Moreover, it provides
the easy maintenance.

Ex:

A Simple Bean Example:

//Employee.java

package mypack;

public class Employee implements java.io.Serializable{

private int id;

private String name;

public Employee(){}
public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

To access the java bean class, we should use getter and setter methods.

package mypack;

public class Test{

public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

System.out.println(e.getName()); }}

2.What is the uses Java Beans in JSP page? Expalin with the example.

In JSP the jsp:useBean action tag is used to locate or instantiate a bean class. If
bean object of the Bean class is already created, it doesn't create the bean
depending on the scope. But if object of bean is not created, it instantiates the
bean.
Syntax of jsp:useBean action tag

<jsp:useBean id= "instanceName" scope= "page | request | session | application"

class= "packageName.className" type= "packageName.className"

beanName="packageName.className | <%= expression >" >

</jsp:useBean>

3.What is the Java Bean and Bean Development Kit (BDK)?

Ans.

JavaBeans are classes that encapsulate many objects into a single object. They are
serializable, have a zero-argument constructor, and allow access to properties
using getter and setter methods.

The Beans Development Kit (BDK) is intended to support the early development
of JavaBeansTM components and to act as a standard reference base for both
bean developers and tool vendors. The BDK provides a reference bean container,
the "BeanBox" and a variety of reusable example source code (in the demo and
beanbox subdirectories) for use by both bean developers and tools developers.
The BDK contains a number of useful things:

JavaBean source files


The BeanBox
JavaBeans demos
JavaBeans documentation
4.What is BeanInfo interface used for? List the three functions defined by this
interface.

Ans.

BeanInfo is an interface implemented by a class that provides explicit


information about a Bean. It is used to describe one or more feature sets of a
Bean, including its properties, methods, and events.

getPropertyDescriptors( ) method: It is used to provide information about


properties of a bean.

Syntax: PropertyDescriptor[ ] getPropertyDescriptors( )

getEventSetDescriptors( ) method: It is used to provide information about events


of a bean.

Syntax: EventSetDescriptor[ ] getEventSetDescriptors( )

getMethodDescriptors( ) method: It is used to provide information about


methods of a bean.

Syntax: MethodDescriptor[ ] getMethodDescriptors( )

5. What is the relevance of Java Beans in software development ?

Ans.
In computing based on the Java Platform, JavaBeans are classes that encapsulate
many objects into a single object (the bean). They are serializable, have a zero-
argument constructor, and allow access to properties using getter and setter
methods. The name "Bean" was given to encompass this standard, which aims to
create reusable software components for Java.
6.What IS introspection ? What are the two ways in which Bean introspection
can be done?

Ans.
Introspection is the automatic process of analyzing a bean's design patterns to
reveal the bean's properties, events, and methods. This process controls the
publishing and discovery of bean operations and properties. It is the examination
provided by a Java Bean class but a class cannot speak. Adeveloper has to write
the description about the bean so that the other developers can understand the
Bean properties,events etc.

In short the process to describe a Bean is known as Bean introspection.


Which is done by two ways:

1. Naming Conventions
2. By writing an additional class that extends the BeanInfo interface

Q13. What is jsp:usebean. What are the scope attributes & difference between
these attributes.

Ans: The jsp:useBean action tag is used to locate or instantiate a bean class. If
bean object of the Bean class is already created, it doesn't create the bean
depending on the scope. But if object of bean is not created, it instantiates the
bean.

There are 4 scopes application, session, request and page in the order of thier
significance.

Application represent the ServletContext. The scope is accesiblethrought out the


application.

session represents HTTPSession object. This is valid till the user requests the
application.

Request represent the HTTPServletRequest and valdi to a particular request. A


request may span a single JSP page or multiple depending upon the situations.
Page is the least valid scope. It is valid to the particular JSP page only This is some
thing like private variable

Q14. Explain the life cycle of JSP.

A JSP life cycle is defined as the process from its creation till the destruction. This
is similar to a servlet life cycle with an additional step which is required to
compile a JSP into servlet.
The steps in the life cycle of jsp page are:

1. Translation
2. Compilation
3. Loading
4. Instantiation
5. Initialization
6. RequestProcessing
7. Destruction

Q15. How does a servlet communicate with a JSP page?

Ans:

A Servlet can communicate with JSP by using the


RequestDispatchermechanism.RequestDispatching is the process hand overing
the request to another web component,and this component takes the response
of generating the response.This mechanism or interface having two methods
1)forward()
2)include()
First we need to get the rerference of the component,and then we need to use
the corresponding methods according to our requirement...
Example:
RequestDispatcherrd=request.getRequestDispatcher("/Home.jsp");
rd.forward(request,response);

Q16. How does JSP handle run-time exceptions?

Ans
JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.
To set up an error page, use the <%@ page errorPage = "xxx" %> directive.
The error-handling page includes the directive <%@ page isErrorPage = "true"
%>. This directive causes the JSP compiler to generate the exception instance
variable.
We can make use of JSTL tags to write an error page . This page has almost same
logic, with better structure and more information .

Q17. What are Custom tags. Why do you need Custom tags. How do you create
Custom tag?

Ans:

A custom tag is a user-defined JSP language element. When a JSP page containing
a custom tag is translated into a servlet, the tag is converted to operations on an
object called a tag handler. The Web container then invokes those operations
when the JSP page's servlet is executed.

To write a custom tag, you can simply extend SimpleTagSupport class and
override the doTag() method, where you can place your code to generate content
for the tag.

Q18. What is the difference between include directive &jsp:include ?


Ans:

Difference between include directive and jsp:include are:

1) Include directive includes the file at translation time (the phase of JSP life
cycle where the JSP gets converted into the equivalent servlet) whereas the
include action includes the file at runtime.

2) If the included file is changed but not the JSP which is including it then the
changes will reflect only when we use include action tag. The changes will not
reflect if you are using include directive as the JSP is not changed so it will not be
translated (during this phase only the file gets included when using directive) for
request processing and hence the changes will not reflect.

3) Syntax difference: Include directive: <%@ include file="file_name" %> whereas


include action has like this <jsp:include page="file_name" />

4) When using include action tag we can also pass the parameters to the included
page by using param action tag but in case of include directive its not possible.

Q19. Write a JSP program (.jsp file) to capture the parameter value using a bean,
from the input form submitted by the user as shown below:
Ans: <html>

<head>

<title>Echoing HTML Request Parameters</title>

</head>

<body>

<h3>Choose an author:</h3>

<form method="get">

Name <input type="text" name="name"><br>

Birth date <input type="date" name="birthdate"><br>

Email Id <input type="text" name="email"><br>

Gender

<input type="radio" name="gender"> Male <br>

<input type="radio" name="gender"> Female<br>

Hobbies
<input type="checkbox" name="hobby> Music>br>

<input type="checkbox" name="hobby">Sports<br>

<input type="checkbox" name="hobby">Reading Books<br>

<input type="submit" value=Send Data">

</form>

<jsp:useBean id="userInfo"
class="com.ora.jsp.beans.userinfo.UserInfoBean"><jsp:setProperty
name="userInfo" property="*" />

</jsp:useBean> You entered:<br> Name: <c:out value="${userInfo.name}" /><br>

Birth Date:<c:out value="${userInfo.birthdate}" /><br>

Email Address: <c:out value="${userInfo.email}" /><br>

Gender: <c:out value="${userInfo.gender}" /><br>

Hobbies: <c:forEach items="${userInfo.hobby}" var="current"><c:out


value="${current}" />&nbsp; </c:forEach></body></html>

Q7. Write an Employee JavaBean class for getting and setting the employee
properties FirstName, LastName and EmpID.

Ans:
Packagecom.EmpBean;

publicclassEmployeeBeanimplementsjava.io.Serializable{
privateStringfirstName=null;
privateStringlastName=null;
privateintEmpID=0;

publicEmployeeBean(){
}
publicStringgetFirstName(){
returnfirstName;
}
publicStringgetLastName(){
returnlastName;
}
publicintgetEmpID(){
returnEmpID;

publicvoidsetFirstName(StringfirstName){
this.firstName=firstName;
}
publicvoidsetLastName(StringlastName){
this.lastName=lastName;
}
publicvoidsetEmpID(IntegerEmpID){
this.EmpID=EmpID;
}
}

You might also like