Tuesday, 30 December 2014

Father of Java James Gosling Joins Google

Father of Java James Gosling Joins Google



 Gosling is formerly of Sun Microsystems, though he left the company after their acquisition by Oracle, the company currently suing Google over claims of stolen code within the Android source. He said it was apparent from early stages of the merger that Oracle wanted to pursue legal action against Google, but for this and other reasons he parted ways with the software company. That is not to say he hasn’t had a few words to say of Google in the past. Speaking about Android, Gosling once said the OS “has pretty much played out the way that we feared: there is enough fragmentation among Android handsets to significantly restrict the freedom of software developers.”


Read Full
http://www.beingjavaguys.com/p/core-java-tutorials.html
Read Full

How to override equals() in Java - Example

How to override equals() in Java - Example

In our previous discussions we came across a quick introduction to Java’s Collection API and Implementation classes for List, Set and Map interface. In this particular blog we will discuss about a very useful topic i.e. "Why to override equals() in Java" and "How to override equals in Java".

We all know it very well that all classes in Java are descendent of Object class, or we can say every class inherits the methods and properties of Object class by default. There are a number of methods in Object class and hence is "public boolean equals(){}".

The public boolean equals(){}, compares two objects and return true or false accordingly. If we don’t override equals in our own class than one present in Object class is called and it compares the object using ‘==’ operator and hence two objects are equal only if their references are same.

Assume we have an class Apple, lets compare its objects using equals() and examine the result.
  1. class Apple {  
  2.   
  3.  private int id;  
  4.  private String name;  
  5.   
  6.  public Apple() {  
  7.  }  
  8.   
  9.  public Apple(int id, String name) {  
  10.   this.id = id;  
  11.   this.name = name;  
  12.  }  
  13.   
  14.  public int getId() {  
  15.   return id;  
  16.  }  
  17.   
  18.  public void setId(int id) {  
  19.   this.id = id;  
  20.  }  
  21.   
  22.  public String getName() {  
  23.   return name;  
  24.  }  
  25.   
  26.  public void setName(String name) {  
  27.   this.name = name;  
  28.  }  
  29. }  


No lets see what happened when we call an equals() method from Object class itself without overriding it.
  1. public class Implementation {  
  2.  public static void main(String args[]) {  
  3.   Apple greenApple = new Apple(1"Apple");  
  4.   Apple redApple = new Apple(1"Apple");  
  5.   
  6.   // returns a false  
  7.   System.out.println(greenApple.equals(redApple));  
  8.  }  
  9. }  
In the example above we can see that even if two instance of Apple are having same data in them but the equals() method from Object class is assuming them to be non equal. The reason is the default implementation of equals() check for references and two objects are same only if their reference is same. And certainly you would not want this kind of behavior in your application, hence we override equals.
Note: Two String object with same values returns true on equals() even if having different references, the reason is String itself override equals() and implement the functionally so that the String content to compare not their references. Hence we can do it in our very own class.

We can override equals() in our own class and give that our own implementation to compare objects considering some contract. The meaning of contract here is that when overriding equals() we must took care of certain rules and those rules should not violate.

If an class “Apple” has three instances “greenApple” , “redApple” and “yellowApple” than according to contract

1) greenApple.equals(greenApple) must be true always. Reflexive

2) If greenApple.equals(redApple) is true than redApple.equals(greenApple) must be true. Symmetric

3) If greenApple.equals(redApple) is true and redApple.equals(yellowApple) is also true than greenApple.equals(yellowApple) must be true. Transitive

4) For any two refrences say “redApple” and “yellowApple” the equals() method must return true or false consistently unill and unless the property of class that is used is equals() is not modified. Consistent

5) For any non-null reference value greenApple, greenApple.equals(null) should return false. Null Test



Lets now look at our modified version of Apple with an override equals() method.
  1. class Apple {  
  2.   
  3.  private int id;  
  4.  private String name;  
  5.   
  6.  public Apple() {  
  7.  }  
  8.   
  9.  public Apple(int id, String name) {  
  10.   this.id = id;  
  11.   this.name = name;  
  12.  }  
  13.   
  14.  /* 
  15.   * One can use his own logic here unless the contract is being followed. 
  16.   */  
  17.  public boolean equals(Object o) {  
  18.   if (o instanceof Apple && ((Apple) o).getName() == name  
  19.     && ((Apple) o).getId() == id)  
  20.    return true;  
  21.   else  
  22.    return false;  
  23.  }  
  24.   
  25.  public int getId() {  
  26.   return id;  
  27.  }  
  28.   
  29.  public void setId(int id) {  
  30.   this.id = id;  
  31.  }  
  32.   
  33.  public String getName() {  
  34.   return name;  
  35.  }  
  36.   
  37.  public void setName(String name) {  
  38.   this.name = name;  
  39.  }  
  40. }  


Now let’s check if we did it right and does not violate the contract.
  1. public class Implementation {  
  2.  public static void main(String args[]) {  
  3.   Apple greenApple = new Apple(1"Apple");  
  4.   Apple redApple = new Apple(1"Apple");  
  5.   Apple yellowApple = new Apple(1"Apple");  
  6.   
  7.   // Reflexive Test : true  
  8.   System.out.println("Reflexive Test : " + greenApple.equals(greenApple));  
  9.   
  10.   // Symmetric Test : true  
  11.   if (greenApple.equals(redApple)) {  
  12.    System.out.println("Symmetric Test : "  
  13.      + redApple.equals(greenApple));  
  14.   }  
  15.   
  16.   // Transitive Test : true  
  17.   if (greenApple.equals(redApple) && redApple.equals(yellowApple)) {  
  18.    System.out.println("Transitive Test : "  
  19.      + yellowApple.equals(greenApple));  
  20.   }  
  21.   
  22.   // Null Test : false  
  23.   if (greenApple != null) {  
  24.    System.out.println("Null Test : " + greenApple.equals(null));  
  25.   
  26.   }  
  27.  }  
  28. }  


And we are getting the expected result that passes the equals() override contract. Now the conclusion of the whole story is that:

1) The public boolean equals(){} is a method that resides in Object class and hence can be overridden in our own classes as well.

2) If one does not override it than the default behavior is being calles i.e. two objects are equal only if their references are same.

3) We can override equals() in our own class and can give own implementation to compare two objects until and unless we are not violating the equals() contract.

Big Big NOTE: If you override equals() in your own class than you must override hashCode() as well, unless it can violate hashCode() contract with equals() that results in Hash Based collections functionality and implementation.


In this particular blog we came across "why to override equals() in Java" and "How to override equals in Java". In our upcoming blog we will come across "how to override hashCode() in Java" and other tips and tricks about Java.








Thanks for reading !
Read Full

How to make a class Immutable in Java - Example & Explanation

How to make a class Immutable in Java - Example & Explanation

What is immutable class in Java? And How to make a class immutable in java? Are two very popular and hot topics as if today. In this particular blog we will look into these two in details and will try to understand benefits if immutable classes in context of Java Language.


What is Immutable class in Java ?

In Java an immutable class is a class whose object’s state can not be changes once created, or any modification on immutable object’s results in another immutable object. Even JDK itself contains a number of immutable classes like String, Float and other wrapper classes. To understand immutable class clearly we can take a simple example of String and StringBuffer classes, any modification on String object i.e. substring, concat ..etc results in a new immutable object while operations performed on StringBuffer class does not create a new object instead modifications are refleted on exiting object only.


How to make a class immutable in Java ?

Let us now discuss how to make a class immutable, there are a number of ways to get an immutable class. Even Java Documentation points out certain guidelines on the same, which we will follow here to get an immutable class.

1) Never provide a setter method for the class, setter methods are used to change the state of a class’s members. This is what we want to prevent here.

2) Make all fields private and final, this will make them non accesable outside the class and their values can not be changed because of being final.

3) Make the class final, so that the class can not be subclassed. This will prevent the class’s methods from overriden.

4) Special attention needs to be applied with mutable reference variables, with reference variables even final can not prevent their value to be changed. The simplest way to prevent reference variables’s vales is to not provide actual object and provide a copy of them.

