Practice Labs with NetBEans IDE 6



Practice Labs with NetBEans IDE 6.X

You will have a number of labs which will help you to understand better about the concepts of Java Servlets. Lab 1 shows the detailed steps to download and install the Servlet execution environments and their configurations. Lab 2 gives a simple Servlet application which converts a temperature from Fahrenheit to Celsius. Lab 3 depicts how one Servlet can collaborate with other Servlets to accomplish a task. The last lab demonstrates a simple example in Java Servlet session tracking showing how to distinguish different sessions during a Web application. All the labs have been tested in Tomcat 5 with Servlet 2.4. Because of the platform independence feature of Java technology, you can implement the labs on any platform. We implemented them on Windows XP.

3.5.1 Develop Java Servelt with NetBEans IDE

Installation of Net beans 6.9:

• Before you install the IDE, the Java SE Development Kit (JDK) 5 (version 1.5.or newer JDK 6 )must be installed on your system. If you do not have an installation of JDK, you cannot proceed with the installation. You can download the latest JDK version at .

• You can download the Net beans from make sure you choose the “all” version to download which has Apache Tomcat 6.x..

• After the download completes, run the installer for Windows, the installer executable file has the .exe extension. Double-click the installer file to run it.

• Even if we have download the Net beans bundle have Apache Tomcat we still need to select it to install it. To choose the tools and runtimes to install, perform the following steps at the Welcome page of the installation wizard:

o Click Customize.

o In the Customize Installation dialog box, make your selections.

o Click OK.

• At the Welcome page of the installation wizard, click Next.

• At the License agreement page, review the license agreement, select the acceptance checkbox, and click Next.

• At the NetBeans IDE installation page, do the following:

o Accept the default installation directory for the NetBeans IDE or specify another directory.

o Accept the default JDK installation to use with the NetBeans IDE or select a different installation from the drop-down list.

o Click Next.

• For installing Apache Tomcat, on its installation page, accept the default installation directory or specify another installation location.

• At the Summary page, verify that the list of components to be installed is correct and that you have adequate space on your system for the installation.

• Click Install to begin the installation.

• When the installation is complete, click Finish to exit the wizard.

Create a Servlet using Net Beans 6.9

• From File menu select New Project following window will appear :

[pic]

• Once on this page select Java Web-> Web Application and then click on Next.

• On the name and Location window enter the project name as “Conv” and enter desired location and select Next.

[pic]

• In the Server and Settings window select the server as Apache Tomcat 6.x and lick on Next.

[pic]

• In the framework window select the desired framework but at present we are going to select none and click Finish.

• Now from the left pane right click on Conv and select New-> Html. The following window will open:

[pic]

• Give the file name as index and click finish. The index.html will appear under Conv-> Web Pages.

• Now double click the index.html and write the following code

[pic]

• Now right click on Conv-> Properties and from the project properties select Run and unselect the check box for Deploy on save and in the space for Relative URL enter the name to the html page we just created and select OK.

[pic]

• Now again from the Right pane right click on Conv-> New and select Servlet a new Servlet Window will open. Enter the Class name as NewServlet and clickon Next.

[pic]

• From the configure Servlet deployment window you can specify how the Servlet could be called from the browser but just now we will leave as it is and click Finish.

[pic]

• Now the servlet class will be placed under Crov->Souce package->default package->NewServlet.

• Write the following code .

[pic]

[pic]

[pic]

• Now Run-> Build the main Project.

• Now Run the project and a new browser will open with the URL : and will display the index page we created.



[pic]

• Now enter the temperature in Fahrenheit and click submit the Servlet will run and will show the result as follows:

[pic]

How to deploy web project to Tomcat from NetBeans?

1. After building the project, you can find .war file in the disk folder from your project category.

[pic]

2. Copy the .war file into webapps folder which in the Tomcat category.

[pic]

3. Type into IE and will display the index page we created.

[pic]

3.5.2 Lab2 A Simple HTTP Servlet Development and Deployment

