Introduction to Servlets Servlets are Java technology’s answer to Common Gateway Interface (CGI).

They are programs that run on a Web server, acting as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Servlets are used to do: Read any data sent by the user. This data is usually entered in a form on a Web page, but could also come from a Java applet or a custom HTTP client program. To See any other information about the request that is embedded in the HTTP request. This information includes details about browser capabilities, cookies, the host name of the requesting client, and so forth. Generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a legacy application, or computing the response directly. Format the results inside a document. In most cases, this involves embedding the information inside an HTML page. Set the appropriate HTTP response parameters. This means telling the browser what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Send the document back to the client. This document may be sent in text format (HTML), binary format (GIF images), or even in a compressed format like gzip that is layered on top of some other underlying format. Servlets are not restricted to Web or application servers that handle HTTP requests, but can be used for other types of servers as well. For example, servlets could be embedded in mail or FTP servers to extend their functionality. The Advantages of Servlets Java servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies. Following are the advantages Efficient With CGI, a new process is started for each HTTP request. So the overhead of starting the process can dominate the execution time. In servlets, the Java Virtual Machine stays running and handles each request using a lightweight Java thread, not a heavyweight operating system process. if there are N simultaneous requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads but only a single copy of the servlet class.

Page 1

Last update: 4 October 2011

with the major exception of Apache. simplifying techniques like session tracking and caching of previous computations. They are now part of the Java 2 Platform. Secure As servlets are written in java. we can add servlet support to it. or StarNine WebStar. This is in contrast to many of the other CGI alternatives. handling cookies. servlets inherit the strong type safety of java language. where as regular CGI programs cannot. for instance. Portable Servlets are written in the Java programming language and follow a standard API. Multiple servlets can also share data. reading and setting HTTP headers. so industry support for servlets is becoming even more pervasive. Servlets can talk directly to the Web server. I-Planet Enterprise Server can run virtually unchanged on Apache. servlets written for. However. Powerful Servlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Nevertheless. Now watch the video tutorial at http://www. Communicating with the Web server makes it easier to translate relative URLs into concrete path names. say. Microsoft Internet Information Server (IIS). Enterprise Edition . IBM In fact. and many other such high-level utilities. once we have a Web server.Convenient Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data. tracking sessions. making it easy to implement database connection pooling and similar resource-sharing optimizations. most commercial-quality Web servers are relatively expensive. Page 2 Last update: 4 October 2011 . at least not without using a server-specific API. Inexpensive There are a number of free or very inexpensive Web servers available that are good for “personal” use or low-volume Web sites. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. Servlets can also maintain information from request to request. which is free. which require a significant initial investment to purchase a proprietary package. If any exception occurs then it will throw an exception. servlets are supported directly or by a plug-in on virtually every major Web server. In servlets we can easily handle the errors due to Java's exception handling mechanism.

it has Tomcat bundled together within the NetBeans hence compiling and deploying Java Servlet is just a few clicks on your mouse. The tutorial consists of four main steps. It is the simplest model to build a complete Java J2EE Web Application. be familiar with the ways to create Java Servlet using NetBeans 5.0 Nowadays. it is just a good idea for you to have well-built understanding of Java Servlet. 3. IBM WebSphere Application Development (WSAD) and etc. This is one of the reasons why NetBeans rapidly grow its popularity. Then the system should response by greeting the users. 4. let’s start our tutorial. Spring.0 Implementation of Tutorial’s Example Conclusion Introduction to NetBeans 5. differences between POST and GET and should be ready to go to the next level. In Java J2EE Web Application. we are going to create one dynamic web application that asks the user for first name and surname. EJB and etc. Prior reading this tutorial. complex algorithms and etc. JSP plays as a front-end while Java Servlet is the controller that contains the business logics. they are still using Servlet for certain purposes such as Servlet Filter. even for complex J2EE Web Application that uses Struts. 1. it would be excellent if you have mastered the basic Java programming languages. Bea WebLogic Workshop.Java Servlet technology is the one of the most important Java technologies. 2. without going any further. Thus.0 Creating New Web Application Project in NetBeans 5. Other popular Java IDEs are also available in the market such as Eclipse. Creating and implementing Java Servlet using NetBeans is extremely straightforward and simple. Page 3 Last update: 4 October 2011 .0 Creating a Java Servlet means that you are required to deal with JSP (JavaServer Pages). Additionally. you are expected to comprehend the concept of the Java Servlet.0. NetBeans is one of the most powerful Java programming IDE. Well. Furthermore. Listener and etc. At the completion of the tutorial. Creating New Web Application Project in NetBeans 5. In short words. JSP is actually a HTML but unlike HTML. we may represent JSP as dynamic HTML. Introduction to NetBeans 5. JSP may have Java codes (usually we call it as Scriptlet) embedded in it. In this tutorial.

generating user id and etc and then keeps the information to database. Okay. it should look like below screenshots. your username and etc are actually a JSP page. Java Servlet receives this information. Java Servlet redirects the user to the success page where the user can log in to the system. Likewise. let’s get ready for our tutorial. does the necessary processes such as validations. Later on. consider “Online University Student Registration System” developed in Java J2EE Web Application.For example. your address. the user will be redirected to the error page. if there is an unexpected error occurred happening in the middle of student registration system’s process.0. the registration page where you fill in your details such as your name. without any more delay. 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. After it has been completely started. Start your NetBeans 5. After successfully saving the data to database. Page 4 Last update: 4 October 2011 .

First.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. Page 5 Last update: 4 October 2011 . 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.

I name our Web Application as MyFirstServlet as shown in the above illustration. All the other options are used to develop other kind of projects in NetBeans and irrelevant for our tutorial.As the wizard is displayed as shown on above illustration. we have completed our configuration of Web Application and we are ready to implement our first Java Servlet. please feel free to name it whatever you want. you can provide your Web Application a name. In this case. In the next step or the second step of configuring our Web Application. there is an option called Server and it has the value of Bundled (Tomcat 5. 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. Well.5.0 will use its bundled Tomcat as the default server.7). we can skip the last step as we do not use any framework for our Java Servlet. In the middle of the wizard. Okay. However. to make it self-explanatory. It demonstrates that NetBeans 5. Page 6 Last update: 4 October 2011 . choose Web on the left panel and Web Application on the right panel and click Next button. Grab your coffee and we are ready to go.

It will also create one default JSP file called index.jsp on your Web Pages folder.After completing the Web Application’s configuration. Page 7 Last update: 4 October 2011 . you should have a screen similar as below.

GreetingServlet -> greeting. in our index.jsp. This information is sent to our Java Servlet and our Java Servlet redirects the users to the greeting. We are also required to create one more JSP file called greeting. We also have two textboxes now i.jsp to demonstrate how to implement Java Servlet that greets the users. Thus.jsp will first be displayed to users.</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. the users then fill his or her first and surname in index. These Page 8 Last update: 4 October 2011 . it would be firstName and surname. However. we need to have two textboxes for getting the user’s input and a button to submit the information to our Java Servlet.jsp.For our tutorial. Index.jsp and press Submit button.jsp. we need to specify few values such as action and method. it would be different case if we are required to get the country of origin of the users. index.jsp .e <input type="text" name="firstName" size="20"> and <input type="text" name="surname" size="20">. please add below lines of codes into your index.jsp to greet the users. 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.jsp after the <h1></h1> tag. textboxes should be adequate as first name and surname. let’s create the textbox. Inside <form></form> tag. For this case. Hence. After pressing the button. There are few important things that you need to pay attention here.jsp. Please remember that every textbox or components whose values would like to be passed into Java Servlet must be within <form></form> tag. we are going to use index. the flow would be index. In index. Now. The textbox command would be the same as HTML command that is <input type=”text” value=”50”> and so on. In short. This method attribute will be discussed further in the later phase. 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. the user should be redirected into greeting page.jsp will be used to obtain the first name as well as the last name / surname of the users. we have <form> and </form> HTML tag. The name attribute for these textbox component are extremely important.

