Creating Servlet Using NetBeans IDE -


NetBeans IDE -

NetBeans is a popular IDE to create java applications. You can download latest version of NetBeans IDE from the NetBeans website - https://netbeans.org/downloads/index.html
Note- By default NetBeans only install GlassFish Server. At the time of NetBeans installation you can also install Tomcat server by following these steps -
a- Click on the Customize button in NetBeans installer window -



b- It will open a new window where you will find that Apache Tomcat option is unselected, select this option too and click on OK button.



Here we are using NetBeans IDE 8.2, The step by step process of using NetBeans to create and run Servlet applications is as follows -

1- Open the NetBeans and go to File -> New Project, It will open a New Project Window as shown below -



2- From Categories select Java Web option and from Projects select Web Application and click on Next. It will open a new window as follows -



This windows allows you to enter Project name and location, Enter desired project name, and here we used “MyFirstServletDemo”. You can also change Project storage location if you want, otherwise leaves them as it is. Here we have not changed it. And click on Next
3- This windows allows you to change the server settings. Click in Server drop down list and select desired server. And leave other options as it is.



Note - You can switch to another server from this window if your server not runs because of some reasons.
4- Click on Next and next window will ask you for Frameworks. Right now we are not using any framework so leave it as it is and click on finish.



5- Now our Project has created with index.html default page (welcome page), It will have the following structure -



Note- if you are using NetBeans older versions the default page may be index.jsp.
6- Open index.html page and make changes to it as shown below -

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
      <a href="test">Click here to go to servlet</a>
    </body>
</html>
       
7- Right Click on Source Package and go to New -> Java Package.

8- It will open New Java Package window, enter package name and enter Finish.In our example package name is servs.



9- Right click on created package (servs in our case) and go to New -> Java Class.



10- It will open New Java Class window, enter class name and enter Finish.In our example class name is MyServlet1.



11- Add the following code to 'MyServlet1' class -
package servs;

import java.io.*;
import javax.servlet.*;

public class MyServlet1 implements Servlet
{
    
private ServletConfig sc;   
    
 public void init(ServletConfig config)throws ServletException
 {
     sc = config;
 }
 
 public ServletConfig getServletConfig()
 {
     return sc;
 }
 
 public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException
 {
     try
     {
         response.setContentType("text/html");     
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>Welcome to Servlet</h1>");
         out.println("</body>");
         out.println("</html>");
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public String getServletInfo()
 {
     return "Info";
 }
 
 public void destroy()
 {
     
 }
}    
Program Description -
  • To convert 'MyServlet1' class into servlet, class implements 'Servlet' interface. As we already know Servlet interface contains 5 methods, so override these methods.
  • Except service() method, all the remaining 4 methods have the same above implementation in all programs.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the service() method that gets executed. So service() method will change in all program according to your requirements. Whatever output produced by servlet will be the output of your service() method. In this example it creates a simple html page with output 'Welcome to Servlet'.
  • service() method has 2 parameters- ServletRequest request and ServletResponse response - these corresponds to client request and response generated by server for the coming request.
  • response.setContentType("text/html"); - ServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.

11- Right Click on your project and go to New -> Other.



12- It will open a new window, select Web fromCategories and select Standard Deployment Descriptor (web.xml) from File Type. And click on Next.



13- Leave every things to its default values and click on Finish.



And it will create web.xml file in Configuration Files folder. 14- Open the web.xml file contained in Configuration Files folder and add the following code within web-app -
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    
</web-app>  
web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Descriptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyServlet1' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
For mapping client known public url('test' in our example) and servlet class name('MyServlet1' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your orignal servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyServlet1' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyServlet1</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url.It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, because in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         

15- To run your Project click on Run Project button from top toolbar.



16- Now it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -