Saturday, October 29, 2011

exceptions


EXCEPTION HANDLING

EXCEPTION HANDLING

1). What is Exception?

An exception is an abnormal condition that arises on programming code at run time. An exception is a run time error.

2). What is java Exception?

A java Exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown to the method that caused error. That method may choose to handle the exception itself or pass to on.

3). How many ways the java exception occurred?

There are two ways.
1). Java run-time system. 2). Manually generated by programming code.

4). What does java run-time system exception means?

Exception thrown by java relate to fundamental errors that violate the rules of the java language. Java run-time system exception are automatically thrown by the java run-time system.

5). What does manually generated exception?

Manually generated exceptions are used to report some error condition to the caller of a method. To manually throw an exception, use keyword throw.

6). How does java exception managed or handled?

Java exception handling is managed via five keywords: try, catch, and throw, throws, finally.

7). How does exception handling work?

Program statements that monitor for exception are contained within a try block. If an exception occurs within the try block, it is thrown. The catch clause can catch this exception and handle the exception.
Note: all exception types are subclasses of built-in class Throwable.

8). What is uncaught exception?

Any exception is not caught by program will be processed by the default handler. The default handler displays a string that describes the exception, print stack trace and terminates the program.

9) What is stack trace?

The stack trace will show the sequence of method invocation that led up to the error.

10) Although java run-time systems handle exception, why we use try and catch?

Two benefits:
1). It allows to fix error. 2). It prevents the program from automatically terminating.

11). Why we use multiple catch clauses for single statement?

In some cases, more than one exception can be raised by a single piece of code. To handle this type of exception, you can specify two or more catch clauses, each catch have different type of exception. When an exception is thrown, each catch statement is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement excutes, the others are bypassed, and execution continues after the try/catch block.

12). What is nested try statement?

The try statement can be nested. A try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or the java run-time system will handle the exception.

13). What is throwing an Exception?.

The act of passing an Exception Object to the runtime system is called Throwing an Exception.

14) What is the use of throw statement?

It is possible to throw an exception explicitly using throw statement.

15) What is the use of throws statement?

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that the callers of the method can guard themselves against that exception. We do this by using throws clause in method’s declaration. The throws clause lists the types of exceptions that a method might throw. This is necessary for all exception except the type Error or Runtime Exception or their subclasses. All exception that a method can throw must be declared in the throws clause. If they are not, the compile time error will result.

16). What is the unchecked exception?

An unchecked exception need not be included in any method’s throws list. Because the compiler dose not check if a method handles or throws these exceptions.

17). What is the checked exception?

A checked exception included in method’s declaration if the method can generated one of these exceptions and does not handle it itself.

18). What is chained exception?

The chained exception features allow to associate another exception with an exception. The second exception describes the cause of the first exception.

19) What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

20). What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

21) What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

22) What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

23) Does the code in finally block get executed if there is an exception and a return statement in a catch block?

If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

24)When is the ArrayStoreException thrown?

When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

25) WHEN IS THE ArithmeticException thrown?

The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

26)What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

27)Can an exception be rethrown?

Yes, an exception can be rethrown.

28)What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

29)Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.

30)What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.

31)What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

32)How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

33) Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can create by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}


34) What are checked exceptions?

Checked exceptions are those that the Java compiler forces you to catch. e.g. IOException are checked Exceptions.


35) What are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.


36) What is the difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

37) How to create custom exceptions?

Your class should extend class Exception.


38) If I want an object of my class to be thrown as an exception object, what should I do?

The class should extend from Exception class. Or you can extend your class from some more precise exception type also.


39) If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

One cannot do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

40). How does an exception permeate through the code?

An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

41) What are the different ways to handle exceptions?

There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

42) What is the basic difference between the 2 approaches to exception handling.

1. Try catch block and
2. Specifying the candidate exceptions in the throws clause

When should you use which approach?

In the first approach as a programmer of the method, you yourself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

