Thursday, June 27, 2013

How to Create "HelloWorldServlet" and what are the things I need to do....... ?

What is Tomcat ?

Tomcat is webcontainer which has the capability to execute Servlets and JSP pages.
I am not going in to more details about tomcat.After downloding tomcat from internet
you will see a folder structure as in below picture.To execute our HelloWorldServlet
download tomcat which is available for free from Internet.



2)How to start tomcat server?


Go to bin folder in TOMCAT_HOME.When I say TOMCAT_HOME it means the
path which contains bin folder(C:\Tomcat7).In bin folder you will find a batch file
with name startup.If you click on it tomcat server starts.But the prerequisite is you
should set environment variable "JAVA_HOME".

Every server runs on a port.Tomcat by default starts on "8080".
If there is any thing that runs on 8080 tomcat server won't startup.

Following screen is an example of successful tomcat startup.




3)How to set JAVA_HOME ?


Go to MyComputer->Right Click on MyComputer->Choose Properties->
AdvancedSystemSettings->Advanced Tab->Click on Environment Variables
->Click on New(User Variables)


Give Variable name as:  JAVA_HOME
Variable value:              C:\Java\jdk1.7
(The folder which contains bin folder is the JAVA_HOME)

Click OK



 


4)Create HelloWorldServlet.java.

I have created in C:\test\examples\HelloWorldServlet.java
Copy the following code in Red into HelloWorldServlet.java in C:\test\examples
folder

package examples;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Rishitha
 */
public class HelloWorldServlet extends HttpServlet {

 

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.print("From doGet method  ");
      
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         PrintWriter writer = response.getWriter();
        writer.print("From doPost method  ");
       
    }

}



 5)Go to C:\test\examples and compile HelloWorldServlet.java.

If you have observed HelloWorldServlet.java,it is using many classes like
HttpServletRequest,HttpServletResponse,HttpServlet.


All those classes are available in servlet-api.jar
servlet-api.jar is present in C:\tomcat7\lib folder

 So,before compiling HelloWorldServlet.java we have to set classpath to
 servlet-api.jar file which contains  HttpServletRequest,HttpServletResponse,
HttpServlet.

6)How to set classpath to servlet-api.jar ?

  a)Go to C:\test\examples
  and type set classpath=%classpath%;C:\Tomcat7\lib\servlet-api.jar

  b)Compile HelloWorldServlet.java from C:\test\examples
      javac HelloWorldServlet.java
 
 
 
 


7)To run servlet you have to place it webapplication.
    Every webapplication should follow a predetermined format.


8)How to prepare predefined webapplication format ?

    Following is the structure we have to follow for any webapplication
    -----------------------------------------------------------------------------------------

          Every web application will have WEB-INF Folder
          WEB-INF folder contains
                a)classes folder(This should contain compiled class files)
                b)web.xml
                  

  1) Create one folder with name "webexamples"
  2)In webexamples folder,Create WEB-INF folder
  3)Go inside WEB-INF folder.Create following
         a)classes folder
         b)web.xml

  4)Copy the following content into web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>HelloWorldServlet</servlet-name>
        <servlet-class>examples.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/HelloWorldServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

9)Go to the C:\test\.
  From there copy the examples folder in to classes folder created in above step.

Folder structure of webexamples folder should be as given in the following
pictures for your reference






 Go to WEB-INF.. It should look like in the following picture




 Classes folder should contain our examples folder which contains HelloWorldServlet.class
as in the following image.


 
10)After creating the webexamples folder in the specified format

Copy the webexamples foder to
C:\Tomcat7\webapps


And we are almost to end of this post.......... :)


11)Go to C:\tomcat7\bin\->Click on startup.bat to start tomcat server

Go to browser

Enter following URL

http://localhost:8080/webexamples/HelloWorldServlet
(If your tomcat is running on another port eg:8084,you have to give url
as
http://localhost:8084/webexamples/HelloWorldServlet


You should see the following output....
If you get "From doGet method"... that means...... You executed your first
HelloWorldServlet successfully.




 If you are first time............. doing this procedure.............. it seems very difficult...........
 but once you practice........... this will be very very easy......................


 If you have doubts you can contact me at
 anilkumar.spectrum@gmail.com

Hope you enjoyed.......... HelloWorldServlet........... 
Anil Chintha............




 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Wednesday, June 26, 2013

1)What is equals method and why is it important ?


