mc0078 set2 july 2011

28

Transcript of mc0078 set2 july 2011

Page 1: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 1/28

Page 2: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 2/28 

1.  Write a complete program fo

ο  Decision Making Statem

Ans: If-else statement 

The if statement is Java’s co

through two different paths.

if (condition) statement1;

else statement2;

Here, each statement may b

(that is, a block). The condit

optional.

The if works like this: If the c

exists) is executed. In no case

Most often, the expression u

not technically necessary. It i

this code fragment:

boolean dataAvailable;

 // …

Master of Computer Applicat

MC0078 – Java P

(Book ID: B0831 & B0

r each of the following:

nts

ditional branch statement. It can be used to rou

ere is the general form of the if statement:

a single statement or a compound statement en

ion is any expression that returns a boolean val

ndition is true, then statement1 is executed. Othe

will both statements be executed. For example, co

ed to control the if will involve the relational oper

s possible to control the if using a single boolean

July 2011

ion (MCA) – Semester 4

rogramming – 4 Credits

32) Assignment Set – 2

e program execution

losed in curly braces

e. The else clause is

wise, statement2(if it

sider the following:

tors. However, this is

variable, as shown in

Page 3: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 3/28

 if (dataAvailable)

ProcessData();

else

waitForMoreData();

Remember, only one statement can appear directly after the if or the else. If you want to include

more statements, you’ll need to create a block, as in this fragment:

int bytesAvailable;

 // …

if (bytesAvailable > 0) { 

ProcessData();

bytesAvailable -= n;

 } elsewaitForMoreData();

Here, both statements within the if block will execute if bytesAvailable is greater than zero. Some

programmers find it convenient to include the curly braces when using the if, even when there is only

one statement in each clause. This makes it easy to add another statement at a later date, and you

don’t have to worry about forgetting the braces. In fact, forgetting to define a block when one is

needed is a common cause of errors. For example, consider the following code fragment:

int bytesAvailable;

 // …

if (bytesAvailable > 0) { 

ProcessData();

bytesAvailable -= n;

 } else

waitForMoreData();

bytesAvailable = n;

It seems clear that the statement bytesAvailable = n; was intended to be executed inside the else

clause, because of the indentation level. However, as you recall, whitespace is insignificant to Java,and there is no way for the compiler to know what was intended. This code will compile without

complaint, but it will behave incorrectly when run.

The preceding example is fixed in the code that follows:

int bytesAvailable;

 // …

if (bytesAvailable > 0) { 

Page 4: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 4/28

 ProcessData();

bytesAvailable -= n;

 } else { 

waitForMoreData();

bytesAvailable = n;

 }

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the ifelse-

if ladder. It looks like this:

if(condition)

statement;

else if(condition)

statement;

else if(condition)

statement;

.

.

.

elsestatement;

The if statements are executed from the top down. As soon as one of the conditions controlling the if 

is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If 

none of the conditions is true, then the final else statement will be executed. The final else acts as a

default condition; that is, if all other conditional tests fail, then the last else statement is performed. If 

there is no final else and all other conditions are false, then no action will take place.

Here is a program that uses an if-else-if ladder to determine which season a particular month is in.

 // Demonstrate if-else-if statements.

class IfElse { 

 public static void main(String args[ ]) { 

int month = 4; // April 

String season;

if(month == 12 || month == 1 || month == 2)

season = "Winter";

Page 5: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 5/28 

else if(month == 3 || month == 4 || month == 5)

season = "Spring";

else if(month == 6 || month == 7 || month ==

season = "Summer";

else if(month == 9 || month == 10 || month == 11)

season = "Autumn";

else

season = "Bogus Month";

System.out.println("April is in the " + season + ".");

 }

 }

Here is the output produced by the program:

April is in the Spring.

You might want to experiment with this program before moving on. As you will find, no matter what

value you give month, one and only one assignment statement within the ladder will be executed.

Switch Statement

The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch

execution to different parts of your code based on the value of an expression.

As such, it often provides a better alternative than a large series of if-else-if statements.

Here is the general form of a switch statement:

switch (expression) { 

case value1:

 // statement sequence

break;

case value2:

 // statement sequence

break;

.

.

.

case valueN:

Page 6: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 6/28 

 // statement sequence

break;

default:

 // default statement sequenc

 }

The expression must be of t

statements must be of a ty

literal (that is, it must be a co

The switch statement works l

values in the case statements

executed. If none of the cons

executed. However, the defa

then no further action is take

The break statement is used

statement is encountered, e

statement. This has the effec

Example

The break statement is optio

It is sometimes desirable t

example, consider the followi // In a switch, break stateme

class MissingBreak { 

 public static void main(String

 for(int i=0; i<12; i++)

switch(i) { 

case 0:

ype byte, short, int, or char; each of the values

e compatible with the expression. Each case val

stant, not a variable). Duplicate case values are no

ike this: The value of the expression is compared

. If a match is found, the code sequence following

tants matches the value of the expression, then th

ult statement is optional. If no case matches and

.

inside the switch to terminate a statement seq

ecution branches to the first line of code that foll

of "jumping out" of the switch.

al. If you omit the break, execution will continue

have multiple cases without break statements

ng program:ts are optional.

args[ ]) { 

specified in the case

e must be a unique

t allowed.

ith each of the literal

hat case statement is

default statement is

no default is present,

ence. When a break

ws the entire switch

n into the next case.

between them. For

Page 7: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 7/28

 case 1:

case 2:

case 3:

case 4:

System.out.println("i is less than 5");

break;

case 5:

case 6:

case 7:

case 8:

case 9:

System.out.println("i is less than 10");

break;

default:

System.out.println("i is 10 or more");

 }

 }

 }

This program generates the following output:

i is less than 5

i is less than 5

i is less than 5

i is less than 5

i is less than 5

i is less than 10

i is less than 10

i is less than 10

i is less than 10i is less than 10

i is 10 or more

i is 10 or more

Nested switch Statements

Page 8: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 8/28

 You can use a switch as part of the statement sequence of an outer switch. This is called a nested

switch. Since a switch statement defines its own block, no conflicts arise between the case constants

in the inner switch and those in the outer switch. For example, the following fragment is perfectly

valid:

switch(count) { 

case 1:

switch(target) { // nested switch

case 0:

System.out.println("target is zero");

break;

case 1: // no conflicts with outer switch

System.out.println("target is one");

break;

 }

break;

case 2: // …

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the

outer switch. The count variable is only compared with the list of cases at the outer level. If count is 1,

then target is compared with the inner list cases.

In summary, there are three important features of the switch statement to note:

The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type

of Boolean expression. That is, the switch looks only for a match between the value of the expression

and one of its case constants.

  No two case constants in the same switch can have identical values. Of course, a switch statement

enclosed by an outer switch can have case constants in common.

  A switch statement is usually more efficient than a set of nested ifs.

The last point is particularly interesting because it gives insight into how the Java compiler works.

When it compiles a switch statement, the Java compiler will inspect each of the case constants and

create a "jump table" that it will use for selecting the path of execution depending on the value of the

expression. Therefore, if you need to select among a large group of values, a switch statement will run

much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this

because it knows that the case constants are all the same type and simply must be compared for

equality with the switch expression. The compiler has no such knowledge of a long list of if 

expressions.

Page 9: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 9/28 

ο  Looping Statements

Ans: ‘for’ Loop 

The usage of for loop is as foll

for (initial statement; termina

statement;

When multiple statements a

flower braces. for (initial stat

statement1;

statement2;

 }

The example below prints nu

The results of the above prog

ows

tion condition; increment instruction)

re to be included in the for loop, the statement

ment; termination condition; increment instructio

bers from 1 to 10

ram is shown below

s are included inside

)

Page 10: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 10/28

 Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside

another. For example, here is a program that nests for loops:

 // Loops may be nested.

class Nested { 

 public static void main(String args[ ]) { 

int i, j;

 for(i=0; i<10; i++) { 

 for(j=i; j<10; j++)

System.out.print(".");

System.out.println();

 }

 }

 }

The output produced by this program is shown here:

……….

………

……..

…….

……

…..

While Statement

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its

controlling expression is true. Here is its general form:

while (condition) { 

 // body of loop

 }

The condition can be any Boolean expression. The body of the loop will be executed as long as theconditional expression is true. When condition becomes false, control passes to the next line of code

immediately following the loop. The curly braces are unnecessary if only a single statement is being

repeated.

Page 11: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 11/28 

Example

do….while’ statement

As you just saw, if the conditi

the loop will not be executed

loop at least once, even if th

times when you would like to

beginning. Fortunately, Java

always executes its body at le

Its general form is

do { 

 // body of loop

 } while (condition);

Each iteration of the do-wh

conditional expression. If this

As with all of Java’s loops, co

Example

onal expression controlling a while loop is initially f 

at all. However, sometimes it is desirable to execu

conditional expression is false to begin with. In o

test the termination expression at the end of the l

supplies a loop that does just that: the do-whil

ast once, because its conditional expression is at th

ile loop first executes the body of the loop an

expression is true, the loop will repeat. Otherwise

dition must be a boolean expression.

lse, then the body of 

e the body of a while

ther words, there are

op rather than at the

e. The do-while loop

e bottom of the loop.

then evaluates the

the loop terminates.

Page 12: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 12/28 

The do-while loop is especially useful when you process a menu selection, because you will usually

want the body of a menu loop to execute at least once. Consider the following program which

implements a very simple help system for Java’s selection and iterationstatements:

 // Using a do-while to process a menu selection

class Menu { 

 public static void main(String args[])

throws java.io.IOException { 

char choice;

do { 

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.println(" 3. while");

System.out.println(" 4. do-while");

System.out.println(" 5. for\n");

System.out.println("Choose one:");

choice = (char) System.in.read();

 } while( choice < ‘1′ || choice > ‘5′);

System.out.println("\n");

switch(choice) { 

case ‘1′:

System.out.println("The if:\n");

System.out.println("if(condition) statement;");

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

break;

case ‘2′:

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

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

System.out.println(" break;");

System.out.println(" // …");

System.out.println("}");

break;

case ‘3′:

Page 13: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 13/28 

System.out.println("The while:\n");

System.out.println("while(condition) statement;");

break;

case ‘4′:

System.out.println("The do-while:\n");

System.out.println("do {");

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

System.out.println("} while (condition);");

break;

case ‘5′:

System.out.println("The for:\n");

System.out.print("for(init; condition; iteration)");

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

break;

 }

 }

 }

Here is a sample run produced by this program:

Help on:

1. if 

2. switch

3. while

4. do-while

5. for 

Choose one:

The do-while:

do { 

statement;

 } while (condition);

In the program, the do-while loop is used to verify that the user has entered a valid choice. If not,

then the user is reprompted. Since the menu must be displayed at least once, the do-while is the

perfect loop to accomplish this.

Page 14: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 14/28

 A few other points about this example: Notice that characters are read from the keyboard by calling

System.in.read( ). This is one of Java’s console input functions. Although Java’s console I/O methods

won’t be discussed in detail until System.in.read( ) is used here to obtain the user’s choice. It reads

characters from standard input (returned as integers, which is why the return value was cast to char).

By default, standard input is line buffered, so you must press ENTER before any characters that youtype will be sent to your program.

Java’s console input is quite limited and awkward to work with. Further, most real-world Java

programs and applets will be graphical and window-based. For these reasons, not much use of 

console input has been made in this book. However, it is useful in this context. One other point:

Because System.in.read( ) is being used, the program must specify the throws java.io.IOException

clause. This line is necessary to handle input errors.

2.  How do you implements inheritance in java?

Ans: Inheritance is one of the cornerstones of object-oriented programming because it allows the creation

of hierarchical classifications. Using inheritance, you can create a general class that defines traits

common to a set of related items. This class can then be inherited by other, more specific classes,

each adding those things that are unique to it. In the terminology of Java, a class that is inherited is

called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a

specialized version of a superclass. It inherits all of the instance variables and methods defined by the

superclass and add its own, unique elements.

Implementing Inheritance in Java: - The extends keyword is used to derive a class from a superclass,

or in other words, extend the functionality of a superclass.

Syntax

public class <subclass_name>extends<superclass_name>

Example

public class confirmed extends ticket

{

}

Rules for Overriding Methods

  The method name and the order of arguments should be identical to that of the superclass

method.

  The return type of both the methods must be the same.

Page 15: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 15/28

   The overriding method cannot be less accessible than the method it overrides. For example, if the

method to override is declared as public in the superclass, you cannot override it with the private

keyword in the subclass.

  An overriding method cannot raise more exceptions than those raised by the superclass.

Example

 // Create a superclass.

class A { 

int i, j;

void showij() { 

System.out.println("i and j: " + i + " " + j);

 }

 } // Create a subclass by extending class A.

class B extends A { 

int k;

void showk() { 

System.out.println("k: " + k);

 }

void sum() { 

System.out.println("i+j+k: " + (i+j+k));

 }

 }

class SimpleInheritance { 

 public static void main(String args[]) { 

 A superOb = new A();

B subOb = new B();

 // The superclass may be used by itself.

superOb.i = 10;

superOb.j = 20;

System.out.println("Contents of superOb: ");

superOb.showij();

System.out.println();

 /* The subclass has access to all public members of 

its superclass. */ 

Page 16: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 16/28

 subOb.i = 7;

subOb.j = 8;

subOb.k = 9;

System.out.println("Contents of subOb: ");

subOb.showij();

subOb.showk();

System.out.println();

System.out.println("Sum of i, j and k in subOb:");

subOb.sum();

 }

 }

The output from this program is shown here:

Contents of superOb:

i and j: 10 20

Contents of subOb:

i and j: 7 8

k: 9

Sum of i, j and k in subOb:

i+j+k: 24

As you can see, the subclass B includes all of the members of its superclass, A. This is why subOb canaccess i and j and call showij ( ). Also, inside sum ( ), i and j can be referred to directly, as if they were

part of B.

Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a

superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a

subclass can be a superclass for another subclass.

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name { 

 // body of class

 }

You can only specify one superclass for any subclass that you create. Java does not support the

inheritance of multiple superclasses into a single subclass. (This differs from C++, in which you can

inherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclass

becomes a superclass of another subclass.

Page 17: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 17/28

 However, no class can be a superclass of itself.

3.  Draw and explain the JDBC Application Architecture?

Ans: The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a

Relational Database.

JDBC helps you to write java applications that manage these three programming activities:

1.  Connect to a data source, like a database

2.  Send queries and update statements to the database

3.  Retrieve and process the results received from the database in answer to your query

JDBC Architecture: - The JDBC API supports both two-tier and three-tier processing models for

database access.

Two-tier Architecture for Data Access

In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver

that can communicate with the particular data source being accessed. A user’s commands are

delivered to the database or other data source, and the results of those statements are sent back to

the user. The data source may be located on another machine to which the user is connected via a

network. This is referred to as a client/server configuration, with the user’s machine as the client, and

the machine housing the data source as the server. The network can be an intranet, which, for

example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the

commands to the data source. The data source processes the commands and sends the results backto the middle tier, which then sends them to the user. MIS directors find the three-tier model very

attractive because the middle tier makes it possible to maintain control over access and the kinds of 

updates that can be made to corporate data. Another advantage is that it simplifies the deployment

of applications. Finally, in many cases, the three-tier architecture can provide performance

advantages.

DBMS

Client Machine

DBMS Proprietary Protocol

Database Server

Java Application

JBDC

Page 18: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 18/28 

Until recently, the middle tieperformance. However, with

into efficient machine-speci

platform is fast becoming t

making it possible to take adv

With enterprises increasingly

API is being used more and

that make JDBC a server tec

and disconnected rowsets. T

middle tier.

Three-tier Architecture for Data Access

r has often been written in languages such as C orthe introduction of optimizing compilers that tra

ic code and technologies such as Enterprise J

e standard platform for middle-tier developmen

antage of Java’s robustness, multithreading, and se

using the Java programming language for writing

ore in the middle tier of a three-tier architecture.

nology are its support for connection pooling, dis

he JDBC API is also what allows access to a dat

C++, which offer fastnslate Java bytecode

vaBeans™, the Java

t. This is a big plus,

curity features.

erver code, the JDBC

Some of the features

tributed transactions,

source from a Java

Page 19: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 19/28

 

4.  What are the difference between an interface and an abstract class?

Ans: An abstract class is a class that leaves one or more method implementations unspecified by declaring

one or more methods abstract. An abstract method has no body (i.e.,no implementation). A subclass

is required to override the abstract method and provide an implementation. Hence, an abstract classis incomplete and cannot be instantiated, but can be used as a base class.

abstract public class abstract-base-class-name { 

 // abstract class has at least one abstract method 

 public abstract return-type abstract-method-name ( formal-params );

... // other abstract methods, object methods, class methods

 }

 public class derived-class-name extends abstract-base-class-name { 

 public return-type abstract-method-name (formal-params) { stmt-list; }... // other method implementations

 }

It would be an error to try to instantiate an object of an abstract type:

abstract-class-name obj = new abstract-class-name(); // ERROR!

That is, operator new is invalid when applied to an abstract class.

An interface is a specification, or contract, for a set of methods that a class that implements the

interface must conform to in terms of the type signature of the methods. The class that implements

the interface provides an implementation for each method, just as with an abstract method in anabstract class.

So, you can think of an interface as an abstract class with all abstract methods. The interface itself can

have either public, package, private or protected access defined. All methods declared in an interface

are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to

declare a method in an interface to be abstract.

You can define data in an interface, but it is less common to do so. If there are data fields defined in

an interface, then they are implicitly defined to be:

  Public,

  Static, and

  Final

In other words, any data defined in an interface are treated as public constants.

Note that a class and an interface in the same package cannot share the same name.

Page 20: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 20/28

 Methods declared in an interface cannot be declared final. Why? Interface declaration Interface

names and class names in the same package must be distinct.

 public interface interface-name { 

 // if any data are defined, they must be constants

 public static final type-name var-name = constant-expr;

 // one or more implicitly abstract and public methods

return-type method-name ( formal-params );}

When to use an Interface vs when to use an abstract class

Having reviewed their basic properties, there are two primary differences between interfaces and

abstract classes:

  An abstract class can have a mix of abstract and non-abstract methods, so some default

implementations can be defined in the abstract base class. An abstract class can also have staticmethods, static data, private and protected methods, etc. In other words, a class is a class, so it

can contain features inherent to a class. The downside to an abstract base class, is that since their

is only single inheritance in Java, you can only inherit from one class.

  An interface has a very restricted use, namely, to declare a set of public abstract method

signatures that a subclass is required to implement. An interface defines a set of type constraints,

in the form of type signatures that impose a requirement on a subclass to implement the

methods of the interface. Since you can inherit multiple interfaces, they are often a very useful

mechanism to allow a class to have different behaviors in different situations of usage by

implementing multiple interfaces.

It is usually a good idea to implement an interface when you need to define methods that are to be

explicitly overridden by some subclass. If you then want some of the methods implemented with

default implementations that will be inherited by a subclass, then create an implementation class for

the interface, and have other class inherit (extend) that class, or just use an abstract base class instead

of an interface

Page 21: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 21/28

 5.  Explain the working of struts with an example.

Ans: Struts is modeled after the MVC design pattern, you can follow a standard development process for

all of your Struts Web applications.

Identificaty of the application Views, the Controller objects that will service those Views, and the

Model components being operated on.

1.  Define and create all of the Views, in relation to their purpose, that will represent the user

interface of our application. Add all Action Forms used by the created Views to the struts-

config.xml file.

2.  Create the components of the application’s Controller.

3.  Define the relationships that exist between the Views and the Controllers (struts-config.xml).

4.  Make the appropriate modifications to the web.xml file, describe the Struts components to the

Web application.

Let’s Start with step one. We will create the view file named index.jsp

index.jsp

<%@ page language="java" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>

<head>

<title>Sample Struts Application</title>

</head>

<body>

<html:form action="Name" name="nameForm" type="example.NameForm">

<table width="80%" border="0">

<tr>

<td>Name:</td> <td>

<html:text property="name" /></td>

</tr>

<tr>

<td><html:submit /></td>

</tr>

</table>

</html:form>

</body>

</html>

Page 22: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 22/28

 Action: Represents the URL to which this form will be submitted. This attribute is also used to find the

appropriate Action Mapping in the Struts configuration file, which we will describe later in this

section. The value used in our example is Name, which will map to an Action Mapping with a path

attribute equal to Name

Name: Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An

ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It main

purpose is to pass form data between View and Controller components. We will discuss NameForm

later in this section.

Type: Names the fully qualified class name of the form bean to use in this request. For this example,

we use the value example. NameForm, which is an ActionForm object containing data members

matching the inputs of this form.

NameForm.java

 package example;

 //import statements

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

 public class NameForm extends ActionForm { 

 private String name = null;

 public String getName() { 

return (name);

 }

 public void setName(String name) { 

this.name = name;

 }

 public void reset(ActionMapping mapping, HttpServletRequest request) { 

this.name = null;

 }

 }

displayname.jsp

<html>

<head>

<title>Sample Struts Display Name</title>

</head>

<body>

Page 23: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 23/28

 <table width="80%" border="0">

<tr>

<td>Hello <%= request.getAttribute("NAME") %> !!</td>

</tr>

</table>

</body>

</html>

NameAction.java

 package example;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

 public class NameAction extends Action { 

 public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { 

String target = new String("success");

if ( form != null ) { 

 // Use the NameForm to get the request parameters

NameForm nameForm = (NameForm)form;

String name = nameForm.getName();

 }// if no mane supplied Set the target to failure

if ( name == null ) { 

target = new String("failure");

 }

else { 

request.setAttribute("NAME", name);

 }

return (mapping.findForward(target));

Page 24: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 24/28 

 }

 }

Moving to step three, to deploy the NameAction to our Struts application, weneed to compile the

NameAction class and move the class file to /WEB-INF/classes/example directory, and add thefollowing entry to the <action-mappings> section of the /WEB-INF/struts-config.xml file:

<action path="/Name" type="example.NameAction" name="nameForm"input="/index.jsp">

<forward name="success" path="/displayname.jsp"/>

<forward name="failure" path="/index.jsp"/>

</action>

For step four we modify the web.xml file. We have to to tell the Web applicationabout our

ActionServlet. This is accomplished by adding the following servlet definition to the /WEB-

INF/web.xml file:

<servlet>

<servlet-name>action</servlet-name>

<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

Once we have told the container about the ActionServlet, we need to tell it whenthe action should be

executed. To do this, we have to add a <servlet-mapping>element to the /WEB-INF/ web.xml file:

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

6. 

Write a program in Java to demonstrate the complete life cycle of a Servlet.

Ans: CODE:

import database.BookDB;

import javax.servlet.*;

import util.Counter;

 public final class ContextListener 

implements ServletContextListener { 

Page 25: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 25/28

  private ServletContext context = null;

 public void contextInitialized(ServletContextEvent event) { 

context = event.getServletContext();

try { 

BookDB bookDB = new BookDB();

context.setAttribute("bookDB", bookDB);

 } catch (Exception ex) { 

System.out.println( 

"Couldn't create database: " + ex.getMessage());

 }

Counter counter = new Counter();

context.setAttribute("hitCounter", counter);

context.log("Created hitCounter" +

counter.getCounter());

counter = new Counter();

context.setAttribute("orderCounter", counter);

context.log("Created orderCounter" +

counter.getCounter());

 }

 public void contextDestroyed(ServletContextEvent event) { 

context = event.getServletContext();

BookDB bookDB = context.getAttribute( 

"bookDB");

bookDB.remove();

context.removeAttribute("bookDB");

context.removeAttribute("hitCounter");

context.removeAttribute("orderCounter");

 }

 }

7.  Explain the life cycle of a Servlet?

Ans: Servlet Life Cycle: 

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When

a request is mapped to a servlet, the container performs the following steps.

1.  If an instance of the servlet does not exist, the Web container

Page 26: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 26/28

 2.  Loads the servlet class.

3.  Creates an instance of the servlet class.

4.  Initializes the servlet instance by calling the init method.

5.  Invokes the service method, passing a request and response object.

If the container needs to remove the servlet, it finalizes the servlet by calling theservlet's destroy

method.

Handling Servlet Life-Cycle Events

You can monitor and react to events in a servlet's life cycle by defining listener objects whose

methods get invoked when life cycle events occur. To use these listener objects, you must define the

listener class and specify the listener class.

The listeners.ContextListener class creates and removes the database helper and counter objects used

in the Duke's Bookstore application. The methods retrieve the Web context object from

ServletContextEvent and then store (and remove) the objects as servlet context attributes.

CODE:

import database.BookDB;

import javax.servlet.*;

import util.Counter;

 public final class ContextListener 

implements ServletContextListener { 

 private ServletContext context = null;

 public void contextInitialized(ServletContextEvent event) { 

context = event.getServletContext();

try { 

BookDB bookDB = new BookDB();

context.setAttribute("bookDB", bookDB);

 } catch (Exception ex) { 

System.out.println( 

"Couldn't create database: " + ex.getMessage());

 }

Counter counter = new Counter();

context.setAttribute("hitCounter", counter);

context.log("Created hitCounter" +

counter.getCounter());

Page 27: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 27/28

 counter = new Counter();

context.setAttribute("orderCounter", counter);

context.log("Created orderCounter" +

counter.getCounter());

 }

 public void contextDestroyed(ServletContextEvent event) { 

context = event.getServletContext();

BookDB bookDB = context.getAttribute( 

"bookDB");

bookDB.remove();

context.removeAttribute("bookDB");

context.removeAttribute("hitCounter");

context.removeAttribute("orderCounter");

 }

 }

8.  Explain the importance, applications and working of Java Struts.

Ans: Struts is an application development framework that is designed for and used with the popular J2EE

(Java 2, Enterprise Edition) platform. It cuts time out of the development process and makes

developers more productive by providing them a series of tools and components to build applications

with. Struts fall sunder the Jakarta subproject of the Apache Software Foundation and comes with an

Open Source license.

An example of a Struts Flow server-side script which logs the user on to an application:

 function login()

{userManager = struts.applicationScope["userManager"];

error = "";

while (struts.sessionScope["curUser"] == null) { 

 forwardAndWait("loginForm", {"error" : error});

user = struts.param["user"];

 passwd = struts.param["passwd"];

if (userManager.login(user, passwd)) { 

struts.sessionScope["curUser"] = user;

 } else { 

error = "Invalid login, please try again";

 }

 }

Page 28: mc0078 set2 july 2011

8/3/2019 mc0078 set2 july 2011

http://slidepdf.com/reader/full/mc0078-set2-july-2011 28/28

 }

Features of Struts are as follows:

  Easily script complex workflows

  Full access to Struts features

  Can exist side-by-side regular Struts actions

  Ability to run in non-Struts environments (uses Jakarta's Commons-Chain)

  Enhanced Java API methods and Collections integration

  Remote RPC support (termed Ajax but with JSON instead of XML) for callingflow methods from

the client

  Includes Wizard library to help easily create complex wizards

  Includes Javascript Templates library to replace JSP for a 100% Javascriptview layer.

  Includes number guessing, remote rpc, Javascript Templates, and wizardexamples

Struts are a Web Application 'Framework'.

Struts–a collection of Java code designed to help you build solid applications while saving time. Struts

are based on the time-proven Model-View-Controller (MVC) design pattern. The MVC pattern is

widely recognized as being among the most well-developed and mature design patterns in use. By

using the MVC design pattern, processing is broken into three distinct sections aptly named the

Model, the View, and the Controller.

Model Components

Model components are generally standard Java classes.

View Components

View components are generally built using Java Server Page (JSP) files.

Controller Components

Controller components in Struts are Java classes and must be built using specificrules. They are usually

referred to as "Action classes."