43) Is it necessary that a catch block must follow each try block?

It is not necessary that a catch block must follow each try block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

44) If I write return at the end of the try block, will the finally block still execute?

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.


45) If I write System.exit (0); at the end of the try block, will the finally block still execute?

No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.


46) How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

47) What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.


48) Which package contains exception handling related classes?

java.lang

49) What are the two types of Exceptions?

Checked Exceptions and Unchecked Exceptions.

50) What is the base class of all exceptions?

java.lang.Throwable

51) What is the difference between Exception and Error in java?

Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

52) What is the difference between throw and throws?

throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

53) Differentiate between Checked Exceptions and Unchecked Exceptions?

Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.

Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions.

54) What are User defined Exceptions?

Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

55) What is the importance of finally block in exception handling?

Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

56) Can a catch block exist without a try block?

No. A catch block should always go with a try block.

57) Can a finally block exist with a try block but without a catch?

Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

58) What will happen to the Exception object after exception handling?

Exception object will be garbage collected.

59) The subclass exception should precede the base class exception when used within the catch clause. True/False?

True.

60) Exceptions can be caught or rethrown to a calling method. True/False?
True.

61) The statements following the throw keyword in a program are not executed. True/False?

True.

62) How does finally block differ from finalize() method?

Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

63) What are the constraints imposed by overriding on exception handling?

An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.

64). If we don’t use exception handling what will happen?

If we don’t use exception handling, the exception is caught by the default handler provided by java run-time system.


65). What are the types of error?

There are two type of error.

1). Compile-time error.
2). Run-time error.

66). What is compile time error?

All syntax error will be detected and displayed by java compiler. So they are compile time error.
If the compiler display error, it will not create .class file.


67). What is run time error?

The program may compile successfully and create .class file but may not run properly. Such a program may produce wrong result or terminate program. Exam is stack overflow.

New Features in Java 5 - From Programmers Point of View


New Features in Java 5 - From Programmer’s Point of View

With emergence of Java 5, a set of new features is included in Java technology. Many programmers working on Java technology were excited before its release about its new features. In this article, new features of Java 5 are summarized which are important from programmer’s point of view.

Language Features

