Practice Labs with NetBEans IDE 6

foreheadsobstinacySoftware and s/w Development

Aug 15, 2012 (5 years and 2 days ago)

326 views

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 configura
tions. 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 sess
ion 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
http://java.sun.com/javase/downloads
.



You can download the Net beans from
http://www.netbeans.org/downloads/index.html

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 e
xecutable 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, veri
fy 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 u
sing Net Beans 6.
9



From File menu select New Project following window will appear :






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 locatio
n
and select Next.






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






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 r
ight click on Conv and select New
-
> Html. The following window will
open
:






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





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.






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.






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.






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



Write the following code .








Now Run
-
> Build the main Project.



Now Run the project and a new browser will open with the URL :

http://localhost:8084/Conv/index.html

and will display the index page we created.







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



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.



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



3.
Type

http://localhost:8080/Conv

into IE
and will display the index page
we created.



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.




The Servlet deployment desc
riptor file
web.xml

is placed in the WEB
-
INF directory. The
classess

directory
holds Servlet packages and class files.




In the
doGetMethod

subdirectory you can find the servlet class file
TestServlet
.class. The
doGetMethod

directory serves as the packa
ge for the
TestServlet

class. It can be created automatically by using a
javac

d

command on the command line or created manually.




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.


<!DOCTYPE HTML PUBLIC "
-
//W3C
//DTD HTML 4.0 Transitional//EN">


<html>

<head>

</head>


<body>


<h3>Please enter Fahrenheit temperature:</h3><p>


<form action="/conv/test">

Temperature(F) : <input type="text" name="temperature"><br><br>

<input type="submit" value="Submit">

</form>


</
body>

</html>


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 speci
fied in the <servlet
-
class> tag which has its Servlet name called
testServlet
. In the <servlet
-
mapping> 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
http://<host>/<application
-
root>/test
?temperature=32

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.


<?xml version="1.0" encoding="ISO
-
8859
-
1"?>


<!DOCTYPE web
-
app


PUBLIC "
-
//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"


"http://java.sun.com/dtd/web
-
app_2_3.dtd">


<we
b
-
app>



<servlet>


<servlet
-
name>testServlet</servlet
-
name>


<servlet
-
class>doGetMethod.TestServlet</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>testServlet</servlet
-
name>


<url
-
pattern>
/test
</url
-
pattern>


</servlet
-
mapp
ing>


</web
-
app>


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 addr
ess 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 java.net.*;

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.ServletE
xception, 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("<html>");




out.println("<head>");




out.println("</head>");




out.println("<body>");




out.println("<h3>" + tempe
rature + " Fahrenheit is


converted to " + tempC + " Celsius</h3><p>");








out.println("</body>");




out.println("</html>");


}


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.




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.





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






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, Enterp
rise 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.


<!DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<head>


<title>doG
etMethod</title>

</head>

<body>

<h3>Please enter the number of tempareture(F):</h3><p>

<form action="/forwardMethod/test">

Temperature(F) : <input type="text" name="temperature"><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>


Here i
s 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 <servlet> tags always precede the <ser
vlet
-
mapping> tags. Both of these two classes
are in the
forwardMthod

package. Both of them get new Servlet names and URL
-
pattern names through
mapping.


<?xml version="1.0" encoding="ISO
-
8859
-
1"?>


<!DOCTYPE web
-
app


PUBLIC "
-
//Sun Microsystems, Inc.//
DTD Web Application 2.3//EN"


"http://java.sun.com/dtd/web
-
app_2_3.dtd">


<web
-
app>



<servlet>


<servlet
-
name>testServlet</servlet
-
name>


<servlet
-
class>forwardMethod.TestServlet</servlet
-
class>


</servlet>



<servlet>


<servlet
-
name>forwar
dServlet</servlet
-
name>


<servlet
-
class>forwardMethod.ForwardedServlet</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>testServlet</servlet
-
name>


<url
-
pattern>/test</url
-
pattern>


</servlet
-
mapping>



<servlet
-
mapping>


<ser
vlet
-
name>forwardServlet</servlet
-
name>


<url
-
pattern>/forward</url
-
pattern>


</servlet
-
mapping>


</web
-
app>


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 th
e 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.
O
therwise 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 i
n 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 java.net.*;

import javax.servlet.*;

im
port 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.0
0");




try


{


double tempF = Double.parseDouble(temperature);


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



PrintWriter out = res.getWriter();




out.println("<html>");




out.
println("<head>");




out.println("</head>");




out.println("<body>");




out.println("<h3>" + temperature + " Fahrenheit is
converted to "


+ tempC + " Celsius</h3><p>");






out.println("</body>");




out.println("</html>");



}


catch(Exception e)


{


req.setAttribute("temperature", temperature);


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




return;


}




}

}


Here is the second Servlet,
Fo
rwardedServlet
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 java.net.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class ForwardedServlet extends HttpServlet

{


public void doGet(HttpServletR
equest 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("<h
tml>");




pw.println("<head>");




pw.println("</head>");




pw.println("<body>");




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


</h3><p>");








pw.println("</body>");




pw.println("</html>");


}


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: http://localhost/forwardMethod/index.html?te
mperature=56

Even the
index.html

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




The next screen shows the response back from the first Servlet




You may type in an invalid input as follows.




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?




3.5.4 Lab4 A Session Tr
acking 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

<web
-
app>



<servlet>


<servlet
-
name>SessionTracking</servlet
-
name>


<servlet
-
class>servlet.session.SessionTracking</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>SessionTracking</servlet
-
name>


<url
-
pattern>/test</url
-
pattern>


</servlet
-
mapping>


</web
-
app>



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.IOExcep
tion


{



PrintWriter out = res.getWriter();


HttpSession session = req.getSession(true);


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




if(session.isNew())


{


c
ounter = new Integer(1);


session.setMaxInactiveInterval(10);


}


else


{


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


}




session.setAttribute("sessionCounter", cou
nter);




out.println("<html>");



out.println("<head>");



out.println("</head>");



out.println("<body>");


out.println("<h1>Session Tracking : </h1>");


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



"</b> times. <p>");


out.println("<h3>Session Data:</h3>");


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


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




out.println("</body>");



out.println("</html>");




}

}


Test session Servlet: