Questions on OOPs

1. What is OOPs?
Ans. OOPs stands for Object Oriented Programming specifications. It is a programming technique or paradigm in which every thing revolves around real world entities or objects. Main focus in this technique is on objects rather than actions and data rather than logic. C++, Java, C# are few examples which supports OOPs.

2. What are the core concepts of OOPs?
Ans. OOPs core concepts are :

  1. Abstraction
  2. Encapsulation
  3. Polymorphism
  4. Inheritance
  5. Composition
  6. Association
  7. Aggregation
3. How does OOPs improves software development?
Ans. The key  benefits of OOPs are :
Re-use  of previous  work: using  implementation inheritance  and  object  composition.
Real  mapping  to the  problem  domain:  Objects map to  real  world and represent  vehicles, customers, products etc.  with  encapsulation.
Modular Architecture:  Objects, systems, frameworks etc are  the building blocks of  larger systems. The  increased  quality  and  reduced  development time  are the by-products of the  key  benefits discussed above. If 90% of the  new  application consists of proven  existing  components then only  the remaining  10%  of the code have to be  tested from scratch.

4. What is the difference between Abstraction and Encapsulation?
Ans. Main differences between Abstraction and Encapsulation are :
1. Abstraction provides a general structure of a class and leaves it's implementation detail to the implementer. Encapsulation is used to restrict access to members of an object.
2. Abstraction is implemented using interfaces and abstract classes. Encapsulation is implemented using four types of access specifiers public, private, protected and default. 

5. What is abstract class in Java?
Ans. A class which defines the structure of a class without going into implementation details is known as abstract class. We can not instantiate an abstract class directly. Abstract classes can have abstract as well as non abstract methods. We have to use abstract keyword for defining abstract classes, which then can be extended using extends keyword.

6. What is interface in Java?
Ans. An interface is also used to define structure of a class with full abstraction which means unlike abstract classes interfaces would not provide any implementation of methods.

7. What is the difference between abstract classes and interfaces?
Ans. There are many differences between them, one of the major difference is interface is used to apply full abstraction where as abstract classes can be used for partial abstraction.
For more information please visit : Difference between abstract classes and interfaces

8. What is the difference between method overloading and method overriding?
Ans. In method overloading same method name is used multiple times with different set of parameters in same class whereas in method overriding implementation of method from super class is override in sub classes without changing it's set of parameters.
Another difference is overloading is resolved at compile time because class information is know at compile time but overriding is resolved at runtime because object information is required to resolve overridden methods.

9. What are the rules for method overloading?
Ans. When we are overloading methods we need to take care that their signature should be different which can be achieved either by changing number of arguments or changing type of arguments. If we are trying to overload methods by simply changing it's return type then compiler will throw an exception. 

10. What are the rules for method overriding?
Ans. When we are overriding methods in sub class then we can't change below things :
1. Signature of method can not be changed.
2. Return type of method can not be changed.
3. Overloaded method can not throw higher exception.

11. What is covariant method overriding in Java?
Ans. Consider a scenario where we have a method in a parent class which is returning a general type like List class etc. and in our sub class we have to override the same method but it would return an ArrayList instead of List. We know that return type of overridden method can not be changed, right, but in this case we can change the return type to ArrayList because it is a sub type of List. This is known as covariant method overriding.

12. What is the difference between "IS A" and "HAS A" relationship?
Ans. The "is a" relationship is expressed with inheritance whereas "has a" relationship is expressed with composition. Both techniques are used for code re-usability. Consider below example for understanding both techniques :


"is a" relationship or inheritance is uni-directional. As shown in above example, House is a Building but Building is not a House. In Java programs to establish "is a" relationship we use extends keyword.
In above example there is "has a" relationship between House and Bathroom, it is incorrect to say House is a Bathroom. In order to establish "has a" relationship we create instances of other classes inside the main class.

