MCA Sem. IV Java Programming Assignment Set -1 Q. 1. Write a program to perform the basic arithmetic operations: a) Addition class Prog21 { public static void main(String[] args) { int i = 10; int j = 20; i = i + j; System.out.println("The sum is: " + i); } } b) Subtraction
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
MCA Sem. IV
Java Programming
Assignment Set -1
Q. 1. Write a program to perform the basic arithmetic operations:
a) Addition
class Prog21 {
public static void main(String[] args) {
int i = 10;
int j = 20;
i = i + j;
System.out.println("The sum is: " + i);
}
}
b) Subtraction
class Prog21 {
public static void main(String[] args) {
int i = 20;
int j = 10;
i = i - j;
System.out.println("The sum is: " + i);
}
}
c) Multiplication
class Prog21 {
public static void main(String[] args) {
int i = 20;
int j = 10;
i = i * j;
System.out.println("The sum is: " + i);
}
}
d) Division
class Prog21 {
public static void main(String[] args) {
int i = 20;
int j = 10;
i = i / j;
System.out.println("The sum is: " + i);
}
}
Q. 2. Discuss the following with suitable example programs for each:
A) Data Types in Java
There are two kinds of data types in Java
· Primitives/standard data types.
· Abstract/derived data types.
Primitives Data Types
Primitive data types (also know as standard data types) are the data types that are built
into the Java language. The Java compiler holds details instructions on each operation the
data types that are built into the Java language. The Java compiler holds detailed
instructions on each legal operation the data type supports. There are eight primitive data
types in Java.
The data types – byte, short, int, long, float and double are numeric data types. The first
four of these can hold only whole numbers whereas the last two (float and double) can
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers.
The port numbers ranging from 0 – 1023 are restricted; they are reserved for use by well-
known services such as HTTP and FTP and other system services. These ports are called
well-known ports. Your applications should not attempt to bind to them.
C) Datagram
Clients and servers that communicate via a reliable channel, such as a TCP socket, have a
dedicated point-to-point channel between themselves, or at least the illusion of one. To
communicate, they establish a connection, transmit the data, and then close the
connection. All data sent over the channel is received in the same order in which it was
sent. This is guaranteed by the channel.
In contrast, applications that communicate via datagrams send and receive completely
independent packets of information. These clients and servers do not have and do not
need a dedicated point-to-point channel. The delivery of datagrams to their destinations is
not guaranteed. Nor is the order of their arrival.
Definition: A datagram is an independent, self-contained message sent over the network
whose arrival, arrival time, and content are not guaranteed.
The java.net package contains three classes to help you write Java programs that use
datagrams to send and receive packets over the network: Datagram Socket. Datagram
Packet, and Multicast Socket An application can send and receive Datagram Packets
through a Datagram Socket. In addition, Datagram Packets can be broadcast to multiple
recipients all listening to a Multicast Socket
1. Write a complete program for each of the following:Decision Making StatementsAns: If-else statementThe if statement is Java’s conditional branch statement. Itthrough 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 isoptional.The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2(if itexists) is executed. In no case will botMost often, the expression used to control the if will involve the relational operators. However, this isnot technically necessary. It is possible to control the if using a single boolean vathis code fragment:boolean dataAvailable;// …Master of Computer Application (MCA)MC0078 – Java Programming(Book ID: B0831 & B0832can be used to route program executionhat both statements be executed. For example, consider theJuly 2011– Semester 4– 4 CreditsB0832) Assignment Set – 2h following:variable, as shown inif (dataAvailable)ProcessData();elsewaitForMoreData();Remember, only one statement can appear directly after the if or the else. If you want to includemore 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. Someprogrammers find it convenient to include the curly braces when using the if, even when there is onlyone statement in each clause. This makes it easy to add another statement at a later date, and youdon’t have to worry about forgetting the braces. In fact, forgetting to define a block when one isneeded is a common cause of errors. For example, consider the following code fragment:int bytesAvailable;// …
if (bytesAvailable > 0) {ProcessData();bytesAvailable -= n;} elsewaitForMoreData();bytesAvailable = n;It seems clear that the statement bytesAvailable = n; was intended to be executed inside the elseclause, 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 withoutcomplaint, 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 {waitForMoreData();bytesAvailable = n;}The if-else-if LadderA common programming construct that is based upon a sequence of nested ifs is the ifelseifladder. 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 ifis true, the statement associated with that if is executed, and the rest of the ladder is bypassed. Ifnone of the conditions is true, then the final else statement will be executed. The final else acts as adefault condition; that is, if all other conditional tests fail, then the last else statement is performed. Ifthere 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; // AprilString 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";elseseason = "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 whatvalue you give month, one and only one assignment statement within the ladder will be executed.Switch StatementThe switch statement is Java’s multiway branch statement. It provides an easy way to dispatchexecution 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 sequencebreak;case value2:// statement sequencebreak;...case valueN:// statement sequencebreak;default:// default statement sequence}The expression must be of type byte, short, int, or char; each of the values specified in the casestatements must be of a type compatible with the expression. Each case value must be a uniqueliteral (that is, it must be a constant, not a variable). Duplicate case values are not allowed.The switch statement works like this: The value of the expression is comparvalues in the case statements. If a match is found, the code sequence following that case statement isexecuted. If none of the constants matches the value of the expression, then the default statement isexecuted. 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 breakstatement is encountered, execution branches to thestatement. This has the effect of "jumping out" of the switch.ExampleThe break statement is optional. If you omit the break, execution will continue on into the next case.
It is sometimes desirable to hexample, 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:compared with each of the literalfirst line of code that follows the entire switchhave multiple cases without break statements between them. Fored avecase 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 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is 10 or morei is 10 or moreNested switch StatementsYou can use a switch as part of the statement sequence of an outer switch. This is called a nestedswitch. Since a switch statement defines its own block, no conflicts arise between the case constantsin the inner switch and those in the outer switch. For example, the following fragment is perfectlyvalid:
switch(count) {case 1:switch(target) { // nested switchcase 0:System.out.println("target is zero");break;case 1: // no conflicts with outer switchSystem.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 theouter 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 typeof Boolean expression. That is, the switch looks only for a match between the value of the expressionand one of its case constants.
No two case constants in the same switch can have identical values. Of course, a switch statementenclosed 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 andcreate a "jump table" that it will use for selecting the path of execution depending on the value of theexpression. Therefore, if you need to select among a large group of values, a switch statement will runmuch faster than the equivalent logic coded using a sequence of if-elses. The compiler can do thisbecause it knows that the case constants are all the same type and simply must be compared forequality with the switch expression. The compiler has no such knowledge of a long list of ifexpressions.Looping StatementsAns: ‘for’ LoopThe usage of for loop is as followsfor (initial statement; termination condition; increment instruction)statement;When multiple statements are to be included in the for loop, the statements are included insideflower braces. for (initial statement; termination condition; increment instruction){statement1;statement2;}The example below prints numbers from 1 to 10The results of the above program is shown belowLike all other programming languages, Java allows loops to be nested. That is, one loop may be insideanother. 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 StatementThe while loop is Java’s most fundamental looping statement. It repeats a statement or block while itscontrolling 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 codeimmediately following the loop. The curly braces are unnecessary if only a single statement is beingrepeated.Exampledo….while’ statementAs you just saw, if the conditional expression controlling a while loop is initially false, then the bodythe loop will not be executed at all. However, sometimes it is desirable to execute the body of a whileloop at least once, even if the conditional expression is false to begin with. In other words, there aretimes when you would like to test the termibeginning. Fortunately, Java supplies a loop that does just that: the doalways executes its body at least once, because its conditional expression is at the bottom of theIts general form isdo {// body of loop} while (condition);Each iteration of the do-while loop first executes the body of the loop and then evaluates theconditional expression. If this expression is true, the loop will repeat. Otherwise, the looAs with all of Java’s loops, condition must be a boolean expression.Exampletermination expression at the end of the loop rather than at thedo-while. The doofnation do-while looploop.loop terminates.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 whichimplements a very simple help system for Java’s selection and iterationstatements:// Using a do-while to process a menu selectionclass 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′: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. if2. switch3. while4. do-while5. forChoose 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 theperfect loop to accomplish this.A few other points about this example: Notice that characters are read from the keyboard by callingSystem.in.read( ). This is one of Java’s console input functions. Although Java’s console I/O methodswon’t be discussed in detail until System.in.read( ) is used here to obtain the user’s choice. It readscharacters 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 Javaprograms and applets will be graphical and window-based. For these reasons, not much use ofconsole 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.IOExceptionclause. 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 creationof hierarchical classifications. Using inheritance, you can create a general class that defines traitscommon 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 iscalled a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is aspecialized version of a superclass. It inherits all of the instance variables and methods defined by thesuperclass 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.Syntaxpublic class <subclass_name>extends<superclass_name>Examplepublic 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 privatekeyword 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 ofits 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 20Contents of subOb:i and j: 7 8k: 9Sum of i, j and k in subOb:i+j+k: 24As 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 werepart of B.Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being asuperclass for a subclass does not mean that the superclass cannot be used by itself. Further, asubclass 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 theinheritance of multiple superclasses into a single subclass. (This differs from C++, in which you caninherit multiple base classes.) You can, as stated, create a hierarchy of inheritance in which a subclassbecomes 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 aRelational Database.JDBC helps you to write java applications that manage these three programming activities:1. Connect to a data source, like a database2. Send queries and update statements to the database3. Retrieve and process the results received from the database in answer to your queryJDBC Architecture: - The JDBC API supports both two-tier and three-tier processing models fordatabase 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 driverthat can communicate with the particular data source being accessed. A user’s commands aredelivered to the database or other data source, and the results of those statements are sent back tothe user. The data source may be located on another machine to which the user is connected via anetwork. This is referred to as a client/server configuration, with the user’s machine as the client, andthe machine housing the data source as the server. The network can be an intranet, which, forexample, 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 thecommands 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 veryattractive because the middle tier makes it possible to maintain control over access and the kinds ofupdates that can be made to corporate data. Another advantage is that it simplifies the deploymentof applications. Finally, in many cases, the three-tier architecture can provide performanceadvantages.DBMSClient Machine
DBMS Proprietary ProtocolDatabase ServerJava ApplicationJBDCUntil recently, the middle tier has often been written in languages such as C or C++, which offer fastperformance. However, with the introduction of optimizing compilersinto efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Javaplatform is fast becoming the standard platform for middlemaking it possible to take advantageWith enterprises increasingly using the Java programming language for writing server code, the JDBCAPI is being used more and more in the middle tier of a threethat make JDBC a server technology are its support for connection pooling, distributed transactions,and disconnected rowsets. The JDBC API is also what allows access to a data source from a Javamiddle tier.Three-tier Architecture for Data Access
that translate Java bytecodemiddle-tier development. This is a big plus,of Java’s robustness, multithreading, and security features.three-tier architecture. Some of the ffeatures4. 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 declaringone or more methods abstract. An abstract method has no body (i.e.,no implementation). A subclassis 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 methodpublic 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 theinterface must conform to in terms of the type signature of the methods. The class that implementsthe 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 canhave either public, package, private or protected access defined. All methods declared in an interfaceare implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant todeclare 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 inan 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 Interfacenames and class names in the same package must be distinct.public interface interface-name {// if any data are defined, they must be constantspublic static final type-name var-name = constant-expr;// one or more implicitly abstract and public methodsreturn-type method-name ( formal-params );}When to use an Interface vs when to use an abstract classHaving reviewed their basic properties, there are two primary differences between interfaces andabstract classes:
An abstract class can have a mix of abstract and non-abstract methods, so some defaultimplementations 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 itcan contain features inherent to a class. The downside to an abstract base class, is that since theiris 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 methodsignatures 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 themethods of the interface. Since you can inherit multiple interfaces, they are often a very usefulmechanism to allow a class to have different behaviors in different situations of usage byimplementing multiple interfaces.It is usually a good idea to implement an interface when you need to define methods that are to beexplicitly overridden by some subclass. If you then want some of the methods implemented withdefault implementations that will be inherited by a subclass, then create an implementation class forthe interface, and have other class inherit (extend) that class, or just use an abstract base class insteadof an interface5. Explain the working of struts with an example.Ans: Struts is modeled after the MVC design pattern, you can follow a standard development process forall of your Struts Web applications.Identificaty of the application Views, the Controller objects that will service those Views, and theModel components being operated on.1. Define and create all of the Views, in relation to their purpose, that will represent the userinterface of our application. Add all Action Forms used by the created Views to the strutsconfig.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 theWeb application.Let’s Start with step one. We will create the view file named index.jspindex.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>Action: Represents the URL to which this form will be submitted. This attribute is also used to find theappropriate Action Mapping in the Struts configuration file, which we will describe later in thissection. The value used in our example is Name, which will map to an Action Mapping with a pathattribute equal to NameName: Identifies the key that the ActionForm will be referenced by. We use the value NameForm. AnActionForm is an object that is used by Struts to represent the form data as a JavaBean. It mainpurpose is to pass form data between View and Controller components. We will discuss NameFormlater 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 membersmatching the inputs of this form.NameForm.javapackage example;//import statementsimport 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><table width="80%" border="0"><tr><td>Hello <%= request.getAttribute("NAME") %> !!</td></tr></table></body></html>NameAction.javapackage 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 parametersNameForm nameForm = (NameForm)form;String name = nameForm.getName();}// if no mane supplied Set the target to failureif ( 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 theNameAction 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 /WEBINF/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 beexecuted. 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 ContextListenerimplements 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();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. Whena request is mapped to a servlet, the container performs the following steps.1. If an instance of the servlet does not exist, the Web container2. 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 EventsYou can monitor and react to events in a servlet's life cycle by defining listener objects whosemethods get invoked when life cycle events occur. To use these listener objects, you must define thelistener class and specify the listener class.The listeners.ContextListener class creates and removes the database helper and counter objects usedin the Duke's Bookstore application. The methods retrieve the Web context object fromServletContextEvent and then store (and remove) the objects as servlet context attributes.CODE:import database.BookDB;import javax.servlet.*;import util.Counter;public final class ContextListenerimplements 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();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 makesdevelopers more productive by providing them a series of tools and components to build applicationswith. Struts fall sunder the Jakarta subproject of the Apache Software Foundation and comes with anOpen 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 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 iswidely recognized as being among the most well-developed and mature design patterns in use. Byusing the MVC design pattern, processing is broken into three distinct sections aptly named the
Model, the View, and the Controller.Model ComponentsModel components are generally standard Java classes.View ComponentsView components are generally built using Java Server Page (JSP) files.Controller ComponentsController components in Struts are Java classes and must be built using specificrules. They are usually