Introduction

Java Servlet is the one of the most important Java technologies. It is the simplest model to build a complete Java J2EE Web Application. Furthermore, even for complex J2EE Web Application that uses Struts, Spring, EJB and etc, they are still using Servlet for certain purposes such as Servlet Filter, Listener and etc. Thus, it is just a good idea for you to have well-built understanding of Java Servlet. Prior reading this tutorial, it would be excellent if you have mastered the basic Java programming languages.

At the completion of the tutorial, you are expected to comprehend the concept of the Java Servlet, be familiar with the ways to create Java Servlet using NetBeans 5.0, differences between POST and GET and should be ready to go to the next level.

In this tutorial, we are going to create one dynamic web application that asks the user for first name and surname. Then the system should response by greeting the users.

The tutorial consists of four main steps.

  1. Introduction to NetBeans 5.0
  2. Creating New Web Application Project in NetBeans 5.0
  3. Implementation of Tutorial's Example
  4. Conclusion
   
 

Introduction to NetBeans 5.0

Nowadays, NetBeans is one of the most powerful Java programming IDE. Other popular Java IDEs are also available in the market such as Eclipse, Bea WebLogic Workshop, IBM WebSphere Application Development (WSAD) and etc. Creating and implementing Java Servlet using NetBeans is extremely straightforward and simple. This is one of the reasons why NetBeans rapidly grow its popularity. Additionally, it has Tomcat bundled together within the NetBeans hence compiling and deploying Java Servlet is just a few clicks on your mouse. Well, without going any further, let's start our tutorial.

Creating New Web Application Project in NetBeans 5.0

Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). JSP is actually a HTML but unlike HTML, JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In short words, we may represent JSP as dynamic HTML. In Java J2EE Web Application, JSP plays as a front-end while Java Servlet is the controller that contains the business logics, complex algorithms and etc.

For example, consider "Online University Student Registration System" developed in Java J2EE Web Application, the registration page where you fill in your details such as your name, your address, your username and etc are actually a JSP page. Later on, when you have completed filling out all the details and you press the submit button, all the information will be sent to Java Servlet for further processes. Java Servlet receives this information, does the necessary processes such as validations, generating user id and etc and then keeps the information to database. After successfully saving the data to database, Java Servlet redirects the user to the success page where the user can log in to the system. Likewise, if there is an unexpected error occurred happening in the middle of student registration system's process, the user will be redirected to the error page.

Okay, without any more delay, let's get ready for our tutorial. Start your NetBeans 5.0. After it has been completely started, it should look like below screenshots.


Image

Image

First, we have to create a new Web Application Project for our Java Servlet. This Web Application contains all the JSP pages as well as our Servlet classes. To create a new Web Application in NetBeans 5.0, you can go to the menu and choose File > New Project. A wizard will instantly be displayed to you and you are required to provide some information to configure your Web Application.


Image

As the wizard is displayed as shown on above illustration, choose Web on the left panel and Web Application on the right panel and click Next button. All the other options are used to develop other kind of projects in NetBeans and irrelevant for our tutorial.


Image

In the next step or the second step of configuring our Web Application, you can provide your Web Application a name. Well, please feel free to name it whatever you want. In this case, to make it self-explanatory, I name our Web Application as MyFirstServlet as shown in the above illustration. In the middle of the wizard, there is an option called Server and it has the value of Bundled (Tomcat 5.5.7). It demonstrates that NetBeans 5.0 will use its bundled Tomcat as the default server. Other configuration should remain the same and press Finish button. You can also press the Next button to go to the last page where you can define the frameworks that you would like to use as shown in below illustration. However, we can skip the last step as we do not use any framework for our Java Servlet. Okay, we have completed our configuration of Web Application and we are ready to implement our first Java Servlet. Grab your coffee and we are ready to go.


Image

After completing the Web Application's configuration, you should have a screen similar as below. It will also create one default JSP file called index.jsp on your Web Pages folder.


Image