Get Rid of ClassCastException With Generics
It is very common experience among programmers to face ClassCastException at run time while integrating different parts (modules) of application which are interacting with each other in form of collections where collections are passed as parameters to methods or returned from methods or set and get in a common place holder mechanism like session. To avoid this scenario Generics are introduced in Java 5. Here is one example how to use Generics with collection classes.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* Note that there is no need to cast the object to Integer class any more*/;;
void userOfCollection(Collection pInt) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Iterator< Integer > i = pInt.iterator(); i.hasNext(); ) ;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Generic is most important and quite hyped feature of Java 5. Prior to this, there was no way to know which type of object is residing there in the collection. Generic helps programmers to integrate their stuff with each other in a declarative manner.
New Convenient for Loop
The “for” loop in Java language has been enhanced to iterate through collections. Here is the example how it works with collections.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/*Old way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void oldForLoop(Collection c) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Iterator< Integer > i = c.iterator(); i.hasNext(); );;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}..........;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* New way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void newForLoop(Collection c) {;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.....for (Integer i : c);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}.....;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
If you notice here, to iterate through a collection using a “for” loop has been very simple now. Prior to this, most time Iterator and Enumerator classes were used to iterate through collection objects. And in most implementations people need to iterate through collection objects.
This new implementation also helps in avoiding NoSuchElementException at run time. It also makes the code more readable and maintainable.
Autoboxing of Primitives
In the example we have discussed in the previous topic, we did something which is not required in Java 5
if(i.next.intValue() == 4)
Here in this assertion, we have to take primitive int type value from the Integer type object using intValue() method. Even to store any primitive value such as int or long in a collection object one needs to wrap it in wrapper class first and store it.
This overhead is no more required in Java 5. With autoboxing, wrapper objects can directly act as primitive type values as and when required. So we can write the above assertion statement this way also.
if(i.next == 4)
The same mechanism can be used to place primitive values in collections without wrapping them in wrapper classes.
Introduction of Enums
Type safe enum was long awaited feature in Java language. It has been introduced in Java 5.
To represent a constant custom type there was no way except definition String or int constant literals like
public static final String DAY_MONDAY = “Monday”;
public static final String DAY_TUESDAY = “Tuesday”;
But now with the introduction of enums in Java, there is a type safe and standard mechanism of defining custom types for multiple values.
Example:
enum DAY { MONDAY, TUESDAY }
This way, Monday and Tuesday are no longer String literals and also String operations cannot be performed on them (which are actually not required).
Varying Arguments – Varargs
Varargs is another step towards Java community’s commitment for object orientation and convenience of programming. We know that when we need to pass multiple values to a method as parameter, array of values (or objects) is efficient and convenient way. But, with the introduction of Varargs it has been more convenient to pass arrays or set of arguments to methods.
E.g. If a method is defined like
void doSomeThing(String[] args){}
As a client to call this method, one has to first create an array containing Strings and then call the method with that array of string as argument.
doSomeThing({“A”,”B”,”C”});
But, with varargs
void doSomeThing(String… args){}
This method can be called in two different ways.
doSomeThing({“A”,”B”,”C”});
or
doSomeThing(“A”,”B”,”C”);
Here String… in method declaration indicates that at a placeholder here either an array of String should be passed or String literals can directly be passed.But it is not advisable to override a method with vararg because it may lead confusion while calling.
Avoid Using Constant Interface Antipattern
Prior to Java 5, there was an ugly approach in using constant values named as Constant Interface Antipattern. To keep constants at one place and make them accessible in different classes of the application, it was a custom to define an interface containing all constants, other classes had to implement the interface wherever those constants were required. Actually this approach conflicts with the object orientation of Java language. Such constants are implementation details for a class but if the class accesses them by implementing an interface they become a part of public access (API) of the class. It means implementation details are being linked as API here.
To avoid this behavior, Constant Imports are introduced in Java 5. Using constant imports one can avoid implementing such interfaces.
E.g. import static com.mycompany.MyClass.MyConstant;
This constant can then be used without class qualificationint l = 5* MyConstant;

Enhancements in Libraries

Language and Utility (lang and util packages)
  • ProcessBuilder: Introduced as enhancement to be used in place of Runtime.exec method. It offers more flexibility.
  • Formatter: This new class has been introduced to improve formatting facility in Java language for String, Date, Time, and Number etc.
  • Scanner: This new class is based in regex implementation. It can be used to read and search from streams for a particular pattern or into a particular primitive type or String.
Networking
  • Ipv6 on Windows Xp and 2003 server is supported.
  • Timeout can be enabled and customized for any connection.
  • InetAdderess API has been improved in a way that it can be used to verify if host is reachable or not.
  • CookieHandler API has been introduced for better handling of cookies.
I18N (Internationalization)
  • Unicode Standard Versions 4.0 now forms basis for character handling.
  • DecimalFormat class has been improved in a way that precision is not lost while parsing BigDecimal and BigInteger values.
  • New language support: Vietnamese

Enhancements in Integration Libraries

Java Naming and Directory Interface (JNDI)
  • NameClassPair has been improved to access full name from directory or service.
  • More standard LDAP controls are being supported now e.g. Manage Referral Control, Paged Results Control and Sort Control
  • Improved functionality to modify LDAP names
JDBC
Five new implementation of RowSet interface has been provided with Java 5.
  • Straightforward implementation of RowSet functionality is JdbcRowSet.
  • CachedRowSet is a lightweight implementation in a way that it dose not hold connection to the data source all time. Once any operation is performed on the data source, it ends the connection and caches data offline.
  • Another implementation of CachedRowSet is FilteredRowSet. This can be used to derive subset of data from cached data of CachedRowSet.
  • JoinRowSet is also one of implementations of CachedRowSet. It can be used to derive data from multiple RowSets based on a SQL join.
  • To describe XML data in tabular format using standard XML schema, WebRowSet has been implemented. It is also extending CachedRowSet.
RMI
  • Stub classes can be generated dynamically in Java 5. With introduction of dynamic stub class generation, one does not need to run rmic compiler to generate stub classes for RMI applications. But, to be prior versions compliance, still one has option to run rmic for older version clients.
  • Standard APIs for SSL and TLS has been added to standard RMI library. So now RMI applications can communicate over secured Socket Layer or Transport Layer Security.

Summary

From programmer’s point of view there are some revolutionary improvements in Java 5. These changes are aimed to improve convenience, stability and performance of application development using Java technology. Also one can opt to make applications more robust by going for features of Java 5 like Enums, Generics, for-each loop and Autoboxing. These features are more targeted to make the code simpler and easy to maintain. Library enhancements are going to help programmers in implementing their ideas in better way. And JDBC enhancements are aimed to support separate data access layer in web and enterprise applications.But, some people never like to change things around them, for them they can always program Java applications the way they have been doing prior to release of Java 5.

JSP



JSP Basics

Author : Exforsys Inc.     Published on: 7th May 2006

JSP Basics

Java Server Pages (JSP) is a Java API in J2EE which allows dynamic creation of web pages using Java. It has the same purpose as other existing technologies like CGI or PHP. In this tutorial you will learn about Lifecycle of JSP pages, Dynamic content generation, Invoking Java code using JSP scripting elements, JavaBeans for JSP and Error Handling.


The main difference between servlets and JSPs is that servlets are Java classes and JSPs are not (they are embedded in HTML pages). This difference also specifies where you want to use servlets and where you want to use JSPs: If you generate all of your html pages dynamically and will have complex logic, you will probably use servlets. If dynamic content is very low compared to the static content in your web page, then you will probably use JSPs.

Lifecycle of JSP pages

The lifecycle of a JSP is shown in Figure-1. The most important fact about this figure is that all JSPs are managed by JSP containers and compiled into servlets before they are loaded. Similar to servlets, the same instance is used for all requests since JSP is compiled into a servlet..
Figure-1 Life cycle of a JSP

Dynamic content generation

In this section, we will create our first JSP which will write “Hello World” to the web page if no user-name parameter is given. If user-name parameter is given (e.g. Smith), then it will print “Hello < user-name >”. (e.g. Hello Smith).
The source code shown in this section can be found in HelloWorldJSP project.
The source code of HelloWorld.jsp is shown in Figure-2.
Figure-2 The source code of HelloWorld.jsp
Figure-3 shows the HelloWorld.jsp when it is run without a user-name. The result of running the same JSP with a user-name of John is shown in Figure-4. As you will notice user-name is given to the JSP as a name parameter added to the URL of the JSP.
Figure-3 HelloWorld.jsp without a user-name parameter
Figure-4 HelloWorld.jsp with a user-name parameter

Invoking Java code using JSP scripting elements

In this section we will create an example which shows how to define Java methods, how to call methods and how to call methods in standard Java libraries using JSPs. Specifically, we will define a factorial method which can return factorial of a number, call factorial method and get a random number from java.lang.Math class in “JavaIntegration.jsp“ file we created.
The source code shown in this section can be found in JavaIntegrationJSP project.
Figure-5 shows the contents of “JavaIntegration.jsp” file. The code is very easy to understand since all we do is to add Java code inside jsp tags and it has comments where they are needed. Figure-6 shows the output of the “JavaIntegration.jsp”.
Figure-5 Contents of JavaIntegration.jsp file
Figure-6 Output of JavaIntegration.jsp file

JavaBeans for JSP

We will modify “HelloWorld.jsp” developed in the “Dynamic Content Generation” section so that it will use a java beans at the background. Figure-5 shows HelloWorldJavaBean class which will be used by the HelloWorld.jsp.
The source code shown in this section can be found in HelloWorldBeanJSP project.
Figure-5 HelloWorldBean class
Figure-6 shows the contents of HelloWorld.jsp file which uses HelloWorldBean by the help of useBean, setProperty and getProperty tags.
Figure-6 HelloWorld.jsp file
Figure-7 shows the HelloWorld.jsp when it is run without a user-name. The result of running the same JSP with a user-name of John is shown in Figure-8. As you will notice user-name is given to the JSP as a name parameter added to the URL of the JSP as before.
Figure-7 HelloWorld.jsp without a user-name parameter
Figure-8 HelloWorld.jsp with a user-name parameter

Error Handling

Although there can be other error handling methods depending your development tools and jsp container, we will show an example for “error.jsp” page strategy in this section.
“error.jsp” page is a java server page where the errors are redirected when any found. So by setting a special parameter for error redirection in our jsp pages we can handle all errors in one jsp page.
The source code shown in this section can be found in ErrorPageJSP project.
Figure-9 shows the contents of the error.jsp file which will be called by index.jsp when an exception occurs. Setting isErrorPage directive to true, we explicitly state that this jsp page is for handling errors to the JSP container. This allows error.jsp to have an “exception” object automatically which can be used for error reporting.
Figure-9 Contents of error.jsp page
Figure-10 shows contents of index.jsp page. Since we tried to convert a non-integer string into an integer, we will get a NumberFormatException and the control is redirected to error.jsp page internally. The errorPage directive is set to the error.jsp since we want to be directed to error.jsp page when some error occurs.
Figure-10 Contents of index.jsp page
The output of index.jsp (which is in fact redirected to error.jsp internally) is shown in Figure-11.
Figure-11 Output of index.jsp page

Servlets


Servlet Basics

Servlets are Java programs running on a web server that produce results viewed remotely on a web server. Servlets has the same purpose that CGI or PHP had in the past. We shall describe how Servlets works with some examples. You will also learn about Servlet Request and Response Model, Servlet Life Cycle, Servlet Scope Objects and Error Handling.

Servlet Request and Response Model

Note that although there are two types of servlets (GenericServlet and HttpServlet), we will discuss here only HttpServlet since GenericServlet can be used for advanced needs. The important thing here is that you should use GenericServlet if you want your servlet to response in another protocol rather than HTTP.
Figure-1 Request and Response Model of HttpServlets
HttpServlets are servlets that respond to the HTTP protocol requests which is used by web servers to return us the requested web pages. We need to extend javax.servlet.http.HttpServlet class to write a servlet. We should select one of doGet or doPost methods for overriding. This choice depends on what type of http request (GET request or POST request) we are expecting. GET request is generally only used to retrieve data from the web server, however POST request are used for more complex requests like storing data. We will generally override both methods in our tutorials and call a processRequest method to handle both types of request.
Let’s start with our first servlet which is called HelloWorld1 servlet. HelloWorld1 servlet will just print “Hello World1” message.
The source code shown in this section can be found in HelloWorld1 project.
Figure-2 shows overridden doGet and doPost methods in our HelloWorld1 servlet. Both methods call processRequest method to handle the http requests. Figure-3 shows processRequest method.
..........processRequest(request, response);..........processRequest(request, response);
public class HelloWorld1 extends HttpServlet {
.
/** Processes requests for both HTTP < code >GET< /code > and < code >POST< /code > methods.
* @param request servlet request
* @param request servlet response
*/
.
protected void processRequest (HttpServletRequest request, HttpServletResponse response)
.....throws ServletException, IOException {
.....response.setContentType(“text/html;charset=UTF-8”);
..........PrintWriter out = response.getWriter();
..........Out.println(“< html >”);
..........Out.println(“< head >”);
..........Out.println(“< title >Servlet HelloWorld1< /title >”);
..........Out.println(“< /head >”);
..........Out.println(“< body >”);
..........Out.println(“< h1 >HelloWorld1< /h1 >”);
..........Out.println(“< /body >”);
..........Out.println(“< /html >”);
..........Out.close();
}
Figure-3 ProcessRequest method used in HelloWorld1 servlet
We get the PrintWriter object from HttpServletResponse object to write the contents of the html page to other side. After writing our content, we close the PrintWriter object. You will get a result similar to shown in Figure-4 after you run the project.
Figure-4 HelloWorld1 servlet running in a browser