13. When to use inheritance and composition?
Ans. Below are the rules that we should follow while using these two techniques :
1. Don't use inheritance relationship unnecessary just for code re-use. If there is no "is a" relationship between classes then composition should be used.
2. Overuse of inheritance (using extends keyword) can break all sub classes if super class is modifed hence use it carefully.
3. Do not use inheritance just to get Polymorphism. If there is no "is a" relationship and all we want is polymorphism then we can  use interfaces with object composition.

14. What is difference between Aggregation and Composition?
Ans. Aggregation is an association in which one class belongs to a collection of classes. That class is a part of whole relationship where a part can exist without a whole, which means if whole relationship is deleted then also that class can exists.
For example : Bill of an order placed contains line items which specifies which products we have ordered. If we delete line items from that order then we do not need to delete products. This means there is weaker relationship between line items and products.

Composition is an association in which one class belongs to a collection of classes. This is a part of whole relationship where a part cannot exist without a whole. If whole is deleted then all parts are deleted.
For example : If we delete the Order then all line items in that order will get deleted, because like line items can not exist without an order. 

15. What is difference between implementation inheritance and interface inheritance?
Ans. For answer please visit : OOPs Concepts - 2

Share:

Difference between Interfaces and Abstract Classes

What is the differences between interface and abstract classes?

This is one of the most widely asked question in an interview at any level. In this post we are going to focus on differences between interface and abstract classes, what are ideal situations in development for using these etc. 

While designing a software or an API we don’t want Base class to be instantiated directly, we just want the base class to provide a structure that needs to be implemented by sub classes. This can be achieved using abstract classes. Interface takes this concept one step further by preventing any method or function implementation at all. 

Differences between interfaces and abstract classes :

1. Prior to Java 8 interfaces can only have abstract methods without any implementation but java 8 on wards we can now have default implementation of methods in interfaces and for that we can use default keyword at the beginning of method signature. Abstract classes can have abstract as well as non abstract methods.

2. Variables declared in interfaces are final by default whereas abstract classes can have non-final variables as well. 

3. Abstract classes can extend interfaces but reverse is not possible.

4. In java we implements interfaces using implements keyword whereas we extend abstract classes by using extends keyword.

5. We can implement more than one interface but we can not extend more than one abstract class.

6. Members of interface in java are public by default, members of abstract classes can have any access specifier.

Diamond problem and use of interface. 

Consider a secenario where we are designing an API for drawing different shapes. First let’s design this using abstract classes. We have created a parent class Shape with all necessary functions that needs to be implemented by it’s sub classes. Now let's create two sub classes one is Circle and other is Square and both extends Shape class. Now what if we want to create a new shape Circle on Square we can’t reuse Circle and Square classes here because only one class can be extended. 
This is know as diamond problem, we can use interfaces to resolve this type of design problems. 

When to use abstract class?

In  case  where  we want  to  use  implementation inheritance  then it  is usually provided by  an  abstract  base class.  Abstract  classes are  excellent  candidates inside of  application frameworks.  Abstract  classes  let  us define  some default  behavior and force subclasses to  provide any  specific behavior.  Care  should be taken not  to  overuse implementation inheritance.

When to use interface?

For polymorphic interface inheritance,  where the client  wants to  only  deal  with  a type  and  does  not  care  about  the  actual  implementation  use  interfaces.  If  you  need  to  change  your design frequently,  you  should  prefer  using interface to  abstract.  Coding  to  an interface inheritance can achieve  code  reuse  with  the help of  object  composition.  For example:  The Spring  reduces coupling  and framework’s  dependency  injection promotes  code to  an  interface principle.  Another justification for using  interfaces is that  they  solve the  ‘diamond problem’ of  traditional  multiple  inheritance as  discussed above. Java  does  not support  multiple  inheritance.  Java only supports  multiple interface inheritance. Interface  will solve  all the ambiguities caused by  this ‘diamond  problem’. 

What is marker interface?