Implementation of Tutorial's Example

For our tutorial, we are going to use index.jsp to demonstrate how to implement Java Servlet that greets the users. Index.jsp will be used to obtain the first name as well as the last name / surname of the users. For this case, textboxes should be adequate as first name and surname. However, it would be different case if we are required to get the country of origin of the users. The use of combobox would be more appropriate for choosing the country of origin as there are more than one choices to be chosen on. We are also required to create one more JSP file called greeting.jsp to greet the users. Hence, the flow would be index.jsp - GreetingServlet -> greeting.jsp. In short, index.jsp will first be displayed to users, the users then fill his or her first and surname in index.jsp and press Submit button. This information is sent to our Java Servlet and our Java Servlet redirects the users to the greeting.jsp.

In index.jsp, we need to have two textboxes for getting the user's input and a button to submit the information to our Java Servlet. After pressing the button, the user should be redirected into greeting page. Now, let's create the textbox. The textbox command would be the same as HTML command that is <input type="text" value="50"> and so on. Please remember that every textbox or components whose values would like to be passed into Java Servlet must be within <form></form> tag. Thus, please add below lines of codes into your index.jsp after the <h1></h1> tag.</p>

   
 
 <form action="GreetingServlet" method="POST">
        First Name: <input type="text" name="firstName" size="20"><br />
        Surname: <input type="text" name="surname" size="20">
        <br /><br />
        <input type="submit" value="Submit">
    </form>

 

 

Now, we have <form> and </form> HTML tag. Inside <form></form> tag, we need to specify few values such as action and method. Action is used to allow the JSP page knows which Java Servlet to be called on the invocation of submit button and the method is used to select the preferred way to pass your information to Java Servlet. This method attribute will be discussed further in the later phase.

We also have two textboxes now i.e <input type="text" name="firstName" size="20"> and <input type="text" name="surname" size="20">. There are few important things that you need to pay attention here. The name attribute for these textbox component are extremely important; in our index.jsp, it would be firstName and surname. These keywords are used to obtain the information in Java Servlet from the JSP page. It would be demonstrated in later phase once you have seen the implementation of the Java Servlet. The type is used to define what kind of component it is; text represents textboxes, button represents a button, image represents a picture and etc. The size is used to determine the width of the textbox. For more information, you can reference to the HTML tag which is available in Internet.

Okay, you must be wondering how the index.jsp looks like now when it has been executed. Let's deploy our JSP into the bundled Tomcat in NetBeans. Right-click your Web Application Project and choose Run Project. This menu first compiles and deploys the application to the Server and subsequently runs the application by executing its index.jsp. Yes, that is correct; it is just one click to run your Web Application within the NetBeans. Later on, if you have modified your JSP or your Java Servlet, you can merely re-deploy the application and all the changes will be reflected. You also need to refresh your Internet Browser.


Image

While running your Web Application Project, you may be prompted with a dialog box showing the progress of your Web Application project. If you carefully pay attention on the dialog box, they once display the message like "Starting Tomcat 5.5.7" and etc. Wait for a few seconds and your default Internet Browser will be launched and it should display your new index.jsp.

Below screenshot shows how the index.jsp should look like.


Image

We have completed our index.jsp. What we need to do now is to create our Java Servlet which is called GreetingServlet. Actually, the name of the Java Servlet can be anything as you want. The most important thing is how you map this Java Servlet in your web.xml to be accessible from your JSP. Well, web.xml is actually a deployment descriptor and it must always be present for each Java J2EE Web Application. For now, what you need to know is that every Java Servlet that you create must be registered in the web.xml file. Thus, this file may be getting bigger and bigger if the project is getting more complex. This will be described in the next phase.

To create your Java Servlet, you need to right-click your Source Packages section within your Web Application and choose New > Servlet as shown on below figures.


Image
Image