they once display the message like “Starting Tomcat 5. You also need to refresh your Internet Browser. Right-click your Web Application Project and choose Run Project.jsp. It would be demonstrated in later phase once you have seen the implementation of the Java Servlet. Yes. If you carefully pay attention on the dialog box. it is just one click to run your Web Application within the NetBeans. button represents a button.keywords are used to obtain the information in Java Servlet from the JSP page.jsp looks like now when it has been executed. that is correct. Later on. Below screenshot shows how the index. The size is used to determine the width of the textbox.7” and etc. For more information. Wait for a few seconds and your default Internet Browser will be launched and it should display your new index.jsp. Okay.jsp should look like. you may be prompted with a dialog box showing the progress of your Web Application project. you must be wondering how the index. This menu first compiles and deploys the application to the Server and subsequently runs the application by executing its index. text represents textboxes. While running your Web Application Project. Let’s deploy our JSP into the bundled Tomcat in NetBeans. you can merely re-deploy the application and all the changes will be reflected.5. Page 9 Last update: 4 October 2011 . The type is used to define what kind of component it is. you can reference to the HTML tag which is available in Internet. image represents a picture and etc. if you have modified your JSP or your Java Servlet.

this file may be getting bigger and bigger if the project is getting more complex.xml to be accessible from your JSP.xml is actually a deployment descriptor and it must always be present for each Java J2EE Web Application. What we need to do now is to create our Java Servlet which is called GreetingServlet.xml file. web. Actually.jsp.We have completed our index. what you need to know is that every Java Servlet that you create must be registered in the web. Page 10 Last update: 4 October 2011 . This will be described in the next phase. For now. Well. To create your Java Servlet. Thus. you need to right-click your Source Packages section within your Web Application and choose New > Servlet as shown on below figures. The most important thing is how you map this Java Servlet in your web. the name of the Java Servlet can be anything as you want.

Page 11 Last update: 4 October 2011 .

So as this is our first Java Servlet. Remember that every Java Servlet that we for encoding. Consider that if you have all the JSP. if I have StringUtil.xml will be discussed in later phase. Normally.util” as they both are actually utility classes. you need to modify the mapping of your web.xml where all the Java Servlets are registered. This web.Again. Page 12 Last update: 4 October 2011 . Your Java Servlet name can be anything but for this tutorial sample. Then press Next button. parameters and etc. a wizard should pop up for you to configure your Java Servlet. you can define any package that you want. If you want the Java Servlet to be on different for String manipulation and EncodingAlgorithmUtil. After pressing Next button. For the Package. Web.mycompany.xml. For example. Java and other files in one folder. Leave the checkbox as checked. The last step is intended to map our Java Servlet in web.xml is not only used for Java Servlet but also for other purposes such as security. let’s name it GreetingServlet. It means that we want to apply the changes to web.xml. we must register that particular Java Servlet in web. The reason we have this Source Packages is to assist us in maintaining our Web Application. This Source Packages should only contain Java files.xml as well.mycompanyname. it would be hard for you or the new developers to track the flow of the applications. we use Package to group a few Java files that has the same functionalities.xml itself is actually a deployment descriptor.servlet”. Web. we are in the last step of configuring our Java Servlet. For now. we can keep the location be in the Source Packages. It contains the necessary configurations for our web application. I will locate them under the same package called “com. let’s create one package called “com.

Servlet Name is used to associate our actual Java Servlet (which is Java class) into a name. protected void processRequest(HttpServletRequest contains our implementation of the Java Servlet.e. You can go to your Web Pages > WEB-INF > web. For our project. HttpServletResponse response) protected void doGet(HttpServletRequest request. So wherever you found Java classes that extends HttpServlet. there are two fields available i. This GreetingServlet. if you see.xml looks like now. Now. If you set the URL Mapping into /test/GreetingServlet. We need to set both of these variables. those classes must definitely be a Java Servlet and there must be an entry in web. HttpServletResponse response) protected void doPost(HttpServletRequest request. This is the URL that is called in your <form></form> tag in JSP file.Back to the Java Servlet’s configuration wizard. HttpServletResponse response) Page 13 Last update: 4 October 2011 . The URL mapping is used to identify on how the Java Servlet should be called. If you carefully pay attention to this i.e. Servlet Name and URL Mapping. you should realize that this class extends HttpServlet.xml. you need to call it as /test/GreetingServlet from your <form></form> tag. We have completed configuring our Java Servlet. set it into /GreetingServlet. There are few Java methods created by default in GreetingServlet.xml. you can see that there is one Java file created which is as shown in below picture. You may also be interested to see how the web.

GET has limited length for the information that is submitted but it is easily appended on the last URL of your Java Servlet. On the other hand. processRequest(request.getParameter("firstName"). Then. However. I am sure that as you go along. POST would be a better choice but sometimes.out. let’s focus on the doGet and doPost methods as these two methods are the most important. you will meet a situation where you need to use GET for sending some information to Servlet. what would be the difference between GET and POST? Each method has its own advantages and disadvantages. POST has URL like “http://localhost:7001/MyFirstServlet/GreetingServlet”. there would just be a situation where we need to use GET to make our development easier.println("firstName = " + firstName).toString(). For example. If we specify it as POST. 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.toString().getParameter("firstName"). let’s add some Java codes into our doPost method. Do you remember that in our <form></form> tag. doGet method will be executed. HttpServletResponse response) throws ServletException. Page 14 Last update: 4 October 2011 . POST does not have any limitation of the length of information sent and it is hidden from the URL. As our JSP used POST. protected void doPost(HttpServletRequest request. Add these two lines into your doPost method so it should be like below. System. response). IOException { String firstName = request. the doPost method will be called. } String firstName = request. if we specify the <form> tag as GET.and many more. It is obvious that GET may have some issues on security as everyone may clearly see the information sent to the Java Servlet. we actually specify the method attribute as POST? For your information. we can also set the method in the <form></form> tag into GET.

What does above code means? If you remember. You should be able to see the output in your Tomcat console in your NetBeans. refresh your Internet Browser and see what’s happening now. <input type="text" name="firstName" size="20"> This is where the name attribute is useful. you just need to re-deploy the project and simply refresh your browser. As your Tomcat has run previously.getParameter(“firstName”).out. The next line of code is used to print out the value into your Tomcat console. Page 15 Last update: 4 October 2011 . We can get the value entered by the user in the index. System. Deploy your project again.jsp by executing request. the textbox that we created in our JSP contains the name attribute.println("firstName = " + firstName). Remember that firstName is case sensitive so firstName is different with FirstName or firstname.

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

Now. let’s move to the last step. This is executed and created by our Java Servlet. IOException { Page 17 Last update: 4 October 2011 . you see that in the Tomcat console. It also means that our Java Servlet has successfully been executed. clear the doPost method and add some more codes to processRequest method as below. protected void processRequest(HttpServletRequest request. there is “firstName = John” line displayed. Okay.Now. We need to greet the users. HttpServletResponse response) throws ServletException.

toString().toString(). PrintWriter out = response.toString().getParameter("firstName"). The two lines above are used to get the firstname and the lastname from our JSP. out.println("<title>Servlet GreetingServlet</title>"). out.println("</body>"). out. out.setContentType("text/html. out.response.close().println("<p>Welcome " + firstName + " " + surname + "</p>").getParameter("surname"). out.println("<head>"). String firstName = request. out.getWriter().println("<h1>Servlet GreetingServlet at " + request. Page 18 Last update: 4 October 2011 . String surname = request.println("<body>").getParameter("firstName"). out. String surname = request.toString().getParameter("surname").println("<html>"). out.println("</head>"). } Let’s see on what the codes do. out.println("</html>").getContextPath () + "</h1>"). String firstName = request.charset=UTF-8").

println("<title>Servlet GreetingServlet</title>"). out.println("</head>"). these two variables are used and displayed into JSP and located in below codes. You need to re-deploy your Web Application and refresh your Internet Browser.println(“”). Struts. If you grab the concept. Go to index. out. you will see a page that greets the user. Congratulations.println("</html>"). you have successfully created your Java Servlet. out. is used to render the HTML into JSP page.Then. you should be able to send information to Java Servlet. out.jsp and provide first name and surname and press Submit button. By reading this tutorial.println("<html>"). However.getContextPath () + "</h1>"). you should practice more and more as your skills will be improved along your experiences. The out.println("<p>Welcome " + firstName + " " + surname + "</p>"). Now.println("<h1>Servlet GreetingServlet at " + request. There are still a lot of things in Java world that you need to know such as Filter. you are good to go to the next level. Source: http://www. EJB and etc. know how to get this information from your Java Servlet and redirect the user to the success page.html Accessed: 08/08/11 Page 19 Last update: 4 October 2011 . I wish you all the best luck.println("<body>"). out. out. Listener. Conclusion Well. I am sure that you now have been able to create a Servlet using NetBeans. out.println("</body>").println("<head>").

Sign up to vote on this title
UsefulNot useful