The interfaces  with  no  defined  methods  act  like markers.  They  just  tell  the  compiler that  the  objects  of  the classes implementing  the interfaces with  no defined  methods need  to  be  treated  differently.  Example  java.io.Serializable,  java.lang.Cloneable,  java.util.EventListener  etc.  Marker interfaces are also  known  as “tag” interfaces  since they  tag  all the derived  classes into  a category based on their purpose.
Share:

OOPs Concept - 5


What is encapsulation? 

Encapsulation means wrapping up things in a single unit, it’s like a process through which capsules are created. In creating we mix up different medicines and wrap them in a single capsule. In OOPs data and functions, which operates on the data, are wrapped in a single unit called class. This is what encapsulation is.

In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.

Below is an example of encapsulation:

class Employee{
        private String empId;
        private String empName;

        public void showDetails(){
                System.out.println("Emp Id :  "+this.empId+" Emp Name : "+this.empName);
        }

         public void setEmpId(String empId){
                this.empId = empId;
        }
        public void setEmpName(String empName){
                this.empName = empName;
        }
}


We can see in above programs variables empId and empName are declared as private so we cannot access them directly. In order to access those variables we need to create an instance of Employee class and then we can access public set method for changing their values. Let’s see how we can do that :

class MainClass{
   public static void main(String []args){
      Employee obj = new Employee();
      obj.setEmpId("EMP10001");
      obj.setEmpName("Nishesh Pratap Singh");
      obj.showDetails();
      System.out.println("Changing Emp Name");
      obj.setEmpName("Rahul Singhania");
      obj.showDetails();
   }
}


When we execute above program we will get following output on console :

Emp Id :  EMP10001 Emp Name : Nishesh Pratap Singh
Changing Emp Name
Emp Id :  EMP10001 Emp Name : Rahul Singhania


Benefits of  Encapsulation are as follows :

1. Through encapsulation we can made fields of a class read-only or write-only.
2. A class can have total control over what can be stored in it's field and what cannot. 
Share:

OOPs Concept - 4


What is abstraction?

Abstraction is one of the important concept in OOPs. Abstraction, basically means hiding unnecessary details and showing relevant information to users. Take for example, when we learn to drive a car we do not care about how it engines work, we only cares about how it's steering, brake and accelerator will work. We never get into the complication of car's internal working.

In OOPs abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

There are basically two types of abstraction :

Data Abstraction : Data abstraction is the way to create complex data types and exposing only meaningful operations to interact with data type, whereas hiding all the implementation details from outside work.
Advantage of this abstraction is that even if our internal implementation got change there will be no impact on client facing code since they only work with the exposed behavior not the internal implementation.

Control Abstraction : When we works on a application software, we sometimes write repetitive code at multiple places. Control abstraction is the process of identifying such statements and expose them as single unit of work. We normally use this feature when we create a function to perform any work.

How we achieve abstraction is Java?
In java abstraction is achieved by interfaces and abstract classes. Interfaces allows you to abstract implementation completely whereas abstract classes allows for partial abstraction.

Let's see an example for both of these:

Abstraction using interfaces

interface Animal{
     public void voice();
     public void eat();
}

class Dog implements Animal{
 
     @Override
     public void voice(){
          System.out.println("Dog Barks");
     }   

     @Override
     public void eat(){
          System.out.println("Dog eats Meat");
     }
}

class Cat implements Animal{
 
     @Override
     public void voice(){
          System.out.println("Cat Meows");
     }   

     @Override
     public void eat(){
          System.out.println("Cat drink Milk");
     }
}

class MainClass{
     public static void main(String[] args){
           Animal  dog = new Dog();
           dog.voice();
           dog.eat();
         
           Animal  cat = new Cat();
           cat.voice();
           cat.eat();
     }         
}


Remember we can not instantiate objects of interfaces directly. When we execute above main class we will get below output on console.

Dog Barks
Dog eats Meat
Cat Meows
Cat drink Milk


For abstract class example let's repeat our Employee example from previous post.

abstract class Employee{
 