In java every class implicitly extends Object class.So,when you write a class, it has equals
method automatically even if you haven't written equals method.(The equals method in
Object class will be inherited in to Student class).

Copy the following code in blue into Student.java,compile and execute it.
Go through the comments section in the code.I have explained clearly... why the
following code returns that objects are not equal.


class Student{
     int studentId;//This is the only property of Student

   

     public static void main(String args[]){

        //Create one student object with name first

        Student first = new Student();
        first.studentId = 100;
       
        //Create one student object with name second
        Student second = new Student();
        second.studentId = 100;
        /*In student class I haven't written equals method but still I am able to use it
        because as I said earlier every class inherits Object class,so we are able to use equals
        method which is inherited from Object class.
       
         Following code prints........ "First Student and Second Student are not equal"
         Logically as two students are having same student id, they should be equal,
        but the equals method from Object class checks if the memory references are
        same or not,it doesn't check if student ids in the two objects are same or not.
       
         I will explain you in more detail what do I mean comparing memory references.
        When you say Student first = new Student(); in memory student object is created and
        reference to that object is assigned to first.This reference is unique for every object.
       
        Student first = new Student();
        above statement creates student object in memory and reference to the object created
        (This will be always unique for every object)is assigned to first
       (For example assume reference returned is 1000)
       
        Student first = new Student();
        above statement creates student object in memory and reference to the object created
        (This will be always unique for every object) is assigned to second
       (For example assume reference returned is 2000 and assigned to second)
       
        equals method inherited from object method checks if references are equal
        So in our example it checks if 1000 == 2000, as they are not equal,equals
        method returns false*/
       
       
        if(first.equals(second)){
             System.out.println("First Student and Second Student are equal");
        }else{
             System.out.println("First Student and Second Student are not equal");
        }
    }   
 }

Output:
--------

C:\test>java Student
First Student and Second Student are not equal

2)How to modify the above class to compare students based on student ids and not based on memory references ?

Solution is you have to override the equals method... in Student class.
Overriding means you create equals method in Student class which has same 
signature as the method inherited from Object class.

Add the equals method given below(highligted in red) into Student class and
compile again,run and see the output.

Now it will print "First Student and Second Student are equal".
Because now equals method in student checks if the studentIds are same
if student Id's are same(100 == 100) it return true otherwise false.


 /*Define equals method in Student class which overrides
 equals method inherited from Object class*/
     

   
    public boolean equals(Object st){
        if(st instanceof Student){
          
           Student second =(Student)st;
           if(this.studentId == second.studentId){
                return true;
           }else{
               return false;
           }
        }else{
             return false;
        }
       }




Hope you understood......
  











Hi Everyone

This is my first post on java and today I like to share you the steps on
"How to create HelloWorld Programme in Java" and "How to execute Java
Programme from command line".

1)Download JDK.I have downloaded jdk1.7 and it is in C:\Java\jdk1.7.
   Folder which contains bin folder is known as "JAVA_HOME"


2)Create a file with HelloWorld.java.Place the following sample code.
    I have created HelloWorld.java in C:\test folder.

public class HelloWorld{

    public static void main(String args[]){

         System.out.println("Hello World");
    }

}

3)Next step is we have to compile HelloWorld.java.
   Before compiling,the most important step is we need to set the path to javac tool in the 
   command prompt.

javac tool is used to compile .java file to .class file.

javac tool will be located in C:\Java\jdk1.7\bin folder.Following picture shows you how to set
path to javac tool from command prompt.

a)When you run javac,initally it gives error.
b)So from C:\test,enter the following command
       set path=%path%;C:\Java\jdk1.7\bin.
  



   4)Now you are ready to compile HelloWorld.java.From C:\test run the following command
      javac HelloWorld.java.When you hit enter you can see HelloWorld.class file gets created
      in C:\test directory.

     

  5)Now you are ready to run and see the output.

      Enter following command from command prompt.
      java HelloWorld(Don't give .class extension)



If you have any doubts please drop me email at anilkumar.spectrum@gmail.com.
Hope you enjoyed my first post.