The following screens show the directory structure for the temperature conversion Web application. The root directory is named conv. The HTML files and JSP files are placed here. WEB-INF directory is also here.

[pic]

The Servlet deployment descriptor file web.xml is placed in the WEB-INF directory. The classess directory holds Servlet packages and class files.

[pic]

In the doGetMethod subdirectory you can find the servlet class file TestServlet.class. The doGetMethod directory serves as the package for the TestServlet class. It can be created automatically by using a javac –d command on the command line or created manually.

[pic]

Here is the index.html file which makes the HTTP request to the Servlet. The action attribute of the form tag specifies the name of the Servlet which will respond this request. The request type is not shown because GET method request type is default. The text field input parameter is named as “temperature” and will be processed by the Servlet.

Please enter Fahrenheit temperature:

Temperature(F) :

Next, let’s look at the Servlet web.xml deployment descriptor file which is placed in the WEB-INF sub-directory of the application root directory. The TestServlet class is in the doGetMethod package so that doGetMethod.TestServlet is specified in the tag which has its Servlet name called testServlet. In the tag the Servlet name is mapped to a URL-pattern name “/test” that can be used as a virtual URL path name for this Servlet. It makes things much easier. For example, we can make a query by simply typing the address in the browser URL location field to access this servlet. Here the “/test” plays a role of virtual URL-pattern path name to the Servlet destination and conv is the Web application ROOT directory.

testServlet

doGetMethod.TestServlet

testServlet

/test

The following is the source code of the TestServlet Servlet class. This Servlet simply takes an input value of Fahrenheit temperature from the parameter “temperature” in the form request of index.html or from a query string of a URL address and converts it to a Celsius temperature, then renders the converted result to the client. If the input from the client is invalid data then an exception is thrown and a status code 500 is sent back to the client to give an error message.

import java.io.*;

import .*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.text.DecimalFormat;

public class TestServlet extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException

{

String temperature = req.getParameter("temperature");

DecimalFormat twoDigits = new DecimalFormat("0.00");

try

{

double tempF = Double.parseDouble(temperature);

String tempC = twoDigits.format((tempF -32)*5.0/9.0);

PrintWriter out = res.getWriter();

out.println("");

out.println("");

out.println("");

out.println("");

out.println("" + temperature + " Fahrenheit is

converted to " + tempC + " Celsius");

out.println("");

out.println("");

}

catch(Exception e)

{

res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,

"There was an input error");

}

}

}

You see the page below:

Type 32 in the Fahrenheit temperature input text field of this page.

[pic]

When you submit the page, you will see the following page dynamically generated by the Servlet. The 32 degree value in Fahrenheit is converted to zero degrees in Celsius.

[pic]

If you type invalid data such as a character string, you will get an error status message in the response page as follows:

[pic]

3.5.2 Lab3 A Servlet forwards the control to another Servlet

In Lab 3 you will see how a Servlet takes requests from clients and forwards the requests to another Servlet or other Web components based on certain conditions. The most important role a Servlet plays in any Web application is front-end decision making or traffic control. The complex business logic processing and GUI presentation are usually done by other Java Web components such JSP, Enterprise Java Beans, and Java Beans.

First, create a Web application root directory called forwardMethod under the webapps directory and place the index.html file under this newly created directory.

The index.html is almost identical to the previous one in Lab 1except that it targets a different Servlet where /forwardMethod is the root and /test is the URL pattern name for the Servlet TestServlet in /forwrdMethod/test.

doGetMethod

Please enter the number of tempareture(F):

Temperature(F) :

Here is the web.xml file for this application. Place this file under the WEB-INF subdirectory of the application root directory forwardmethod. Notice that there are two Servlet classes, TestServlet and ForwardServlet. The tags always precede the tags. Both of these two classes are in the forwardMthod package. Both of them get new Servlet names and URL-pattern names through mapping.

testServlet

forwardMethod.TestServlet

forwardServlet

forwardMethod.ForwardedServlet

testServlet

/test

forwardServlet

/forward