        private String empName;
        private String empId;
     
        public void storeDetail(){
             System.out.println("Storing employee details");
        }

        public void showDetail(){
             System.out.println("Showing employee details");
        }

        public abstract void calculateSalary();
}

class PartTimeEmployee extends Employee{

        @Override
        public void calculateSalary(){
             System.out.println("Calculating salary for part time employee.");
        }
}


You might like to see : Difference between abstraction and interface.

This is all about abstraction is java, we will discuss about Encapsulation in next post. 
Share:

OOPs Concept - 3


What is Polymorphism?

Polymorphism is one of the important principle of OOPs. In this post we are going to discuss about Polymorphism. This word has been derived from two words poly (which means many) and morph (which means forms), so Polymorphism means many forms. In OOP an object can exists in more than one form, which can happen when we have many classes related to each other through Inheritance. This can  be achieved when a parent class reference is used to refer a child class object.

Let’s take our example from previous post on Inheritance, we have a super class Employee and two sub classes PartTimeEmploye and FullTimeEmployee.

class Employee{
      private String empName;
      private String empId;


      public void storeDetails(){}
      public void showDetails(){}
}

class PartTimeEmployee extends Employee{
      private void calculateSalary(){}
}

class FullTimeEmployee extends Employee{
      private void calculateSalary(){}
}


Now let’s create a main class for using these classes :

class MainClass{

  public static void main(String []args){
     Employee emp1 = new Employee();
     Employee emp2 = new PartTimeEmployee();
     Employee emp3 = new FullTimeEmployee();
  }

}


So in above main class you can see we have created three instance of Employee class emp1, emp2 and emp3. In above example emp1 is purely an Employee, emp2 is PartTimeEmployee and emp3 is FullTimeEmployee, which shows instance of Employee class can exists in many form. This is what Polymorphism is all about.

There are two more terms Overriding and Overloading that's been considered as type of Polymorphism. Let's discuss about therm.

Overriding : When we extend parent class for creating child classes we can also override functions in parent class as per the requirement in child classes, this is know as overriding. Consider below example.

class Employee{
      private String empName;
      private String empId;


      public void storeDetails(){}
      public void showDetails(){}

      public void calculateSalary(){
        System.out.println("This is default method for calculating salary.");
      }
}

class PartTimeEmployee extends Employee{
      private void calculateSalary(){

        System.out.println("This is method for calculating salary for part time employees.");
           }
}

class MainClass{

  public static void main(String []args){
     Employee emp1 = new Employee();

     emp1.calculateSalary();

     Employee emp2 = new PartTimeEmployee();

     emp2.calculateSalary();
  }

}


We can see we have overridden method calculateSalary so when above main class is executed that will print below statements on console :

This is default method for calculating salary.
This is method for calculating salary for part time employees.

calculateSalary now has two forms one for Employee class and other for PartTimeEmployee class.

Overloading : When we have same method with different set of arguments in a class then it is known as method overloading. Below is an example of overloading :

class OverloadingExample{
 
       public void print(int a, int b){
             System.out.println("a : "+a+" , b : "+b);
       }

       public void print(String a, int b){
             System.out.println("a : "+a+" , b : "+b);
       }

       public void print(String a, String b){
             System.out.println("a : "+a+" , b : "+b);
       }   

       public static void main(String[] args){
             OverloadingExample exp = new OverloadingExample();
             exp.print(10,20);
             exp.print("ABC",20);
             exp.print("ABC","XYZ");
       }
}


In above example we can see print method has been overloaded three times, so when above program is executed we will see below output on console.

a : 10 , b : 20
a : ABC , b : 20
a : ABC , b : XYZ

print method has now more than one form and which form is executed depends on number and type of arguments passed.

This was all about polymorphism, we will discuss about abstraction in next post.
Share:

OOPs Concept - 2

What is Inheritance?