5) Make the default constructor of the class private and provide instances with a factory method.

  1. package com.beingjavaguys.com;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  * @Author Nagesh Chauhan 
  7.  */  
  8. /* Making class final, prevents it's methods from overriden in subclasses */  
  9. public final class IAmImmutable {  
  10.   
  11.  private Integer id;  
  12.  private String name;  
  13.  private Date currentDate;  
  14.   
  15.  /* 
  16.   * private constructor ensured no unwanted object creation 
  17.   */  
  18.  private IAmImmutable(Integer id, String name, Date currentDate) {  
  19.   this.id = id;  
  20.   this.name = name;  
  21.   this.currentDate = currentDate;  
  22.  }  
  23.   
  24.  /* this hold the logic of object creation, only point to get an object */  
  25.  static IAmImmutable getInstance(Integer fld1, String fld2, Date fld3) {  
  26.   return new IAmImmutable(fld1, fld2, fld3);  
  27.  }  
  28.   
  29.  /* Integer is a immutable class, this can be served directly */  
  30.  public Integer getId() {  
  31.   return id;  
  32.  }  
  33.   
  34.  /* String is a immutable class, this can be served directly */  
  35.  public String getName() {  
  36.   return name;  
  37.  }  
  38.   
  39.  /* 
  40.   * Date class is mutable so we don't provide an direct object, instead we 
  41.   * provide a copy of it 
  42.   */  
  43.  public Date getCurrentDate() {  
  44.   return new Date(currentDate.getTime());  
  45.  }  
  46.   
  47. }  


  1. package com.beingjavaguys.com;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class ImmutableDemo {  
  6.   
  7.  /** 
  8.   * @Author Nagesh Chauhan 
  9.   */  
  10.  public static void main(String[] args) {  
  11.   /* 
  12.    * getting an instance of immutable class 
  13.    */  
  14.   IAmImmutable iAmImmutable = IAmImmutable.getInstance(2"Andrew",  
  15.     new Date());  
  16.   System.out.println("Id: " + iAmImmutable.getId() + " Name: "  
  17.     + iAmImmutable.getName() + " Date:"  
  18.     + iAmImmutable.getCurrentDate());  
  19.   
  20.   /* 
  21.    * Try to modify object's states 
  22.    */  
  23.   // iAmImmutable.getId() = 5; not permitted  
  24.   // iAmImmutable.getName() = "Stuart" not permitted  
  25.   iAmImmutable.getCurrentDate().setDate(23);  
  26.   /* 
  27.    * Printing values again to test 
  28.    */  
  29.   System.out.println("Id: " + iAmImmutable.getId() + " Name: "  
  30.     + iAmImmutable.getName() + " Date:"  
  31.     + iAmImmutable.getCurrentDate());  
  32.  }  
  33.   
  34. }  


Benefits of making a class Immutable

1) Thread-safe hence can be used in concurrent environment without synchronization.
2) Immutable objcts can be used to boost memory, we can simply save them and serve again and again.


That’s all about immutable classes and objects in java, we cam across what is immutablity ? What are immutable classes in Java ?, How to create a class immutable in Java ? and benefits of immutable classes in Java. In upcoming blogs we will see more about Java and Other opensource technologies.








Thanks for reading !
Read Full

Create a Java Project in Maven and import it in Eclipse IDE

Create a Java Project in Maven and import it in Eclipse IDE

In this particular blog we will discuss ‘How to create a Java Project in Maven’, ‘Import maven java project in eclipse ’. and ‘create a jar from java maven project’.

Before we start lets make sure you have a working Maven Package and Java installation in your machine. To make sure if you have Java installed in your system supply following command:





To make sure you have a correctly configured Maven package supply following command.





Create Java project in Maven

To create a java project in maven open your command prompt and navigate to the folder where you want to create the project. Now supply following command.

C:\Users\nagesh.chauhan>cd maven-project
C:\Users\nagesh.chauhan\maven-project>mvn archetype:generate -DgroupId=com.beingjavaguys.java -DartifactId=SimpleJavaProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


You will see a screen creating Maven a specified Java Project for you.



Make Maven – Jave project to work with Eclipse IDE

Here we are done with creating a Java Project in Maven, now lets make it working with eclipse IDE. Now to convert this maven-java project to work with Eclipse IDE navigate to the parent directory of your project and supply following command.

C:\Users\nagesh.chauhan>mvn eclipse:eclipse




Now import the converted project in your Eclipse IDE, the project structure in Eclipse will look like the image shown below:



Create a jar file from maven-java project in Eclipse

Now lets see how to create a jar from java-maven project, update your pom.xml a little bit to make it package your java application.

SimpleJavaProject\pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.  <modelVersion>4.0.0</modelVersion>  
  4.  <groupId>com.beingjavaguys.java</groupId>  
  5.  <artifactId>SimpleJavaProject</artifactId>  
  6.  <packaging>jar</packaging>  
  7.  <version>1.0-SNAPSHOT</version>  
  8.  <name>SimpleJavaProject</name>  
  9.  <url>http://maven.apache.org</url>  
  10.  <dependencies>  
  11.   <dependency>  
  12.    <groupId>junit</groupId>  
  13.    <artifactId>junit</artifactId>  
  14.    <version>4.11</version>  
  15.    <scope>test</scope>  
  16.   </dependency>  
  17.  </dependencies>  
  18.   
  19.  <build>  
  20.   <plugins>  
  21.    <plugin>  
  22.     <groupId>org.apache.maven.plugins</groupId>  
  23.     <artifactId>maven-compiler-plugin</artifactId>  
  24.     <version>2.3.2</version>  
  25.     <configuration>  
  26.      <source>1.6</source>  
  27.      <target>1.6</target>  
  28.     </configuration>  
  29.    </plugin>  
  30.   </plugins>  
  31.  </build>  
  32.   
  33. </project>  