Two Servlet classes are generated either in classes sub-directory by javac –d *.java if all Java files are in classes directory, or by javac *.java in forwardMethod sub-directory of classes directory if all Java source files are available in the forwardMethod directory. The source code is listed here: The first Servlet forwards the request to the second servlet and the second Servlet receives the forwarded request. First, let’s take a look at the TestServlet which forwards the request to another Forwarded Servlet. The first Servlet checks the validation of the data. If the data is valid then the converted temperature is sent back to the client. Otherwise this TestServlet will forward the same request to the second Servlet Forwarded to generate a custom error page. This Servlet takes both GET and POST requests by adding doPost(req, res) in the body of doGet() method.

Two most important statements in this class are

req.setAttribute("temperature", temperature);

req.getRequestDispatcher("/forward").forward(req, res);

In the first statement the value of the temperature is stored in a request attribute called “temperature”. In the second statement the Servlet gets the requestDispatcher reference pointing to the second Servlet by its URL-name and then forwards the request and response objects to the second Servlet.

package forwardMethod;

import java.io.*;

import .*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.text.DecimalFormat;

public class TestServlet extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException

{

doPost(req, res);

}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException

{

String temperature = req.getParameter("temperature");

DecimalFormat twoDigits = new DecimalFormat("0.00");

try

{

double tempF = Double.parseDouble(temperature);

String tempC = twoDigits.format((tempF -32)*5.0/9.0);

PrintWriter out = res.getWriter();

out.println("");

out.println("");

out.println("");

out.println("");

out.println("" + temperature + " Fahrenheit is converted to "

+ tempC + " Celsius");

out.println("");

out.println("");

}

catch(Exception e)

{

req.setAttribute("temperature", temperature);

req.getRequestDispatcher("/forward").forward(req, res);

return;

}

}

}

Here is the second Servlet, ForwardedServlet which gets the value of the temperature attribute with the req.getAttribute("temperature") method and includes it as part of error message sent back to the client. You can see that this attribute of the request is shared by these Servlets since they are in the same session.

package forwardMethod;

import java.io.*;

import .*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ForwardedServlet extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

javax.servlet.ServletException, java.io.IOException

{

doPost(req, res);

}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws

javax.servlet.ServletException, java.io.IOException

{

try

{

String temp = (String) req.getAttribute("temperature");

PrintWriter pw = res.getWriter();

pw.println("");

pw.println("");

pw.println("");

pw.println("");

pw.println("" + "Input " + temp + " is not valid!

");

pw.println("");

pw.println("");

}

catch(Exception e)

{

}

}

}

You can run this application using any internet browser as follows. You can attach a query string after the URL address and a “?” like this:

Even the index.html in this string can be omitted since it is the default home page name.

[pic]

The next screen shows the response back from the first Servlet

You may type in an invalid input as follows.

[pic]

The next screen shows the error pages generated from the Forwarded Servlet (the second Servlet). Pay attention to the URL address in the response page; you will find that is exactly identical to the URL address of valid input response page. Can you tell why?

[pic]

3.5.4 Lab4 A Session Tracking example

This session-tracking lab demonstrates the Servlet session tracking control by a simple example. You can see when the new session starts and the session terminates

SessionTracking

servlet.session.SessionTracking

SessionTracking

/test

package servlet.session;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SessionTracking extends HttpServlet

{

public void service(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException

{

PrintWriter out = res.getWriter();

HttpSession session = req.getSession(true);

Integer counter = (Integer)session.getAttribute("sessionCounter");

if(session.isNew())

{

counter = new Integer(1);

session.setMaxInactiveInterval(10);

}

else

{

counter = new Integer(counter.intValue() + 1);

}

session.setAttribute("sessionCounter", counter);

out.println("");

out.println("");

out.println("");

out.println("");

out.println("Session Tracking : ");

out.println("You have visit this page " + counter +

" times. ");

out.println("Session Data:");

out.println("New Session: " + session.isNew());

out.println("Session ID: " + session.getId());

out.println("");

out.println("");

}

}

Test session Servlet:

[pic]

[pic]

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download