Again, a wizard should pop up for you to configure your Java Servlet. Your Java Servlet name can be anything but for this tutorial sample, let's name it GreetingServlet. If you want the Java Servlet to be on different name, you need to modify the mapping of your web.xml as well. This web.xml will be discussed in later phase. For now, we can keep the location be in the Source Packages. This Source Packages should only contain Java files. The reason we have this Source Packages is to assist us in maintaining our Web Application. Consider that if you have all the JSP, Java and other files in one folder, it would be hard for you or the new developers to track the flow of the applications.

For the Package, you can define any package that you want. Normally, we use Package to group a few Java files that has the same functionalities. For example, if I have StringUtil.java for String manipulation and EncodingAlgorithmUtil.java for encoding, I will locate them under the same package called "com.mycompanyname.util" as they both are actually utility classes. So as this is our first Java Servlet, let's create one package called "com.mycompany.servlet". Then press Next button.

Image

After pressing Next button, we are in the last step of configuring our Java Servlet. The last step is intended to map our Java Servlet in web.xml. Leave the checkbox as checked. It means that we want to apply the changes to web.xml where all the Java Servlets are registered. Remember that every Java Servlet that we create, we must register that particular Java Servlet in web.xml. Web.xml itself is actually a deployment descriptor. It contains the necessary configurations for our web application. Web.xml is not only used for Java Servlet but also for other purposes such as security, parameters and etc.

Back to the Java Servlet's configuration wizard, there are two fields available i.e. Servlet Name and URL Mapping. We need to set both of these variables. Servlet Name is used to associate our actual Java Servlet (which is Java class) into a name. The URL mapping is used to identify on how the Java Servlet should be called. This is the URL that is called in your <form></form> tag in JSP file. If you set the URL Mapping into /test/GreetingServlet, you need to call it as /test/GreetingServlet from your <form></form> tag. For our project, set it into /GreetingServlet. We have completed configuring our Java Servlet. You may also be interested to see how the web.xml looks like now. You can go to your Web Pages > WEB-INF > web.xml.

Now, if you see, you can see that there is one Java file created which is GreetingServlet.java as shown in below picture.


Image

This GreetingServlet.java contains our implementation of the Java Servlet. If you carefully pay attention to this file, you should realize that this class extends HttpServlet. So wherever you found Java classes that extends HttpServlet, those classes must definitely be a Java Servlet and there must be an entry in web.xml.

There are few Java methods created by default in GreetingServlet.java i.e.

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
protected void doGet(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response)

 

 

and many more.

However, let's focus on the doGet and doPost methods as these two methods are the most important. Do you remember that in our <form></form> tag, we actually specify the method attribute as POST? For your information, we can also set the method in the <form></form> tag into GET. If we specify it as POST, the doPost method will be called. On the other hand, if we specify the <form> tag as GET, doGet method will be executed. Then, what would be the difference between GET and POST?

Each method has its own advantages and disadvantages. GET has limited length for the information that is submitted but it is easily appended on the last URL of your Java Servlet. POST does not have any limitation of the length of information sent and it is hidden from the URL. For example, GET will display something like http://localhost:7001/MyFirstServlet/GreetingServlet?firstName=david&surname=test while POST would not display firstName and surname in the end of the URL. POST has URL like "http://localhost:7001/MyFirstServlet/GreetingServlet". It is obvious that GET may have some issues on security as everyone may clearly see the information sent to the Java Servlet. POST would be a better choice but sometimes, there would just be a situation where we need to use GET to make our development easier. I am sure that as you go along, you will meet a situation where you need to use GET for sending some information to Servlet.

As our JSP used POST, let's add some Java codes into our doPost method. Add these two lines into your doPost method so it should be like below.

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        String firstName = request.getParameter("firstName").toString();
        System.out.println("firstName = " + firstName);
        processRequest(request, response);
    }

    String firstName = request.getParameter("firstName").toString();

 

What does above code means? If you remember, the textbox that we created in our JSP contains the name attribute.

 

 

This is where the name attribute is useful. We can get the value entered by the user in the index.jsp by executing request.getParameter("firstName"). Remember that firstName is case sensitive so firstName is different with FirstName or firstname. The next line of code is used to print out the value into your Tomcat console.

 System.out.println("firstName = " + firstName);

 

 

You should be able to see the output in your Tomcat console in your NetBeans. Deploy your project again, refresh your Internet Browser and see what's happening now. As your Tomcat has run previously, you just need to re-deploy the project and simply refresh your browser.

Image

 <input type="text" name="firstName" size="20">

After you have pressed the submit button, the page will go blank. Yes, it is because we have not specified where Java Servlet should redirect. We will go to this later on. But if you see at the Tomcat logs, you will notice something interesting.


Image

Image

Now, you see that in the Tomcat console, there is "firstName = John" line displayed. This is executed and created by our Java Servlet. It also means that our Java Servlet has successfully been executed.

Okay, let's move to the last step. We need to greet the users.

Now, clear the doPost method and add some more codes to processRequest method as below.

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

        out.close();
    }

 

 

Let's see on what the codes do.

       String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

 


 

The two lines above are used to get the firstname and the lastname from our JSP.

Then, these two variables are used and displayed into JSP and located in below codes. The out.println(""); is used to render the HTML into JSP page.

      out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

 

You need to re-deploy your Web Application and refresh your Internet Browser. Go to index.jsp and provide first name and surname and press Submit button. Now, you will see a page that greets the user. Congratulations, you have successfully created your Java Servlet.

Conclusion

Well, I am sure that you now have been able to create a Servlet using NetBeans. By reading this tutorial, you should be able to send information to Java Servlet, know how to get this information from your Java Servlet and redirect the user to the success page. However, you should practice more and more as your skills will be improved along your experiences. There are still a lot of things in Java world that you need to know such as Filter, Listener, Struts, EJB and etc. If you grab the concept, you are good to go to the next level. I wish you all the best luck.

You can find the NetBeans project for the tutorial source codes here.
The README file for the sources is available here.

Introduction

Java Servlet is the one of the most important Java technologies. It is the simplest model to build a complete Java J2EE Web Application. Furthermore, even for complex J2EE Web Application that uses Struts, Spring, EJB and etc, they are still using Servlet for certain purposes such as Servlet Filter, Listener and etc. Thus, it is just a good idea for you to have well-built understanding of Java Servlet. Prior reading this tutorial, it would be excellent if you have mastered the basic Java programming languages.

At the completion of the tutorial, you are expected to comprehend the concept of the Java Servlet, be familiar with the ways to create Java Servlet using NetBeans 5.0, differences between POST and GET and should be ready to go to the next level.

In this tutorial, we are going to create one dynamic web application that asks the user for first name and surname. Then the system should response by greeting the users.

The tutorial consists of four main steps.

  1. Introduction to NetBeans 5.0
  2. Creating New Web Application Project in NetBeans 5.0
  3. Implementation of Tutorial's Example
  4. Conclusion
   
 

Introduction to NetBeans 5.0

Nowadays, NetBeans is one of the most powerful Java programming IDE. Other popular Java IDEs are also available in the market such as Eclipse, Bea WebLogic Workshop, IBM WebSphere Application Development (WSAD) and etc. Creating and implementing Java Servlet using NetBeans is extremely straightforward and simple. This is one of the reasons why NetBeans rapidly grow its popularity. Additionally, it has Tomcat bundled together within the NetBeans hence compiling and deploying Java Servlet is just a few clicks on your mouse. Well, without going any further, let's start our tutorial.

Creating New Web Application Project in NetBeans 5.0

Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). JSP is actually a HTML but unlike HTML, JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In short words, we may represent JSP as dynamic HTML. In Java J2EE Web Application, JSP plays as a front-end while Java Servlet is the controller that contains the business logics, complex algorithms and etc.