Inheritance is another important concept of OOPs. In this post we will discuss about another important OOPs concept i.e. "Inheritance".  In general term it means something that is being inherited. When we write programs in OOPs languages like JAVA we can use this concept for creating relationships between classes. We can't write code for each and every entity repeating common functionality.

Consider a simple scenario, we need to write programs for managing employees now there are two categories of employees part time and full time. If we write two separate Class for managing these two categories then we need to repeat lot of code like managing basic details, showing details when required etc. Below are the sample code for both classes without inheritance.

class PartTimeEmployee{
        private String empName;
        private String empId;

        private void storeDetails(){}
        private void showDetails(){}
        private void calculateSalary(){}
}

class FullTimeEmployee{
        private String empName;
        private String empId;

        private void storeDetails(){}
        private void showDetails(){}
        private void calculateSalary(){}
}


In this scenario we need to identify which are common properties and behavior that both entities have and taking those properties and behavior we can create a "Super Class" or "Parent Class".  We can clearly see in above classes only implementation of calculateSalary() is going to be different. For part time employees it is going to be based on number of hours whereas for full time employee salary is a fixed monthly amount.

So if we take out common properties and behaviors out and create a new class, we can create a "Supper Class" employee as shown below.

class Employee{
        private String empName;
        private String empId;

        public void storeDetails(){}
        public void showDetails(){}     
}

Why we have defined methods with public access specifier, because we want them to be available for other classes as well. Now we can create "Sub Class" using above class which will have all the properties and behavior(only public ones) from it. Additionally they can have specialized properties which will not be common.

In Java we have extends keyword for creating sub-classes. After implementing inheritance concept we will get following implementation of  PartTimeEmployee and FullTimeEmployee.

class PartTimeEmployee extends Employee{
        private void calculateSalary(){}
}

class FullTimeEmployee extends Employee{
        private void calculateSalary(){}
}

As you can see our implementation got simpler now without any repetition. This is what inheritance is all about, creating generalized class having common properties and behavior and then extending that class for creating specialized classes.

Some important terms that we need to remember in relation to inheritance :
Super Class or Parent Class : This is a generalized class having common properties and behavior which can be inherited by other classes. This class can be extended using extends keyword.

Sub Class or Child Class : This is a specialized class which extends super class and have some specialized properties and behavior which are not there in super class.

There are different types of inheritance that we can come across :
Single Inheritance : This is the simplest form of inheritance. In this type of inheritance there is one parent class and one child class inherits from the parent class.

Multi-level Inheritance In this type of inheritance child class can also be extended. Consider below example.

class A{

//this is the parent class

}



class B extends A{


//this is child class of A

}

class C extends B{

//this is child class of B

}


Hierarchical Inheritance In this type of inheritance more than one sub class are created extending the same parent class. The example that we have done in starting of this post is this type of inheritance.

Multiple Inheritance In this type of inheritance one sub class extends more than one parent class. But in Java multiple inheritance is not possible because extends keyword can only be applied to one parent class.
Note : From Java 8 onward there is possibility of multiple inheritance using interfaces by defining default methods.

From implementation point of view, there are two types of Inheritance :
1. Implementation inheritance (aka class inheritance): You can extend an application's  functionality by reusing functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only inherit from one superclass. Implementation inheritance promotes re-usability but improper use of class inheritance can cause programming nightmares by breaking encapsulation and making future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using implementation inheritance, make sure that the subclasses depend only
on the behaviour of the superclass, not on the actual implementation.

2. Interface inheritance (aka type inheritance): This is also known as subtyping. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.

This is all for inheritance, we will discuss about polymorphism in next post. 
Share:

Handling user inputs using Servlets - Part 4

This is the final part of "Handling user inputs using Sevlets". In the last post we have seen how we can create servlet which will handle our server side processing.
To begin with we need to create an HTML page which will hold our sign up form. We have created sign_up.html page.

