Blog is under construction. Blog is under construction.

Me on Flickr

Wednesday, 1 August 2012

Servlets - Advantages of Servlet


Advantages of Servlets
In any J2EE web applications servlets are an integral part. The server side component of a servlets gives a powerful mechanism for developing server side web applications. It provides an important role in the explosion of Internet, its reusability, performance and scalability. Web developers can create fast and efficient server side programs or applications by using servlets. By using servlets web developers can run these applications in any servlet enabled web servers.
The main advantages of using servlets over CGI are, the CGI programs are run outside the web server so a new process should be started before the execution of a CGI programs. At a time the CGI programs handle only one request. After the execution of a CGI program they return the result in the web server and exit. But in the case of servlets it can handle multiple requests simultaneously. Servlets generate dynamic content or create dynamic web pages that is easy to write and faster to run within a web servers. Servlets can access any J2SE and J2EE APIs and it can take the full advantage and capabilities of the java programming language. Servlets are component based, platform independent method for create in the web based applications, without the performance limitations of CGI programs.
The advantages of servlets are discussed below.
1)      Portability
2)      Powerful
3)      Efficiency
4)      Safety
5)      Integration
6)      Extensibility
7)      Inexpensive
8)      Secure
9)      Performance
Portability
Servlets are highly portable crosswise operating systems and server implementations because the servlets are written in java and follow well known standardized APIs. Servlets are writing once, run anywhere (WORA) program, because we can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet simply on any other operating system like Unix. Servlets are extremely portable so we can run in any platform. So we can call servlets are platform independent one. Servlets are written entirely in java.
Powerful
We can handle several things with the servlets which were difficult or sometimes impossible to do with CGI. For example the CGI programs can’t talk directly to the web server but the servlets can directly talk to the web server.  Servlets can share data among each other, they make the database connection pools easy to implement. By using the session tracking mechanism servlets can maintain the session which helps them to maintain information from request to request. Servlets can do many things which are difficult to implement in the CGI programs.
Efficiency
The servlets invocation is highly efficient as compared to CGI programs. The servlet remains in the server’s memory as a single object instance, when the servlet get loaded in the server. The servlets are highly scalable because multiple concurrent requests are handled by separate threads. That is we can handle N number of threads by using a single servlet class
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. In java automatic garbage collection mechanism and a lack of pointers protect the servlets from memory management problems. In servlets we can easily handle the errors due to the exception handling mechanism. If any exception occurs then it will throw an exception by using the throw statement.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets. Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets take all these advantages and can be extended from existing class to provide the ideal solutions. So servlets are more extensible and reliable.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.
Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.

Performance
Servlets are faster than CGI programs because each scripts in CGI produces a new process and these processes takes a lot of time for execution. But in case of servlets it creates only new thread. Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request.




Differences between CGI and Servlet:

  

Servlets - What is Servlet?


What is Java Servlet?
Servlet is a Java-based server-side web technology. As the name implies, it serves a client request and receives a response from the server.
Technically speaking, a Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. They are not tied to a specific client-server protocol, but are most often used with the HTTP protocol. Therefore, the word "Servlet" is often used in the meaning of "HTTP Servlet". Thus, a software developer may use a servlet to add dynamic content to a Web server using the Java platform.
Servlet is a server-side programming language that is used to create the dynamic web page. Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.
Servlet can be described in many ways, depending on the context.
·         Servlet is a technology i.e. used to create web application.
·         Servlet is an API that provides many interfaces and classes including documentations.
·         Servlet is an interface that must be implemented for creating any servlet.
·         Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
·         Servlet is a web component that is deployed on the server to create dynamic web page.




To deploy and run a Servlet, a Web container must be used. A Web container (also known as a Servlet container) is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.
The servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the Web container and a servlet.
A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application.
Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.

Monday, 30 July 2012

Difference between JRE, JVM and JDK?


Difference between JRE, JVM and JDK:

JRE, JVM and JDK are three terms you often heard in conjunction with Java programming language and most people either confuse between them or think they all are same. In this java article we will what is Java Run-time (JRE), what is Java virtual Machine (JVM) and what is Java development Kit (JDK) along withJust in Time compiler or JIT. Once you know what JRE, JVM or JDK means you can differentiate them easily by yourself

JRE JVM and JDK in Java Programming language

Java Runtime Environment (JRE)

Java is everywhere in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it. Now JVM is an executable or program like any other program and you can install that into your machine. You have seen browser often suggesting download JRE to run a Java Applet downloaded from Internet. Various version of JRE are available in java.oracle.com and most of the user who just want to execute Java program inside browser or standalone downloads JRE. All browsers including Internet Explorer, Firefox and Chrome can work with JRE.

Java Virtual Machine (JVM)

When you download JRE and install on your machine you got all the code required to create JVM. Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code and that's why you have different JVM for Windows, Linux or Solaris but one JAR can run on all this operating system. Java Virtual machine is at heart of Java programming language and provide several feature to Java programmer including Memory Management and Garbage Collection, Security and other system level services. Java Virtual Machine can be customized e.g we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation. If we supplied invalid argument to java command it may refuse to create Java Virtual Machine by saying "failed to create Java virtual machine: invalid argument". In short Java Virtual Machine or JVM is the one who provides Platform independence to Java.

Java Development Kit (JDK)

JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program. Just like JRE, JDK is also platform specific and you need to use separate installer for installing JDK on Linux and Windows. Current Version of JDK is 1.7 which is also referred as Java7 and it contains javac (java compiler) based on programming rules of Java7 and Java which can execute java7 code with new features like String in Switch, fork-join framework or Automatic Resource Management. When you install JDK, installation folder is often referred as JAVA_HOME. All binaries are located inside JAVA_HOME/bin which includes javac, java and other binaries and they must be in your system PATH in order to compile and execute Java programs. For details on Path see how to set PATH for Java in Windows and UNIX.

Difference between JRE, JDK and JVM

In short here are few differences between JRE, JDK and JVM:

1)  JRE and JDK come as installer while JVM are bundled with them.
2)  JRE only contain environment to execute java program but doesn’t contain other tool for compiling java program.
3)  JVM comes along with both JDK and JRE and created when you execute Java program by giving “java” command.

Just in Time Compiler (JIT)

Initially Java has been accused of poor performance because it’s both compiles and interpret instruction. Since compilation or Java file to class file is independent of execution of Java program do not confuse. Here compilation word is used for byte code to machine instruction translation. JIT are advanced part of Java Virtual machine which optimize byte code to machine instruction conversion part by compiling similar byte codes at same time and thus reducing overall execution time. JIT is part of Java Virtual Machine and also performs several other optimizations such as in-lining function.

That’s all on JRE, JDK and Java Virtual machine and difference between them. Though they look similar they are different and having a clear idea of JVM, JIT or JDK helps in java programming.


How the Java Virtual Machine (JVM) Works?

How the Java Virtual Machine (JVM) Works?


The Java virtual machine is called "virtual" because it is an abstract computer defined by a specification. To run a Java program, you need a concrete implementation of the abstract specification. This chapter describes primarily the abstract specification of the Java virtual machine. To illustrate the abstract definition of certain features, however, this chapter also discusses various ways in which those features could be implemented.


What is a Java Virtual Machine?
To understand the Java virtual machine you must first be aware that you may be talking about any of three different things when you say "Java virtual machine." You may be speaking of:
  • the abstract specification,
  • a concrete implementation, or
  • a runtime instance.
The abstract specification is a concept, described in detail in the book: The Java Virtual Machine Specification, by Tim Lindholm and Frank Yellin. Concrete implementations, which exist on many platforms and come from many vendors, are either all software or a combination of hardware and software. A runtime instance hosts a single running Java application.
Each Java application runs inside a runtime instance of some concrete implementation of the abstract specification of the Java virtual machine. In this book, the term "Java virtual machine" is used in all three of these senses. Where the intended sense is not clear from the context, one of the terms "specification," "implementation," or "instance" is added to the term "Java virtual machine".



The Architecture of the Java Virtual Machine



1.            The first component of JVM architecture is "class loader" used to load the .class files.
2.            Class Loader object loads user defined .class files from the given userdefined package or from current package by default where as ' boot strap class loader' loads .class files from Java API at runtime.
3.            The loaded .class files is forwarded to 'execution engine'.
4.            'Execution Engine' translates .class files byte code to platform native code and it calls the native functions using native callable statements.
5.            Execution engine contains 2 components. (i) JVM (Interpreter) (ii) JIT(Just In Time)Compiler
6.            JDK contains JVM by default where as web browsers contain JIT. JIT compiles all components at a time. It improves performance. JIT is needed to display downloaded applet file at client browser.
7.            The code which is written in other languages is known as native code(.dll, .cab) to Java. Native code is processed by native translator of JVM.
8.            JVM allocates memory for Java Datatypes at runtime not at compilation time. JVM needs memory to allocate. JVM needs 2MB to 64MB initial memory to execute an application.
9.            Memory is divided into five data areas like Stack Area, Heap Area, Method Area, Register Area and Stackpool Area.

For more information on JVM: 

Watch Video about JVM:



How to write a simple Java Program?



Java HelloWorld Program



In this page, you will learn how to write a Java program
hello world java program :- Java code to print "Hello World".
Open Notepad and type as below:

Java source code

public class HelloWorld
{
   public static void main(String args[])
   {
      System.out.println("Hello World");
   }
}

Save this file as HelloWorld.java
To compile: javac HelloWorld.java

To execute: java HelloWorld


Output:
Hello World

What happens at Compile Time?



To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code. 
The output from a Java compiler comes in the form of Java class files (with .class extension). The java source code contained in files end with the .java extension. The file name must be the same as the class name, as classname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension.
Following figure shows the working of the Java compiler:



Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine.

At Compile Time, Java file is compiled by Java Compiler (it does not interact with OS) and converts the Java code into Byte code (Which is nothing but .class file)
.

What happens at Run time?

At Run time, following steps are performed



Classloader:  is the Sub system of JVM that is used to load class files.
Bytecode Verifier: Checks the code fragments for illegal code
Interpreter:  read bytecode stream then execute the instructions

How to Set Path and Classpath for Java on Unix, Linux and Windows?


How to Set Path and Classpath for Java on Unix, Linux and Windows?



PATH is one of fundamental Environment variable on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program which doesn't include Java executable in PATH then we say PATH is not set for Java and we need to set path for Java. I have also seen developer getting confused over path and classpath in java. Though both path and classpath provides run-time settings for any java environment which is required to compile and execute Java program they are completely different to each other.
Classpath is usually used to find out classes and mostly associated with lib part while PATH is used to find the executable or command to be executed. In order to compile and run java program from command line your PATH environment variable must have "javac" and "java" on it. In this Java PATH tutorial we will see what is PATH for Java, How to Set Path for Java and how to troubleshoot PATH related issues.
What is Path in Java
First of all PATH is not specific to java it’s a shell concept and also available in Windows and DOS. It’s represented by Environment variable called "PATH" and that's why it’s known as path. Whenever you type a command in shell in UNIX or Linux or in command prompt in windows machine, command will be looked on PATH and if shell is not able to find the command in PATH it says "not recognized" or wrong command. Now for compiling and running we use two java commands "javac" and "java" and these commands doesn't come by default with windows or Unix instead they comes when you install JDK in your machine. Now to successfully compile and run a java program in either windows or Linux you must have these two commands or executable in your PATH environment variable and that is called Setting Path for Java.

Setting Path for Java in Unix/Linux and Windows
How to check if "java" or "javac" is in PATH
Javac and Java command resides under /bin directory or your Java installation directory. In my machine its "C:\Program Files\Java\jdk1.6.0_26\bin"

If you have this bin directory in path it means java and javac will be in path and Path is set to run Java Program. There are two ways you verify whether java is in path or not.
1) Simple and easy way
Open a command prompt window by pressing start -->run-->cmd and then typing "java" or "javac" in command prompt as shown in below example
C:\Documents and Settings>java
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -client       to select the "client" VM
    -server       to select the "server" VM
    -hotspot      is a synonym for the "client" VM [deprecated]



If it displays lot of output means Java is in your path and similarly you can check for "javac”, on the other hand if java is not in your system's path you will get below output in UNIX
stock_trader$ javac
javac: not found
and in windows
C:\Documents and Settings>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
If java or javac is not in your path then you can add them into path by adding "bin" directory or your JDK installation directory into environment variable "PATH". Both windows and UNIX use same name.
How to set PATH for Java in windows
I say pretty easy just add bin directory of your JDK installation directory into PATH environment variable. You can do this either from command prompt or by using windows advanced environment editor
1) Setting Java PATH using command prompt in windows

Use "set" command to set value of PATH environment variable as shown in below example:

C:\Documents and Settings>set PATH=%PATH%;
C:\Program Files\Java\jdk1.6.0_26\bin

%PATH% is actually representing current path and we are appending java bin directory into PATH. Note that every path in windows is comma (;) separated while in UNIX it would be colon (:) separated

2) Setting Java PATH using windows environment variable editor
Use short cut "window key + pause/break" --> Advanced --> Environment Variables -->PATH
Just append the path of java installation directory here and you are done. Open a command prompt and type java or javac and you can see the output.
How to set Java PATH in UNIX or Linux
Setting PATH for java in UNIX is similar to the way we did for it on windows using command prompt. In UNIX just open any shell and execute below command
set PATH=${PATH}:/home/opt/jdk1.6.0_26/bin
Remember here each element in PATH is colon separated.

CLASSPATH in Java
I have experience in finance and insurance domain and Java is heavily used in this domain for writing sophisticated Equity, Fixed income trading applications. Most of these investment banks have written test for Java and I always fine at least one question related to CLASSPATH in Java on those interview. Java CLASSPATH is one of the most important concepts in java but I must say mostly overlooked. This should be the first thing you should learn while writing java programs because without understanding of Classpath in Java you can't understand how java locates your class files.

So let’s start with basic and then we will see some example and improvisation of Classpath in Java. In Fact CLASSPATH is an environment variable which is used by Java Virtual Machine to locate user defined classes. 

Setting Java Classpath in Windows
For setting Java Classpath in Windows (any version either Windows XP or Windows 2000) you need to specify value of environment variable CLASSPATH, name of this variable is not case sensitive and it doesn’t matter if name of your environment variable is Classpath, CLASSPATH or classpath in Java.

Here is Step by Step guide for setting Java Classpath in Windows:


  1. Go to Environment variable window in Windows by pressing "Windows + Pause “-->Advanced -->Environment variable " or you can go from right click on my computer than choosing properties and then Advanced and then Environment variable this will open Environment variable window in windows.
  2. Now specify your environment variable CLASSPATH and put the value of your JAVA_HOME\lib and also include current directory by including (dot or period sign).
  3. Now to check the value of Java classpath in windows type "echo %CLASSPATH" in your DOS command prompt and it will show you the value of directory which are included in CLASSPATH
Setting Java Classpath in UNIX or Linux
To set Classpath for Java In Linux you can simply export CLASSPATH="your classpath" from either your .bash_profile or .bashrc script which will run whenever you login into your Linux or Unix Machine.
Now to check value of Java CLASSPATH in Linux type "echo ${CLASSPATH}. 
I hope this example for setting classpath in Java will enable to set classpath by yourself let me know if you face any problem while setting up classpath in Java

Overriding Classpath in Java
You can override value of Java classpath defined by environment variable CLASSPATH by providing option "-cp" or "-classpath" while running your program and this is the best way to have different classpath for different application in Java. General way to define classpath is in the startup script of any program. e.g.
CLASSPATH=/home/tester/classes
java -cp $CLASSPATH Test

By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.

Different example of using Classpath in Java
In case you have multiple directories defined in CLASSPATH variable, java will look for a class starting from first directory and only look second directory in case it did not find the specified class in first directory. This is extremely useful feature of Classpath in java to understand and it’s very useful for patch release kind of stuff. Let’s see  java -classpath example

I have my CLASSPATH=/home/tester/first:/home/tester/second
Now I have "Test" class of different version in both first and second directory so when I give a command
"java Test" What will happen ? Which Test class would be picked?
Since JVM search directory in the order they have listed in CLASSPATH variable it will first go to the "first" directory and if it finds "Test" over there it will not go to "/home/tester/second" directory.
Now if you delete Test class from /home/tester/first directory it will go to /home/tester/second directory and will pick "Test" class from there.

I have used this feature of Java Classpath to test my patch releases, we used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of time we want to put any debug statement or want to test any bug we just modify Java source file , compile it and generate class file and put that inside patch folder instead of releasing whole new jar and this comes very handy if you are working in a large project where you don't have development environment setup in Windows and your project only runs on Unix server.
Its also worth noting that when you use the -jar command line  option to run your program as an executable JAR, then the CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored. 

In this case you can set your Java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute.
Now a common question if I have my CLASSPATH variable pointing to current directory "." and I have class called "Test" inside package "testing" and with below directory structure C:\project\testing\Test.class in my computer.
What will happen if I run command "java Test" from directory "C:\project\testing\" will it run?
No it will not run it will give you Exception in thread "main" java.lang.NoClassDefFoundError: Test
Since name of the class is not Test, instead it’s testing. Test even though your classpath is set to current directory.

Now what will happen if I give command “java testing.Test “from” C:\project\testing\, it will again not run and give error?

Exception in thread "main" java.lang.NoClassDefFoundError: testing/Test
Why because now it looking for class called Test which is in package testing, starting from current directory "." but don't find it since there is no directory called "testing after this path "C:\project\testing\".

To run it successfully you need to go back to directory "C:\project" and now run 
C:\project>java testing.Test 
It will run successfully.

Errors related to Classpath in Java

If you are working in Java you must have faced some errors and exception related to classpath in java, two most common issues related to java classpath is ClassNotFoundException and NoClassDefFoundError. I have seen that most of java developer tries to solve this error by trial and error; they just don’t look beyond the hood and try to understand what the reason for these java classpath related errors is. They often misunderstood that these two errors are same also. 

Here is the reason of these java classpath errors: 

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a particular Class at Runtime and don’t find that on Java classpath. Two keyword here “dynamically” and “runtime”. Classic example of these errors is when you try to load JDBC driver by using Class.forname(“driver name”). So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.

On the other hand NoClassDefFoundError is an Error and more critical than ClassNotFoundException which is an exception and recoverable. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on classpath in java during run-time. Keyword here is “class present at compile time but not available on run-time”. This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java.












                                                                                                                                                                                                               



Related Posts Plugin for WordPress, Blogger...