For example, consider "Online University Student Registration System" developed in Java J2EE Web Application, the registration page where you fill in your details such as your name, your address, your username and etc are actually a JSP page. Later on, when you have completed filling out all the details and you press the submit button, all the information will be sent to Java Servlet for further processes. Java Servlet receives this information, does the necessary processes such as validations, generating user id and etc and then keeps the information to database. After successfully saving the data to database, Java Servlet redirects the user to the success page where the user can log in to the system. Likewise, if there is an unexpected error occurred happening in the middle of student registration system's process, the user will be redirected to the error page.

Okay, without any more delay, let's get ready for our tutorial. Start your NetBeans 5.0. After it has been completely started, it should look like below screenshots.


Image

Image

First, we have to create a new Web Application Project for our Java Servlet. This Web Application contains all the JSP pages as well as our Servlet classes. To create a new Web Application in NetBeans 5.0, you can go to the menu and choose File > New Project. A wizard will instantly be displayed to you and you are required to provide some information to configure your Web Application.


Image

As the wizard is displayed as shown on above illustration, choose Web on the left panel and Web Application on the right panel and click Next button. All the other options are used to develop other kind of projects in NetBeans and irrelevant for our tutorial.


Image

In the next step or the second step of configuring our Web Application, you can provide your Web Application a name. Well, please feel free to name it whatever you want. In this case, to make it self-explanatory, I name our Web Application as MyFirstServlet as shown in the above illustration. In the middle of the wizard, there is an option called Server and it has the value of Bundled (Tomcat 5.5.7). It demonstrates that NetBeans 5.0 will use its bundled Tomcat as the default server. Other configuration should remain the same and press Finish button. You can also press the Next button to go to the last page where you can define the frameworks that you would like to use as shown in below illustration. However, we can skip the last step as we do not use any framework for our Java Servlet. Okay, we have completed our configuration of Web Application and we are ready to implement our first Java Servlet. Grab your coffee and we are ready to go.


Image

After completing the Web Application's configuration, you should have a screen similar as below. It will also create one default JSP file called index.jsp on your Web Pages folder.


Image

Implementation of Tutorial's Example

For our tutorial, we are going to use index.jsp to demonstrate how to implement Java Servlet that greets the users. Index.jsp will be used to obtain the first name as well as the last name / surname of the users. For this case, textboxes should be adequate as first name and surname. However, it would be different case if we are required to get the country of origin of the users. The use of combobox would be more appropriate for choosing the country of origin as there are more than one choices to be chosen on. We are also required to create one more JSP file called greeting.jsp to greet the users. Hence, the flow would be index.jsp - GreetingServlet -> greeting.jsp. In short, index.jsp will first be displayed to users, the users then fill his or her first and surname in index.jsp and press Submit button. This information is sent to our Java Servlet and our Java Servlet redirects the users to the greeting.jsp.

In index.jsp, we need to have two textboxes for getting the user's input and a button to submit the information to our Java Servlet. After pressing the button, the user should be redirected into greeting page. Now, let's create the textbox. The textbox command would be the same as HTML command that is <input type="text" value="50"> and so on. Please remember that every textbox or components whose values would like to be passed into Java Servlet must be within <form></form> tag. Thus, please add below lines of codes into your index.jsp after the <h1></h1> tag.</p>

   
 
 <form action="GreetingServlet" method="POST">
        First Name: <input type="text" name="firstName" size="20"><br />
        Surname: <input type="text" name="surname" size="20">
        <br /><br />
        <input type="submit" value="Submit">
    </form>

 

 

Now, we have <form> and </form> HTML tag. Inside <form></form> tag, we need to specify few values such as action and method. Action is used to allow the JSP page knows which Java Servlet to be called on the invocation of submit button and the method is used to select the preferred way to pass your information to Java Servlet. This method attribute will be discussed further in the later phase.

We also have two textboxes now i.e <input type="text" name="firstName" size="20"> and <input type="text" name="surname" size="20">. There are few important things that you need to pay attention here. The name attribute for these textbox component are extremely important; in our index.jsp, it would be firstName and surname. These keywords are used to obtain the information in Java Servlet from the JSP page. It would be demonstrated in later phase once you have seen the implementation of the Java Servlet. The type is used to define what kind of component it is; text represents textboxes, button represents a button, image represents a picture and etc. The size is used to determine the width of the textbox. For more information, you can reference to the HTML tag which is available in Internet.

Okay, you must be wondering how the index.jsp looks like now when it has been executed. Let's deploy our JSP into the bundled Tomcat in NetBeans. Right-click your Web Application Project and choose Run Project. This menu first compiles and deploys the application to the Server and subsequently runs the application by executing its index.jsp. Yes, that is correct; it is just one click to run your Web Application within the NetBeans. Later on, if you have modified your JSP or your Java Servlet, you can merely re-deploy the application and all the changes will be reflected. You also need to refresh your Internet Browser.


Image

While running your Web Application Project, you may be prompted with a dialog box showing the progress of your Web Application project. If you carefully pay attention on the dialog box, they once display the message like "Starting Tomcat 5.5.7" and etc. Wait for a few seconds and your default Internet Browser will be launched and it should display your new index.jsp.

Below screenshot shows how the index.jsp should look like.


Image

We have completed our index.jsp. What we need to do now is to create our Java Servlet which is called GreetingServlet. Actually, the name of the Java Servlet can be anything as you want. The most important thing is how you map this Java Servlet in your web.xml to be accessible from your JSP. Well, web.xml is actually a deployment descriptor and it must always be present for each Java J2EE Web Application. For now, what you need to know is that every Java Servlet that you create must be registered in the web.xml file. Thus, this file may be getting bigger and bigger if the project is getting more complex. This will be described in the next phase.

To create your Java Servlet, you need to right-click your Source Packages section within your Web Application and choose New > Servlet as shown on below figures.


Image
Image

Again, a wizard should pop up for you to configure your Java Servlet. Your Java Servlet name can be anything but for this tutorial sample, let's name it GreetingServlet. If you want the Java Servlet to be on different name, you need to modify the mapping of your web.xml as well. This web.xml will be discussed in later phase. For now, we can keep the location be in the Source Packages. This Source Packages should only contain Java files. The reason we have this Source Packages is to assist us in maintaining our Web Application. Consider that if you have all the JSP, Java and other files in one folder, it would be hard for you or the new developers to track the flow of the applications.

For the Package, you can define any package that you want. Normally, we use Package to group a few Java files that has the same functionalities. For example, if I have StringUtil.java for String manipulation and EncodingAlgorithmUtil.java for encoding, I will locate them under the same package called "com.mycompanyname.util" as they both are actually utility classes. So as this is our first Java Servlet, let's create one package called "com.mycompany.servlet". Then press Next button.

Image

After pressing Next button, we are in the last step of configuring our Java Servlet. The last step is intended to map our Java Servlet in web.xml. Leave the checkbox as checked. It means that we want to apply the changes to web.xml where all the Java Servlets are registered. Remember that every Java Servlet that we create, we must register that particular Java Servlet in web.xml. Web.xml itself is actually a deployment descriptor. It contains the necessary configurations for our web application. Web.xml is not only used for Java Servlet but also for other purposes such as security, parameters and etc.

Back to the Java Servlet's configuration wizard, there are two fields available i.e. Servlet Name and URL Mapping. We need to set both of these variables. Servlet Name is used to associate our actual Java Servlet (which is Java class) into a name. The URL mapping is used to identify on how the Java Servlet should be called. This is the URL that is called in your <form></form> tag in JSP file. If you set the URL Mapping into /test/GreetingServlet, you need to call it as /test/GreetingServlet from your <form></form> tag. For our project, set it into /GreetingServlet. We have completed configuring our Java Servlet. You may also be interested to see how the web.xml looks like now. You can go to your Web Pages > WEB-INF > web.xml.

Now, if you see, you can see that there is one Java file created which is GreetingServlet.java as shown in below picture.


Image

This GreetingServlet.java contains our implementation of the Java Servlet. If you carefully pay attention to this file, you should realize that this class extends HttpServlet. So wherever you found Java classes that extends HttpServlet, those classes must definitely be a Java Servlet and there must be an entry in web.xml.

There are few Java methods created by default in GreetingServlet.java i.e.

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
protected void doGet(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response)

 

 

and many more.

However, let's focus on the doGet and doPost methods as these two methods are the most important. Do you remember that in our <form></form> tag, we actually specify the method attribute as POST? For your information, we can also set the method in the <form></form> tag into GET. If we specify it as POST, the doPost method will be called. On the other hand, if we specify the <form> tag as GET, doGet method will be executed. Then, what would be the difference between GET and POST?

Each method has its own advantages and disadvantages. GET has limited length for the information that is submitted but it is easily appended on the last URL of your Java Servlet. POST does not have any limitation of the length of information sent and it is hidden from the URL. For example, GET will display something like http://localhost:7001/MyFirstServlet/GreetingServlet?firstName=david&surname=test while POST would not display firstName and surname in the end of the URL. POST has URL like "http://localhost:7001/MyFirstServlet/GreetingServlet". It is obvious that GET may have some issues on security as everyone may clearly see the information sent to the Java Servlet. POST would be a better choice but sometimes, there would just be a situation where we need to use GET to make our development easier. I am sure that as you go along, you will meet a situation where you need to use GET for sending some information to Servlet.

As our JSP used POST, let's add some Java codes into our doPost method. Add these two lines into your doPost method so it should be like below.

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        String firstName = request.getParameter("firstName").toString();
        System.out.println("firstName = " + firstName);
        processRequest(request, response);
    }

    String firstName = request.getParameter("firstName").toString();

 

What does above code means? If you remember, the textbox that we created in our JSP contains the name attribute.

 

 

This is where the name attribute is useful. We can get the value entered by the user in the index.jsp by executing request.getParameter("firstName"). Remember that firstName is case sensitive so firstName is different with FirstName or firstname. The next line of code is used to print out the value into your Tomcat console.

 System.out.println("firstName = " + firstName);

 

 

You should be able to see the output in your Tomcat console in your NetBeans. Deploy your project again, refresh your Internet Browser and see what's happening now. As your Tomcat has run previously, you just need to re-deploy the project and simply refresh your browser.

Image

 <input type="text" name="firstName" size="20">

After you have pressed the submit button, the page will go blank. Yes, it is because we have not specified where Java Servlet should redirect. We will go to this later on. But if you see at the Tomcat logs, you will notice something interesting.


Image

Image

Now, you see that in the Tomcat console, there is "firstName = John" line displayed. This is executed and created by our Java Servlet. It also means that our Java Servlet has successfully been executed.

Okay, let's move to the last step. We need to greet the users.

Now, clear the doPost method and add some more codes to processRequest method as below.

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

        out.close();
    }

 

 

Let's see on what the codes do.

       String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

 


 

The two lines above are used to get the firstname and the lastname from our JSP.

Then, these two variables are used and displayed into JSP and located in below codes. The out.println(""); is used to render the HTML into JSP page.

      out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () + "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

 

You need to re-deploy your Web Application and refresh your Internet Browser. Go to index.jsp and provide first name and surname and press Submit button. Now, you will see a page that greets the user. Congratulations, you have successfully created your Java Servlet.

Conclusion

Well, I am sure that you now have been able to create a Servlet using NetBeans. By reading this tutorial, you should be able to send information to Java Servlet, know how to get this information from your Java Servlet and redirect the user to the success page. However, you should practice more and more as your skills will be improved along your experiences. There are still a lot of things in Java world that you need to know such as Filter, Listener, Struts, EJB and etc. If you grab the concept, you are good to go to the next level. I wish you all the best luck.

You can find the NetBeans project for the tutorial source codes here.
The README file for the sources is available here.