<html>
<head>
<title>Sign Up</title>
</head>
<body>
<form action="sign_up.do" method="post">
First Name : <input type="text" name="first_name">
<br/><br/>
Last Name : <input type="text" name="last_name">
<br/><br/>
Gender : <input type=radio name="gender" value="male"> Male <input type=radio name="gender" value="female"> Female
<br/><br/>
Favorite Color : <select name="color">
                    <option value="Red">Red</option>
                    <option 
value="Blue">Blue</option>
                    <option value="Green">Green</option>                           
                 </select>
<br/><br/>

<input type="submit" /> <input type="reset" />
</form>

</body>

</html>

When we run our application, setting this html as first welcome file in deployment descriptor (WEB-INF/web.xml) we will be able to see below page in browser.

HTML Form
HTML Form

Now we will create the servlet which will process our form at server end.

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/sign_up.do")
public class SignUpServlet extends HttpServlet{

 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         String firstName = request.getParameter("first_name");
         String lastName = request.getParameter("last_name");
         String gender = request.getParameter("gender"); 
         String color = request.getParameter("color"); 
         System.out.println("Form submitted by user with below value");
         System.out.println(firstName+" : "+lastName+" : "+gender+" : "+color);
    }
}


Above we have only override doPost method as we are submitting form using POST method. For now we will be printing form values on console. You can save these values to database as well but that's a separate topic which we will cover later.

When below form is submitted we will be able to see below values in console.

Form in HTML

getParameter in Servlet


This is how we handle user inputs in servlet. Thanks for seeing all my posts on "Handling user inputs using Servlets". There are more to come please follow my blog and give your suggestions, any suggestion given is valuable to me.
Share:

Handling user inputs using Servlets - Part 3

How to create servlet?

In previous two post we have learnt how to create forms and what are important things that needs to taken care of for proper form submission. From this post on wards we will be learning how to handle submitted form at server side in a servlet. I hope you have some knowledge of a servlet and if not then below is a short tutorial on "How to create Servlets".

In order to create a Servlet we need to create a Java Class first.

public class SignUpServlet{

}


This is a simle POJO (Plain Old Java Object), in order to convert this simple class to Servlet we need to extend this class from HttpServlet which is available in javax.servlet.http package.

import javax.servlet.http.HttpServlet;

public class SignUpServlet extends HttpServlet{

}


Now in order to make this servlet accessible through URL, we need to specify the path for this servlet which we can do using @WebServlet annotation which is available in javax.servlet.annotation package.

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;

@WebServlet("/sign_up.do")
public class SignUpServlet extends HttpServlet{

}


As we discussed in previous posts there are two methods through which we can submit our forms those are "GET" and "POST". In order to handle form at server side we need to define method for corresponding methods HHTP method which we have used in our forms. In brlow example I am showing implementation for both methods.

We have methods defined in our parent class(HttpServlet) for servlet, for hadling GET and POST requests, below are two methods :

doGet(HttpServletRequest request, HttpServletResponse response)
doPost(HttpServletRequest request, HttpServletResponse response)


We need to override one of these two for handling forms at server end.

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/sign_up.do")
public class SignUpServlet extends HttpServlet{


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}


This is how we create servlets. Above servlet code will be used in next post and will see how we can access form data at server end.

Continue to Part 4
Share:

Handling user inputs using Servlets - Part 2

This post is in continuation of  first part of  "Handling user inputs using Servlets", if you haven't seen that post, I will request you to see that post first before continuing this post.

In our first part of this topic, we have seen how to create form. In this post we will learn how form submission works and what are the important things that we need to take care during form submission. Below are some important attributes of form tag that we need to use for form submission.

action : This attribute is use to specify the destination of the form, where the information that users has filled up needs to be send. Below is an example :

<form action="sign_up.do">.............</form>

When we submit above form the information that we have filled up in form will be submitted to the page that we have mentioned in action attribute. In our example form will be submitted to sign_up.do, which is a servlet.

method : This attribute is use to specify how form will be submitted. There are primarily two HTTP methods which we basically use for form submission. They are GET and POST, below is the difference between two.

