43
1. Write a complete program for each of the following: Decision Making Statements Looping Statements Decision Making Statements If-else statement The if statement is Java’s conditional branch statement. It can be used to route program execution Through two different paths. Here is the general form of the if statement: if (condition) statement1; else statement2; Here, each statement may be a single statement or a compound statement enclosed in curly braces (That is, a block). The condition is any expression that returns a Boolean value. The else clause is that Optional. The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed.

MC0078 – Java Programming set-2

Embed Size (px)

Citation preview

Page 1: MC0078 – Java Programming set-2

1. Write a complete program for each of the following: Decision Making Statements Looping Statements

Decision Making Statements

If-else statement

The if statement is Java’s conditional branch statement. It can be used to route program execution

Through two different paths. Here is the general form of the if statement:

if (condition)

statement1;

else

statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly braces

(That is, a block). The condition is any expression that returns a Boolean value. The else clause is that Optional.

The if works like this:

If the condition is true, then statement1 is executed.

Otherwise, statement2 (if it exists) is executed.

In no case will both statements be executed.

For example, consider the following: both

Most often, the expression used to control the if will involve the relational operators.

However, this is not technically necessary. It is possible to control the if using a single Boolean variable, as shown in this code fragment:

Page 2: MC0078 – Java Programming set-2

boolean dataAvailable;

// …

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;

}

else

waitForMoreData();

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:

Page 3: MC0078 – Java Programming set-2

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)

{

ProcessData();

bytesAvailable -= n;

}

else

{

Page 4: MC0078 – Java Programming set-2

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;

.

.

.

else

statement;

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

{

Page 5: MC0078 – Java Programming set-2

public static void main(String args[ ])

{

int month = 4; // April

String season;

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

season = "Winter";

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.

Page 6: MC0078 – Java Programming set-2

Here is the general form of a switch statement:

Switch (expression)

{

case value1:

// statement sequence

break;

case value2:

// statement sequence

break;

.

.

.

case valueN:

// statement sequence

break;

default:

// default statement sequence

}

The expression must be of type byte, short, int, or char; each of the values specified in the case

statements must be of a type compatible with the expression. Each case value must be a unique

literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.

Page 7: MC0078 – Java Programming set-2

The switch statement works like this: The value of the expression is compared with each of the literalcompared values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of "jumping out" of the switch.

Example

The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. Forhave example, consider the following program:

// In a switch, break statements are optional.

class MissingBreak

{

public static void main(String args[ ])

{

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

switch(i)

{

case 0:

case 1:

case 2:

case 3:

case 4:

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

break;

case 5:

case 6:

Page 8: MC0078 – Java Programming set-2

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 10

i is less than 10

i is 10 or more

i is 10 or more

Nested switch Statements

Page 9: MC0078 – Java Programming set-2

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

Page 10: MC0078 – Java Programming set-2

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.

Looping Statements

‘for’ Loop

The usage of for loop is as follows

for (initial statement; termination condition; increment instruction)

statement;

When multiple statements are to be included in the for loop, the statements are included inside

flower braces. for (initial statement; termination condition; increment instruction)

{

statement1;

statement2;

}

The example below prints numbers from 1 to 10

The results of the above program is shown below

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

{

Page 11: MC0078 – Java Programming set-2

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

Page 12: MC0078 – Java Programming set-2

}

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional 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.

do….while’ statement

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the termination beginning. Fortunately, Java supplies a loop that does just that: the do while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

Its general form is

do

{

// body of loop

}

while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates thewhile conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. Loop As with all of Java’s loops, condition must be a boolean expression.

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[])

Page 13: MC0078 – Java Programming set-2

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) {");

Page 14: MC0078 – Java Programming set-2

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

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

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

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

System.out.println("}");

break;

case ‘3′:

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;

}

}

}

Page 15: MC0078 – Java Programming set-2

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.

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 you type will be sent to your program.

Java’s console input is quite limited and awkward to work with. Further, most real-world Javaprograms 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.

Page 16: MC0078 – Java Programming set-2

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.

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.

Page 17: MC0078 – Java Programming set-2

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();

Page 18: MC0078 – Java Programming set-2

// 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. */

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

Page 19: MC0078 – Java Programming set-2

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 can access 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. 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

Page 20: MC0078 – Java Programming set-2

database access

Java Application

JBDC

DBMS Proprietary Protocol

DBMS

Database Server

Client Machine

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 back to 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.

Three-tier Architecture for Data Access

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Javaspecific platform is fast becoming the standard platform for middle tier development. This is a big plus,middle-tier making it possible to take advantage of Java’s robustness, multithreading, and security features. With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three tier architecture. Some of the features three-tierf that make JDBC a server technology are its support for connection pooling, distributed transactions,and disconnected row sets. The JDBC API is also what allows access to a data source from a Java middle tier.

Page 21: MC0078 – Java Programming set-2

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 class is 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 an abstract 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

Page 22: MC0078 – Java Programming set-2

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. 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 static methods, 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 there 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 23: MC0078 – Java Programming set-2

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

Page 24: MC0078 – Java Programming set-2

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

</tr>

<tr>

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

</tr>

</table>

</html:form>

</body>

</html>

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

Page 25: MC0078 – Java Programming set-2

{

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>

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

<tr>

Page 26: MC0078 – Java Programming set-2

<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

Page 27: MC0078 – Java Programming set-2

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));

}

}

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 the

following 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>

Page 28: MC0078 – Java Programming set-2

<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:

Page 29: MC0078 – Java Programming set-2

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());

counter = new Counter();

Page 30: MC0078 – Java Programming set-2

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:

Page 31: MC0078 – Java Programming set-2

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

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 destroymethod.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();

Page 32: MC0078 – Java Programming set-2

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");}}

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

Page 33: MC0078 – Java Programming set-2

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";

}

}

}

Features of Struts are as follows:

Easily script complex workflows

Page 34: MC0078 – Java Programming set-2

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. Strutsare 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 theModel, 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."