Week 3 Lab
Week 3 Lab
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
Convenient Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. Powerful Servlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, where as regular CGI programs cannot, at least not without using a server-specific API. Communicating with the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations. Portable Servlets are written in the Java programming language and follow a standard API. Consequently, servlets written for, say, I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft Internet Information Server (IIS), IBM WebSphere, or StarNine WebStar. In fact, servlets are supported directly or by a plug-in on virtually every major Web server. They are now part of the Java 2 Platform, Enterprise Edition , so industry support for servlets is becoming even more pervasive. Secure As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. Inexpensive There are a number of free or very inexpensive Web servers available that are good for personal use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once we have a Web server, we can add servlet support to it. This is in contrast to many of the other CGI alternatives, which require a significant initial investment to purchase a proprietary package. Now watch the video tutorial at http://www.youtube.com/watch?v=Q6b3ZYKngXA
Page 2
Java Servlet technology 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. 2. 3. 4. Introduction to NetBeans 5.0 Creating New Web Application Project in NetBeans 5.0 Implementation of Tutorials Example 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, lets 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.
Page 3
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 systems process, the user will be redirected to the error page. Okay, without any more delay, lets get ready for our tutorial. Start your NetBeans 5.0. After it has been completely started, it should look like below screenshots.
Page 4
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.
Page 5
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.
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.
Page 6
After completing the Web Applications 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.
Page 7
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 users 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, lets 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
Page 8 Last update: 4 October 2011
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. Lets 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.
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.
Page 9
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.
Page 10
Page 11
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, lets 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, lets create one package called com.mycompany.servlet. Then press Next button.
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.
Page 12
Back to the Java Servlets 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.
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)
Page 13
and many more. However, lets 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, lets 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); }
Page 14
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.
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 whats happening now. As your Tomcat has run previously, you just need to re-deploy the project and simply refresh your browser.
Page 15
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.
Page 16
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, lets 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.
Page 17
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(); }
The two lines above are used to get the firstname and the lastname from our JSP.
Page 18
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. Source: http://www.java-tips.org/java-tutorials/tutorials/introduction-to-java-servlets-withnetbeans.html Accessed: 08/08/11
Page 19