GET : We can use this method when there is non-confidential information in our forms because when form is submitted with GET method all information in the form will get shown to the user in the URL.

POST : We can use this method when there is confidential information in our forms because when form is submitted with POST method all information in the form will not be shown to the user in the URL. All those information will be send in request body.

Below are examples for both methods.

<form action="sign_up.do" method="get">.............</form>
<form action="sign_up.do" method="post">.............</form>


Now we are aware how a form is submitted to a servlet. There is one more important thing that we need to take care for proper form submission. When we use input, select or any other tag inside form element, we need to make sure they all have "name" attribute and should be given a suitable value because through this value we will be getting the form information on server side. All those input elements which do not have name attribute inside forms will not be available on server side, so this is an important point to remember.

Below is the complete for with above attributes which is ready to be submitted.

<form action="sign_up.do" method="post">
First Name : <input type="text" name="first_name">
<br/><br/>
Last Name : <input type="text" name="last_name">
<br/><br/>
Gender : <input type=radio name="gender"> Male <input type=radio name="gender"> Female
<br/><br/>
Favorite Color : <select name="color">
                                 <option>Red</option>
                                 <option>Blue</option>
                                 <option>Green</option>                             
                          </select>
<br/><br/>
</form>


Above code will generate the same form which we have seen in first post.

This is how we create forms in HTML. In next post we will see how we can get values filled by user in a form on server side in servlet. Please let me know if you have any doubts or questions, I will be happy to help you out.

Continue to Part 3
Share:

Handling user inputs using Servlets - Part 1.

In most of the websites and in all web applications there are forms for taking input from users. You may have seen form in "Contact Us" section of websites. Even if you are surfing on internet there are forms that you fills up for searching things on internet.

Forms are the most effective way of taking inputs from user. In this post we are going to discuss how we can handle forms using servlets.

In order to start we need to create a form that either can be in form of HTML page or JSP page whatever you like. We need to use <form> tag for generating forms.


<form>
    .
    .
   //We will be using different elements within this form 
     element for taking different types of inputs from users.
    .
    .
</form>

There is <input> tag which can be used within form element for creating different types of controls for taking inputs from user.Below is the list of components that can be used in form for taking inputs from users.

Textbox : This is the most common element that is being used in forms for taking input from users. We will use input tag and will use its type attribute for generating a textbox by passing "text" in its value. Below is an example.

Enter Name : <input type="text"> 

Above code will generate below element on HTML page.
Textbox in Form

Dropdown : Another common element that we see in HTML forms is dropdown. For generating dropdown we will use <select> tag, this will generate dropdown in form. We can use <option> tag for specifying values in dropdown. Below is an example.

Select Favorite Color : <select>
                           <option>Red</option>
                           <option>Blue</option>
                           <option>Green</option>
                        </select>

Above code will generate below element on HTML page.
Select in Form







Radio Buttons : I am sure you all have seen radio buttons in web sites as well. We will use <input> tag and will pass radio in it's type attribute. Below is an example.

Gender : <input type="radio"> Male <input type="radio"> Female

Above code will generate below element on HTML page.
Radio buttons in Form

For more information on input tag you can visit on : W3Schools

Now we have essential information about form and input tags which we can utilize for generating forms on HTML page. For our exercise we will take "Sign Up" form as an example. Below is the code for form creation :

<form>
First Name : <input type="text">
<br/><br/>
Last Name : <input type="text">
<br/><br/>
Gender : <input type=radio> Male <input type=radio> Female
<br/><br/>
Favorite Color : <select>
                                 <option>Red</option>
                                 <option>Blue</option>
                                 <option>Green</option>                               
                          </select>
<br/><br/>
</form>

Above code will generate below form :

Forms in HTML










This is all about basics of HTML form. We will continue this topic in parts, this is the first part. Please let me know what you feel about this post.

Continue to Part 2
Share:

Popular Posts

Recent Posts

Followers

Total Pageviews