Servlet Life Cycle

Servlet container creates only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls doGet or doPost methods. This idea is shown in Figure-5.
Figure-5 A way of handling Servlet requests
The init method of the servlet is called when the servlet is first created and each time the server receives a request for a servlet, the server spawns a new thread calls service method.
The service method checks the HTTP request type (GET, SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. method as appropriate.
Finally, the server may decide to remove a previous loaded servlets. In this case, the server calls destroy method of the servlet.

Servlet Scope Objects

There are four scope objects in servlets which enables sharing information between web components. The scope objects and their corresponding Java classes are listed below:
• Web Context – javax.servlet.ServletContext
• Session – javax.servlet.http.HttpSession
• Request – javax.servlet.HttpServletRequest
• Page – javax.servlet.jsp.PageContext
You can get attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the client’s IP address by calling getRemoteAddr method of HttpServletRequest class.
Let’s develop an example on how to use servlet scope objects. In this example, we will print the information about the server which hosts our servlet.
The source code shown in this section can be found in ServerInfoServlet project.
In our example, we will use the following methods to get the information about the server which hosts the client:
public String getServerName()
public String getServerPort()
public String getServletContext().getServerInfo()
Figure-6 shows processRequestMethod of ServerInfoServlet servlet and Figure-7 shows the output of the servlet in a browser.
..........
public class ServerInfoServlet extends HttpServlet {
........../** Processes requests for both HTTP < code >GET< /code > and < code >POST< /code > methods.
* @param request servlet request
* @param request servlet response
*/
..........
protected void processRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
..........response.setContentType(“text/html;charset=UTF-8”);
..........PrintWriter out = response.getWriter();
..........
..........Out.println(“< html >”);
..........Out.println(“< head >”);
..........Out.println(“< title >Servlet ServerInfoServlet< /title >”);
..........Out.println(“< /head >”);
..........
..........Out.println(“< body >”);
..........Out.println(“< p >Server Name:+request.getServerName()+”< br >”);
..........Out.println( Server Port :+request.getServerPort()+”< br >”);
..........Out.println(“Server Path:+request.getServerPath()+”< /p >”);
..........
..........
Out.println(“< /body >”);
..........Out.println(“< /html >”);
..........
..........
Out.close();
}
..........
Figure-6 ProcessRequest method used in ServerInfoServlet servlet
Figure-7 ServerInfoServlet servlet running in a browser

Error Handling

There are two ways to handle errors in servlets. You can send an error message or throw a ServletException.
For example, if a servlet can not find the requested file, it can display a 404 (“File Not Found”) message to the user by using the following command instead of directly writing the output to the PrintWriter object:
response.sendError(HttpServletResponse.SC_NOT_FOUND)
There are several other HTTP error codes which can be sent to the client. Some of the important ones are listed in Table-1. You can search on the internet about the details of those messages if they are not clear for you.
Mnemonic
Code
Message
SC_OK
200
OK
SC_NO_CONTENT
204
No Content
SC_MOVED_PERMANENTLY
301
Moved Permanently

Servlets Advanced

After describing some basic programming of servlets, we will describe some advanced topics of servlets in this tutorial, viz., Session Tracking, Servlet Filters, Servlet Life Cycle Events, Including, forwarding and redirecting, Servlet Chaining and Applet Servlet Communication.

Session Tracking

HTTP is a stateless protocol which means that each request done using HTTP is independent from each other. This is a restriction in HTTP since some applications like e-commerce sites require to hold state information. One of the traditional examples of state is a shopping cart. In this tutorial, we will learn how to hold states between HTTP requests using servlets.
We will specifically use cookies to hold states between servlet requests. Cookie is a file on a web user’s hard disk that is used by web sites to hold information about the web users. So, the idea with cookies is to put state information into cookies and retrieve the information from the cookie in the successive requests.
Working with cookies using servlets is very easy since there is a specific javax.servlet.http.Cookie class in Servlet API. New cookie instances can be created with this class. They can also be added and retrieved easily using methods in HttpServletRequest and HttpServletResponse objects.
SimpleCookieServlet is a servlet which detects whether a web user previously visits itself by using cookies. It simply searches for cookies in the user’s disk. If it can not find the cookie which is added previously, it simply adds a new cookie and prints “This is your first visit.” message. The cookie added contains the last time the user visits the site, so if the servlet finds this cookie it prints “Your last visit to the site was on XXX” message. Here XXX is the time of latest visit of the user. Figure-1 shows the processRequest method of the servlet. We first look for a previously written cookie and print appropriate message. At the last step we are adding a new cookie containing current time.
The source code shown in this section can be found in SimpleCookieServlet project.
Figure-2 shows our first visit to the servlet. Since, there is no cookie yet, the servlet detects that this is our first visits and print appropriate message. Figure-3 shows the behavior of the servlet when we visit it second time. In this case, the servlet detects the cookie added in the previous step and prints the time of the visit.
Figure-1 ProcessRequest method of SimpleCookieServlet servlet
Figure-2 First visit to the SimpleCookieServlet servlet
Figure-3 Second visit to the SimpleCookieServlet servlet

Servlet Filters

Filters are introduced in Servlet specification version 2.3. Filters are used to process the content in request or response objects of servlets and generally do not produce responses themselves.
Let’s create an example for a filter which prints the duration of all requests in our web server into the log file of Tomcat. This is a classical example which also came with Tomcat as an example of filter, but this allows you to understand how servlet filters work.
The source code shown in this section can be found in TimerFilterServlet project.
We need to implement javax.servlet.Filter interface to create a new filter. Filter interface has a doFilter method and the actual work of the filter is done in this method. Figure-4 shows doFilter method implementation of TimerFilter.
Figure-4 doFilter method implementation of TimerFilter
Actual processing of the filtered servlet is done in the line where we call chain.doFilter(request, response) method. This method calls servlet chain to process the request. So, if we want to pre-process the servlet request we do our work before this method and if we want to post-process the servlet response, we do filter code after this method.
Since we need to calculate the time passed for generating actual servlet response, we add our filter code on both sides. We get the current time using System.currentTimeMillis method before and after calling the filter chain and log the difference between those times.

Servlet Life Cycle Events

As you remember from the previous tutorial, the life cycle of event is controlled by the web 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 loads the servletclass, creates an instance of the servlet class and initializes the servlet instanceby calling the init method.
2. Invokes the service method, passing request and response objects.
3. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
The texts with red color are examples of events in servlet life cycle. If you want to react to those events in servlet lifecycle you should create listener objects. The table below shows several types of events and their corresponding listener interfaces needed to implement to catch those events:
Related Object
Events
Listener Interface and event
Web context
Initialization and destruction
javax.servlet.ServletContextListenerjavax.servlet.ServletContextEvent
Web context
Attribute added, removed, or replaced
javax.servlet.ServletContextAttributeListenerjavax.servlet.ServletContextAttributeEvent
Session
Creation, invalidation, activation, passivation, and timeout
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionActivationListener
javax.servlet.http.HttpSessionEvent
Session
Attribute added, removed, or replaced
javax.servlet.http.HttpSessionAttributeListenerjavax.servlet.http.HttpSessionBindingEvent
Request
A servlet request has started being processed by web components
javax.servlet.ServletRequestListenerjavax.servlet.ServletRequestEvent
Request
Attribute added, removed, or replaced
javax.servlet.ServletRequestAttributeListenerjavax.servlet.ServletRequestAttributeEvent

Including, forwarding and redirecting

Including a web resource into your servlet can be very useful. For example, you can have a company logo which should be placed on all web pages. In this case, instead of generating html code for the banner for each servlet, you can create a BannerServlet which produces the html code for the banner and include it into other servlets in your web site.
Including a web resource can be done by obtaining RequestDispatcher object from ServletContext object and then calling include() method of the RequestDispatcherObject. Example code for these operations is written below:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/images/banner.gif");
dispatcher.include(request, response);
As you will notice, the web resource can be any type including a servlet or image.
Forwarding is another useful mechanism. For example, if you want to have a component doing some preliminary works and doing the real job in another component, then the preliminary component can forward the request to the real component when it finished its job.
Forwarding requires obtaining a RequestDispatcher object from ServletContext object for the web resource. Instead of calling include method, we call forward() method in this case. Example code for these operations is written below:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ForwardedServlet ");
dispatcher.forward(request, response);
There are two more methods for redirecting browser to another web resource. The first one is using the header and status elements of HTTP response as shown below:
response.setStatus(response.SC_MOVED_PERMANTLY);
response.setHeader("Location", 
http://www.exforsys.com);
The code above redirects the web browser to Google’s web site. The second method is calling sendRedirect(String url) method of ServletResponse object as shown below:
response.sendRedirect(http://www.exforsys.com);

Servlet Chaining

The mechanism described above can be used as a communication medium between servlets. But, there is one more requirement to handle this communication. We should find a way to pass data between the servlets!
We will use attributes sent by the HttpServletRequest object. The code below shows how to set attributes on the request so that the next servlet can get this information:
RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
req.setAttribute("key1", value1); // This line adds a new attribute
req.setAttribute("key2", value2); // This line adds another attribute
rd.forward(req, resp); // This will redirect request to Servlet3
Next servlet reads the attributes similarly with the following calls:
Object val1 = req.getAttribute("key1");
We will develop a TimedHelloWorldServlet web application in this section to practice on servlet chaining. TimedHelloWorldServlet project has two servlets: TimeServlet and HelloWorldServlet. When TimeServlet is called by the web browser, it puts the current time into request attributes and calls HelloWorldServlet. HelloWorldServlet gets current time from the request attributes and prints a “Hello World” message together with the current time.
The source code shown in this section can be found in TimedHelloWorldServlet project.
Figure-5 shows ProcessRequest method of the TimeServlet servlet. It gets the details of the current time from a Calendar object and puts them into the request as an attribute. After preparing the attributes of the request, it forwards the request to HelloWorldServlet servlet.
Figure-5 processRequest method of TimeServlet
Figure-6 shows ProcessRequest method of the HelloWorldServlet servlet. It gets the details of the current time from the attributes of the request object and prints the current time.
Figure-6 processRequest method of HelloWorldServlet
Final output of TimeServlet is shown in Figure-7. Note that although the url in the address bar of the browser still points to the TimeServlet, the content is produced by HelloWorldServlet.
Figure-7 Output of TimeServlet

Applet Servlet Communication

Although several methods are available to connect servlets with applets, we will select one method in this section and give an example for this type of implementation.
We will print the current time in our applet by obtaining time information from the servlet. So our servlet (namely TimeProviderServlet) will work like a server on our machine and the applet (namely TimeApplet) will connect and get current time from the servlet using object-based HTTP communication. Servlet will send current time by serializing a String object of current time.
The source code shown in this section can be found in AppletServletCommunication project. Note that this project can not be run directly since deployment of Java applets in NetBeans is not done automatically.
Figure-8 shows the source code of TimeProviderServlet servlet.
Figure-9 shows the getTime() method of TimeApplet applet.
Figure-9 TimeApplet source code
Note that double clicking on html file of the applet will not work since the applet and the servlet should reside on the same we server.