Now navigate to your project parent directory and supply following command.

C:\Users\nagesh.chauhan\maven-project\SimpleJavaProject>mvn install -Dmaven.test.skip=true

We have skipped all junit classes from packaging because those are not configured yet. You will get following output screen showing packaging process.


Now go to your Eclipse IDE and expand target folder, you will get your generated jar file there as shown in following figure.


Run the java project from eclipse IDE and you will see the output like :



In this particular blog we came across ‘How to create a Java Project in Maven’, ‘Import maven java project in eclipse ’. and ‘create a jar from java maven project’. In upcoming blogs we will see more about 'Maven', 'Spring', 'Java' and other opensource technologies.






Thanks for reading
Read Full

Java - Introduction and Overview of Language

Java - Introduction and Overview of Language

This is the very first part of our 'Core Java programming tutorials' series. Today we will cover a quick overview of Java History, its properties and a quick introduction to overall language structure.

Java is a High Level computer programming language that was initially invented by James Gosling. In June 1991 James introduces Java with an initial name ‘oak’, the purpose behind ‘Oak’ invention  was to implement an virtual machine with an language much familier with c/c++ but a simple way of understanding and implementation.





Quick History

The very first public implementation came in 1995 i.e. Java 1.0. The tagline behind the launch was ‘Write once and Run everywhere’. The release was platform independent and quit secure and configurable.

As the time passes Java got popular and it was assumed as the best programming language for web programming. In November 2006 Sun launches Java as open source project under GNU General Public License. Sun introduces Java 2 with a better and advanced security configurations and broken the launch in three main subsidiaries, J2SE, J2ME and J2EE.


Java Properties

1) Platform Independent

Java is most known for it Platform Independent nature, one can write a program in any environment and that can be run on a variety of Hardware and Platforms. Java is compiled and run within JDK(Java Development Kit). JDK includes JRE(Java Runtime Environment) in it. JRE is what makes java program run, this JRE can be different for different platforms but java code will run on each JRE..

2) Object Oriented

Java is fully object oriented or not, it is still a debate among programmers and communities. In java everything is an object except that of Primitive Types(int, char…) so this can be assumed that java is not a pure object oriented language, On the other hand Java supports Wrapper classes (Integer, Float …), so all primitive types can be represented as objects using wrapper classes, this is also true that java is an pure object oriented language.

3) Secure

Java is well known for its security features, java implements security API’s that makes is fully secured programming language. Java security API covers Platform security, Cryptography, Public key infrastructure, Authentication and Access Control that provides the programmers a secured framework to develop applications.

4) Simple

Java was intended to build a simple programming language with much similar that C/C++ syntax and functionality.  Java is a easy to learn and implement programming language with a clear understanding of its useful features. One can be a master in java with a quick understanding of its basic syntax and data flow across the applications.

5) Portable

Portability is again a big concern in Java popularity and wide usage. Being platform independent and architecture neutral makes java a efficient and idle language in portability aspects.

6) Robust

JVM is the root of Java, JVM is said to be the best virtual machine made till data. JVM enables a strong debugging and compilation capabilities that makes Java a error free and easy to detect errors mechanism implementation. Java is very strong in its robust part by providing a efficient mechanism against error detection at compile time and run time.

7) Architectural Neutral

Java compilation is a two step process, all java codes are converted to byte codes first. This makes java to run everywhere and architecturally neutral programming language.

8) Multithreaded

Java supports a fully integrated multithreaded environment, this feature makes the developers to utilize bandwidth and reduce idle cpu time. Multithreading makes it easy to divide the task in multiple parts to make the application more productive and safe to develop.

9) Distributed

Java support distribution of its code across the internet, its platform independent nature and byte code make it easy to distribute easily.

10) Dynamic

Java is being called more dynamic than c/c++, the reason behind its strong dynamic support is the capabilities of run time implementation and easy to adopt dynamic features.


Development Environment

A java program can be written on a simple text editor with a .java file extension. A .class file is generated after compilation that is nothing but a byte code file. This .class file is than run on JVM to see the expected output.

Being a very popular and widely used programming language Java enables a wide range of development capabilities. To start programming in java one need to install a JDK package on the machine and that’s it, JDK comes with a Java compiler, debugger and JVM to run and deploy java applications on.

Till date a number of Development IDE’s are available for java, Eclipse and Netbeans are most popular and widely used IDE’s for Java as of today.


Programming Syntax of Java

Java is based on c/c++ languages as in syntax perspective, Java’s syntax is easy and easy to learn. In java everything is written inside classes and that methods are declared to complete the tasks. In java everything is based on objects. More detailed overview of Java syntax will be covered in Simple Hello World in java section.


Install Java and Environment Settings

Start programming with java is simple, just install a JDK from a variety of providers and set JAVA_HOME path. More details can be get from Install Java and Set Environment section.


In this particular blog we came across a quick introduction of Java programming language and its properties. In upcoming tutorials we will cover Set Java Development environment , Start programming in Java and step by step introduction to all basic concepts of Java programming language.










Thanks for reading !
Read Full

Jsp and Servlet Tutorials - Request-Response Model (Part 1 of 8)

Jsp and Servlet Tutorials - Request-Response Model (Part 1 of 8)

Today we are living in an era where java is being used at its best, we have very efficient frameworks and tools to make web development easy and stable. To make software development more useful and productive its important to implement industry best practices and clean coding implementations. Good naming conventions and easy to implement algorithms is not enough to make smart development done. 
No matters how improved frameworks and techniques we are using in our development process the key feature to write smart code is always stick to basics.

There is no doubt that a lot of effort and experience is behind today's java web frameworks and these stuffs has been made web development very flexible and advanced, but we must not forget about those old but gold concepts so called jsp and servlets. Whenever there is something related to web development in java the first thing that comes in our mind is servlets and jsp's. So its never wrong to say that a good java developer must have a very good command on basics of servlet and jsp's.     

In this series of jsp-servlet tutorials we are going to talk about servlet ans jsp's to make you guys understand the basics of what web development is all about. In today's discussion lets starts with an introductory part of Servlets. By the end of this tutorial we will be able to understand things like : What is a Request ?, What is a Response and What is Request-Response model exactly.

Although this series of jsp-servlet tutorials is written for extremely start level readers, but we assumes that you guys have a little knowledge of oops concepts and java language in general. First of all lets starts with a quick and brief introduction to data flow model of web to better understand the things that are exactly happening behind the screen.

Request-response model

jsp-servlet-tutorials

Whenever a software guy enters in web development world the first thing that he comes to know is, client and server, client makes an request and server sends a response back to client. So let's first discuss how basically communication takes place in web world and what exactly the terms client and server means.

Client: A client in basically something(web browser) or someone(user) who requests some resource from server.

Server: A server is a combination of a hardware machines and a number of softwares running on that machine. The one and only duty of server is to serve resources that are being requested by the client.

Servers itself are capable of serving static resources only. To serve a dynamic response servers needs some extra technologies like servlets running on them. 
How servlets helps server in serving dynamic contents, we will come to know about it in later part of this blog.
Now to get client and server in contact and make communication possible we needs some set of rules so called http(Hyper text transfer protocol). In web there are a number of protocols other than http that does the communication work done, but almost in 99% of applications the requests being made are http requests.

Http: Http can be assumed as a common interface of interaction that both client and server understands.

Request/Response circle
 
Web flow starts from a request being made by user's browser, the request is made as http request so that server can understand it. Based on request the server searches for an appropriate resource and sends it back to client in form of http response.

Http Request: A http request basically have three major components.
1 - HTTP method, there are 7 methods defined in java servlets but most of the time you will see either a get or post method. We will get to know about these methods and their usage in later part of this blog.
2 - The requesed page URL, the page to access like www.google.com.
3 - Parameters, parameters(as id, name, email.. etc.) are being send as part of request on which the response is being generated.

Http Response: A http request basically have three major components.
1 - A status code, this code tells the browser wheather the request is successfull or not.
2 - Content type, it tells the browser about the type of content that response web page contains in it (text, picture, html...etc).
3 - The content, the important and last information that is the served resource that the user was requested.

Till now we are much famelier with the request-response cycle and client-server model over the web. Now the next things that would be coming in your mind is "Where does the Servlet comes into the picture". As we said before that the server can serve static pages or response by itself. In case we need to serve some dynamic pages the served must have something that provides dynamic contents to serve. And this is what servlets does exactly.
Servlets are nothing but helper applications that helps the server to response back dynamic pages. How servlets prepares dynamic response and what exactly happened in the process we will come to know about this thing in a moment, be cool.

A static resource is a page whose contents are static in nature as a simple text file, on the other hand dynamic pages are being prepared according to user's request parameters.

For example lets assume a user requests a page having some text information written on some topic. This page content is never going to change and the same page is sended back to every user request.
But if a user requests something like profile information of his own account this time server needs to create a page of that user's information based on id or username the user provided. This page is going to contain different profile information for different users. These username, email are called parameters and the response id being generated dynamically based on user's request parameter. These are called dynamic pages.

The existence of servlets came into picture because, most of the time client needs dynamic contents and not static contents always. So in java when we need some dynamic content rather that static content we go for a servlet. 

In this part of jsp-servlet tutorial series we came across a basic introduction of Servlet and come to know about request, response and request-response model in web development. In upcoming blogs of this tutorial series we will come to know about Servlet Architecture and other topics related to Servlet ans Jsp's.









Thanks for reading !
Read Full

Jsp and Servlet Tutorials - Servlet life cycle methods - doGet() and doPost() (Part 3 of 8)

Jsp and Servlet Tutorials - Servlet life cycle methods - doGet() and doPost() (Part 3 of 8)

Welcome to third part of jsp-servlet tutorials series. So far we have discussed Request-Response model of Servlet and Archetecture of Servlet. We have also discussed, what a servlet is ? why to use a servlet and we have also discussed how the communication takes place between client and the server. In this particular blog we will dive into lifecycle of a servlet and will come to know about servlet lifecycle methods doGet() & doPost() and their implementation.

Lets first starts with servlet lifecycle states, when it comes to servlet lifecycle we can say that sevlet has a single state so called initialization state. During its whole lifecycle servlet went through three main methods and all these methods are basically called by web container or servlet engine.


1 -init() : init() method of a servlet is called only once in its lifecycle, when a very first request comes to servlet it makes servlet state from does not exists to initialized state and during all other requests servlet remains already initialized.
The container calls the init() method before the servlet can serve any client request. This method can be overridden in our servlet classes to write some initialization code in it. Initialization means something like initializing your data source or other things that we want ready before servlet starts serving the request.

As we all knows that in java constructors are used for initialization stuff, now the question arises why do we use a init() method and not a constructor of servlet class ? The answer of this question is that init() method have access to two useful objects so called servletContext and servletConfig and we needs to use these two many times during our application. A constructor does not have access to servletConfig and servletContext thats why we use init() instead of class constructor to initialize a servlet.

What exactly the servletContext and servletConfig is, we will see this in a moment.

2 -service() : Service methods are the methods where actual working of servlet is defined, a service method is called every time a request comes for a servlet. It determines which http method should be called based on client request. There are 7 http methods but almost in 99% of web application you will be dealing with either a doGet() or a doPost() method.

If user request is a get request than doGet() method of servlet is called and if the request ia a post than doPost() method is called and all the business logic goes into either a doGet() or a doPost() method of servlet. 

3 -destroy() : This method is called by the container when the servlet is no longer required.

Servlet Hierarchy


Servlet Interface : At the top of the hierarchy we have an interface with name Servlet.

GenericServlet Abstract Class : This is an abstract class that implements Servlet interface and overrides its init() method. If init() method is not overridden in your servlet class than init() method of GenericServlet is implemented by default.

HttpServlet AbstractClass : This is the abstract class that is being extended by all servlets created by us, it has all service methods in it so called doGet() or doPost(). If our servlet does not override any service method than the one deleared in HttpServlet class in being implemented by default.

User defined servlet (the one we created in our application) : This is the servlet that we code in our application, http methods so called doGet() and doPost() are written here and all business logic and implementation goes inside these methods.

Difference between doGet() and doPost()
So far we have discussed a lot about doGet() and doPost() methods, now the question arises that when to use a doGet and when to use a doPost(). The one thing to be noted down here is that a get request is sent to request some resource from the server whereas the post request is sent to process data.

The get request contains only the request line and HTTP header, whereas a post request also contains HTTP body along with request line and header.

In get the request parameters are passed to the server by appending at the end of the url, whereas in a post request form elements or parameters are passed as a part of HTTP body and does not append at the end of URL. So whenever we need to send some sensitive information to server, a post request is sent.


The parameters data to be sent over the web is limited to a get request and it depends on container, whereas in a post request we can send a huge amount of data to the server.

In this particular blog from jsp-servlet tutorial series we come across servlet lifecysle and difference between doGet() and doPost() methods. In upcoming tutorial we will cover Response part of Servlet and Difference between RequestDispatcher and SendRedirect.











Thanks for reading !
Read Full

Jsp and Servlet Tutorials - Servlet Architecture and Use of Web Container (Part 2 of 8)

Jsp and Servlet Tutorials - Servlet Architecture and Use of Web Container (Part 2 of 8)

Welcome to Second part of our jsp-servlet tutorial series, so far we have discussed What is request-response model and a quick introduction to Servlet. In this particular blog we will try to cover Architecture of Servlet and a little about Web Containers and their usage in Servlet world.

Archetecture of servlets
Till now we have a brief introduction about servlet need and usage now the question arises that what exactly the servlet is ? and what is servlet architecture

jsp-servlet-tutorials


In simple words we can say that servlet is nothing but a java program, rather we should say it is a special java program, why this is special java program ?, because this does not have a main method instead it has some call back methods so called get or post method as discussed before.

Before we come to know more about get and post method and their implementations, lets first see the request-response cycle in servlets environment. We already knows that to serve dynamic pages a server needs servlets now the question arises, how the server communicates with servlets ? the answer to this question is Web Container.

What does the web container is exectly ?
A web container so called a servlet engine in one which helps the server to communicate with servlet and servlets takes birth and died in a web container, actually a web container is much more than it.
Whenever a request comes from client to server the server sends that request to web conainer and web container invokes either a get or a post method written on servlet, based on which method is being requested in user's request. Now the code written inside that servlet's method body is executed to make response ready. This response is send back to server and finally server sends a dynamic resource back to client.


How does the container handles the request ?
Till now we came to know that whenever a http request for dynamic resource came to the server, the server send that http request to container and now the container is responsible for invocking the right method of right servlet by sending this http request to servlet. And as we already knows that servlet is a java programme, now the question arises that how a java programme understand http request ?, because java understand objects only.

Now the actual function of web container comes into picture, the container converts the http request into valid request and response objects to communicate to servlet. The request object is responsible to send request to servlet programme and run right get or post method accordingly, response object is responsible for getting back the response from servlet to container.
Now a number of questions arises here, what happens when there are a number of requests for a single servlet ? does the same request and response ojects are being used for every request ? what happens to those request and response objects when response is getted back by container ?
The answer to these questions is that,

Every time a new request came to the container it generates a new thread per request and new request and response object for every new request. When the response is got back by the container the request/response objects are destroyed by the container itself. Hence container plays a very important role in servlet life cycle.

Role of web Container 
A web container can have a number of jsp and servlet inside it, it does a number of things by itself so that the developer can concentrate on business logic rather than other low level functions. Some of the main roles of web container are follows.

1- Communication Support : Everything that happens to a servlet the container is responsible for that. It provide an communicative interface between server and the servlets.

2- Lifecycle Management Support :
Servlet have a number of methods to initialize it, provide services and destroy it. And all those methods are invoked by the container from the birth to the death of an servlet.

3- Multi-threading support :
For every request that comes in for the servlet the conatiner creates a saperated thread and execute service method as per client request.

4- Security Handling :
As the requests are always coming through the container, we can put security constarints in container to stop a invalid request being processed.

5- JSP Support


Now the question arises how does the container knows which servlet is being requested by the client, the answer to this question is web.xml file that resides there on server and it have valid mappings from request to servlet. This web.xml looks something like this:
view plainprint?
  1. <web-app>  
  2.   
  3.   <servlet>  
  4.     <servlet-name>loginServlet</servlet-name>  
  5.     <servlet-class>com.javaguys.servlet.LoginServlet</servlet-class>  
  6.   </servlet>  
  7.   
  8.   <servlet-mapping>  
  9.     <servlet-name>loginServlet</servlet-name>  
  10.     <url-pattern>/login</url-pattern>  
  11.   </servlet-mapping>  
  12. </web-app>     

Every servlet in a web application must have an entry into this file withing two tags <servlet> and <servlet-mapping>. Now lets see these fields in details.

<servlet-name>  : A name is given to the servlet withing this tag, name could be any user defined value. <servlet-class> : Here we give the name with path to exact servlet class (java file).

<url-pattern>   : Here we gives the url pattern of requested url, on which the servlet will be called.

Lets understand this servlet mapping with an example, lets assume we have an web application with a host name www.yahoo.com, now we want to call a servlet for login on requested url like www.yahoo.com/login.Here /login is the url-pattern for servlet, lets give it a name LoginServlet in servlet-name tags.

Whenever a requested url like www.yahoo.com/login be requested, it will search for an url-pattern with /login in web.xml, now the servlet-name to this mapping will be compared to servlet block and required class file will be called according to servlet-class tag.

So this is how a web container maps a request from a client and invoke a right servlet and right method and the dynamic response is being served to the client.

In this blog we came to know about the architecture of servlet and a basic introduction to web containers. In our upcoming blogs we will come to know more about Servlet Lifecycle and Implementation of doGet() and doPost methods. In upcoming tutorials we will learn more techniques related to servlets and jsp's and try to create our very first hello world web application with jsp and servlet.









Thanks for reading !
Read Full

Jsp and Servlet Tutorials - Difference between RequestDispatcher and SendRedirect (Part 4 of 8)


Jsp and Servlet Tutorials - Difference between RequestDispatcher and SendRedirect (Part 4 of 8)

Welcome to fourth part of jsp-servlet tutorial series, so far we have discussed Request-Response model of Servlet, Servlet Architecture and Difference between doGet() and doPost(). In this particular blog we will cover difference between RequestDispatcher and SendRedirect that we will cover Difference between ServletContext and ServletConfig.

Response

Now lets discuss something about response, in normal conditions a request comes in for a servlet and servlet sends back the respose to the client. But in some cases assume that if the servlet does not know how to serve the request, now either the servlet knows someone that is able to serve the request or the servlet does not have any information about the request at all.
Whenever a request came to the server and the server is not able to serve it, if the servlet knows someone else who can serve the request, than it redirects the request to that other servlet. If the servlet does not have any information regarding the request it get, a Error page is rendered.

When a servlet is not able to serve a request but it knows that some other server can serve the request it sends the request to that servlet and response is sent back to the client, this process can be done by two different approaches.

Send Redirect

Lets assume that the end user(client) makes a request to some abc servlet, now abc servlet is not able to serve but it knows that an another servlet xyz can serve the request. The abc servlet tells the browser that i am not able to serve the request but xyz can, make a request to xyz to get response. Now browser sends a redirect to xyz servlet and xyz sends back the response to the client. However the end user does not know about this two step process it assumes the request is being served by abc servlet itself.

Request Dispatcher

In case of request dispatcher when a client makes a request to abc servlet, abc forward the request to xyz servlet without telling the browser anything and the response in send back to client by xyz servlet. In request dispatcher the browser does not need to send a redirect to xyz again.
Now the question arises that :

When to use a Request Dispatcher and when to use a Send Redirect ?

We can use request dispatcher only when the other servlet to which the request is being forwarded lies in the same application. In the example explained above, if abc and xyz are not in the same application than we can not use request dispatcher. On the other hand Send Redirect can be used in both the cases if the two servlets resides in a same application or in different applications.

Difference between ServletContext and ServletConfig

Earlier we have discussed that in init() method of servlet, servlet got the access of two object servletContext and servletConfig, now lets discuss these two in more details. To better understand these two objects and difference between them lets take a look at the following picture All the servlets in a web application have access to a single Servlet Context object, whereas each of the servlet have its own servlet config object.


Servlet Context

Servlet context is basically a java object that resides there on application level, there is always a single servlet context for a application. To get values of init parameters on application level we uses getServletContext(). In web.xml it can be specified under <web-app> tags and not under <servlet> tags.

Servlet Config

There can be a number of servlet config objects in an application, its specified as one saperate object for each servlet and jsp. To get init parameters of perticular servlet we uses getServletConfig(). In web.xml it can be specified under <servlet> tags and not under <web-app> tags.
So far we have discussed request, response and their implementations, now its time to get into something about parameters and attributes. Attributes and parameters are something in which we can store the data and retrieve that data when required. Now the question arises what is the difference between attributes and parameters ?.

The return type of Attributes is Object and return type for parameters is a String.

In a high level abstraction we have three three types of attributes and two types of parameters in a web application.

Types of attributes:

1 - Context or Application : Application level attributes or so called application variable can be accessed throughout the whole application. 
2 - Request : The request variable can be accessed within a request scope. Its done by setAttribute(String,object) and retrived using getAttribute(String). It takes an key in form of a string and any type of java object can be stored and retrieved associated to that key.
3 - Session : A session variable or session attribute can be accesed and use in the application within a session or we can say until the session is live.

Parameters : Parameters are of two types, Context parameters and Servlet Init parameters, the return type for parameters is always a string. Here one thing to be noted is that we can access init parameters but we can not set a value to these init parameters in our servlet code, The value to init parameters can be given in web.xml only, init parameters can be accessed using getInitParameter() method.

In this particular blog we went through Difference between RequestDispatcher and SendRedirect and what is difference between ServletContext and ServletConfig than we get to know something about parameters and attributes in servlet and their scope and usage. In our next and blog of jsp-servlet tutorials series we will discuss other useful feature and implementation of Servlet and Jsp's.










Thanks for reading !
Read Full