Web applications are client/server applications
where the web browser is the client who always initiates the connection.
The server is a program running on some computer which is
identified by a number called the port to distinguish it
from other server programs. Clients access the server
program via the pair (server,port) called a socket.
The browser client (as well as other client programs)
initiates the interaction with a URL request:
protocol://data_source
where the protocol is any number of possiblities, including
http, file, https, ftp, etc.
The data_source can be any number of things from a regular
file on the client machine to a program on some server
such as these:
file://file
http://server/dir1/dir2/file
http://server/dir1/program
http://server:port/file (server running on alternate port)
The protocol normally dictates the port, but we can
specify it if the different than the usual one,
as in the case of the alternate Tomcat server which we want to use.
If the target file is a directory, then a default file or program is
chosen as the source.
Server-side web programming means that an HTTP request from a browser
causes the web server to run a program which generates HTML
(or other data) to sends back to the browser.
Server-side programming stands in contrast to client-side programming
which is usually equated with JavaScript, but can also be effected by
Java Applets, Flash, or any others which provide a browser plugin.
There are two styles that a server-side program can use
to generate the HTML code sent to the browser:
HTML code generated by programming: (e.g. Perl/CGI, Servlets)
program code embedded within HTML code: (e.g., PHP, ASP, JSP)
Both styles have certain advantages and disavantages.
One advantage of the embedded code style is that it is easier to
adapt static HTML files to dynamic server-side script files.
On the other hand, the generative style is more uniform and avoids
the sometimes confusing transitions between HTML and the program code.
Apache Tomcat
A Java Servlet or Java Server Page
is an object that can the executed by an HTTP server
due to the invocation of a browser client.
This ability is not automatically part of standard
web servers like Apache and Microsoft's IIS via modules,
and so we need a specialized web server for that purpose.
The Apache open source tomcat web server serves our needs.
Its home page is this:
Tomcat runs on port 8080 by default. By doing so it avoids conflict
with standard web service on port 80 and permits control by
non-root users because ports up to 1024 are restricted to root
usage only on UNIX-like systems.
The Tomcat web server starts a Java virtual machine (JVM) and
handles browser client accesses by executing the requests in
threads created by this JVM which
makes the entire web service process very fast.
The software package you'll need is the Tomcat installation
file. You can get it from the Tomcat home page
or from here as a
hyperlink to the Computer Science website:
The tomcat server needs to have pre-existing
JRE (Java Runtime Environment) installation. JRE is part of a
JDK (Java Development Kit) installation which we will assume has
been done
(see the JDK/NetBeans
document).
Windows
Linux/Mac
Windows
Extract apache-tomcat-6.0.20.zip
into a dedicated location, which
we assume will be "C:\", thus getting the installation
directory:
C:\apache-tomcat-6.0.20\
Configure Tomcat Manager
Netbeans controls Tomcat via the manager application
which needs to be configured to permit access.
The Tomcat manager allows you to dynamically deploy,
undeploy, start, stop and restart
web applications through a web interface.
We can actually have NetBeans configure this for us,
but it is useful to know what is going on.
In order use the manager
you must define a managerrole
and set a user/password combination
which validates access to this role.
Edit the file:
apache-tomcat-6.0.20/conf/tomcat-users.xml
Within the tomcat-users start and end tags
(but outside the comments) add the following
XML entry:
For simplicity, we've given access to the manager
by using the username admin with empty password.
You can make these values anything you'd like.
Configure Tomcat Ports
This section is probably not necessary. Tomcat uses
the ports 8005, 8080, 8009, 8443 to run it services. It
is possible that some other web-based application running
on your system is using one or more of these. For example,
on Windows, you may be using both IIS (port 80) as
your main web server and Apache (port 8080) for development.
If you are aware of a service conflict,
or find that NetBeans cannot start up
Tomcat, you may have to change the Tomcat ports.
To do so, edit the file
apache-tomcat-6.0.20/conf/server.xml
and search for occurrences of the string "port=". You should find
up to three uncommented occurrences:
For our sake, probably the only one that needs
to be changed is 8080. Change it is some simple way,
like inserting a "1" in place of a "0", for example:
In NetBeans, install this plugin
via the menu
Tools Plugins Available Plugins:
Java Web Applications
Now we want to register Tomcat as a NetBeans server. You need
to know the Tomcat installation directory used above.
Open the
Services window on the left. If necessary
bring it up from
Windows Services:
Right-click on Servers
and select Add Server.
Choose Tomcat 6.0 from the list
in the Choose Server popup. Click Next.
In the Add Server Instance window, add this information:
CataLina Home: <the Tomcat installation directory>
UserName: admin
Password: <leave blank>
Create user if it does not exist. (unchecked)
Click Finish.
Then test that NetBeans can control it:
Test startup:
Right-click on the Tomcat 6.0 server entry
and select Start. If it failed read the failure message
closely and try to fix it.
Test shutdown:
Right-click on the Tomcat 6.0 server entry
and select Stop.
If all goes well you're ready to start creating
Java web applications.
Hello World web application
Proceed as follows:
From the Projects window, follow
New Project Java Web Web Application.
Set the Project Name to WebHello.
Click Next.
Take the default selections:
Project Name: WebHello
Server: Tomcat 6.0
Java EE version: Java EE 5
Context Path: /WebHello
Click Finish (skip the Frameworks dialog).
The root file, index.jsp, is automatically
brought up in the editor. The Palette window appears
on the right. For the most part, I find the Palette
not very helpful, and delete it to get more editor
space.
Edit index.jsp,
changing the title tags to:
<title>Web Hello</title>
Change the header tag (in the body) to
<h2>Web Hello</h2>
Run the project in the usual way you'd run any project.
It most likely will use the system default browser and
bring up a new browser window
or a new tab in an existing
browser with the URL:
http://localhost:8080/WebHello/
displaying what you just created.
This is the point at which NetBeans accesses the
Tomcat Manager. If you see a popup asking for access
to the manager, you've made a mistake in the
Tomcat server configuration. Go back to the
Configure Tomcat Manage
section
and check your settings.
See the project registered in the Tomcat manager. Open
http://localhost:8080/
and select the Manager hyperlink. Enter
the manager username/password in the authentication
popup and
look for WebHello in the list.
Run the Clean and Build choice and observe
the output.
When you build a Web Application,
Tomcat creates a ".war"
(web archive) file in the
dist directory
which can be used to upload to
other Java-based web servers such
as, perhaps, the "production"
version of Tomcat
running on a different port or different server.
Create a Hello Servlet
Right-click on project:
Select
New Servlet
(you may have to go through Other initially).
In the Name and Location window,
enter this information:
Class Name: Hello
package: servlet
Click
Finish (skip the Configure Servlet Deployment step).
This creates the servlet class servlet.Hello which
is brought up in the editor window.
Modify
the code in processRequest by simply removing the comment lines
/* TODO output your page here
and
*/
Run this servlet by itself by selecting Hello.java
from the project, right-clicking,
and selecting Run File. Click OK in the
Set Servlet Execution popup.
As before it should bring up a browser window,
or a new tab in an existing
browser with the following URL and its
expected content.
http://localhost:8080/WebHello/Hello
The structure of a Servlet
The activation of a servlet is initiated by a client-side (browser)
request. There are two types of requests: GET and POST. GET requests
are most standard and always activated by typing any URL into a browser.
GET requests are also those in which you see parameters delivered in
the URL itself after the "?" character, a portion called the
query string. POST requests are less frequent and
are normally initiated by HTML forms.
A Java Servlet is an extension of the
javax.servlet.http.HttpServlet.
A GET or POST request
activates one of the two built-in functions:
doGet or doPost, respectively.
Many server-side programs do not need to
differentiate between these two activations and it is often
common to merge the behaviors of these activations as is done
in Netbeans:
Edit index.jsp and, beneath the header element in the body,
add this line :
<a href="Hello">Hello Servlet</a>
Now run the project (not the servlet)
and
observe that you can activate the servlet through the hyperlink.
Changes in JSP vs. changes in Servlets
Run this little experiment which illusrates about editing changes:
Change the line in index.jsp to:
<a href="Hello">A Hello Servlet Link</a>
Then simply refresh the browser window (not re-run) to observe
that you've picked up the change. Click on the servlet
hyperlink again.
Now edit the Hello servlet. Add this line:
out.println("Test addition");
Just before the line:
out.println("</body>");
Then Save and refresh the browser and
observe that the change is (hopefully)
picked up as well.
In past versions of NetBeans, a servlet change
would only be picked up when you
re-ran the application (creating yet another tab/window).
It may be necessary to re-run
the application to pick up certain deeper changes.
Create a dynamic JSP hello script
The JSP file index.jsp illustrates primarily static HTML features, but
in reality, it is as dynamic as a Servlet. This little example
gives us a step towards JSP capabilities:
Right-click on project. Select
New JSP
(you may have to go through Other initially).
Enter only the name:
JSP File Name: hello (the .jsp extension is automatically added)
Click Finish. Modify hello.jsp to look like this:
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<% String title = "JSP Hello"; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><%= title %></title>
</head>
<body>
<h2><%= title %></h2>
<% out.println("Hello Again"); %>
</body>
</html>
Then add a hyperlink to this page in index.jsp
beneath the hyperlink
to the Hello servlet:
<br /><a href="hello.jsp">Hello JSP</a>
When you execute the main program and activate the link
You'll see the effects. Here is a description:
The tags <% ... %> are points for entry of Java code.
The tags <%= ... %> allow for the printing of a
Java expression.
The variable out used in the last tag pair is a predefined
variable for JSP scripts which has the same effect as in servlets
which specifically define it as:
PrintWriter out = response.getWriter();
Discussion
Tomcat Web configuration file
The key file which controls the web structure of servlets
in a Tomcat server is:
Web Pages/WEB-INF/web.xml
The file you're seeing is an XML file which is being displayed
through a number of viewer filters. If you click on the XML tab
on the far right you'll see the actual file.
Here are some of the features to observe:
The welcome-file-list element. The
welcome-file entries
are automatically used
when a browser accesses a directory. NetBeans only has one
initially, index.jsp, but you can add other likely choices
such as index.html, index.htm, etc.
The servlet and servlet-mapping elements.
Tomcat uses these and three other elements to map the URL
/WebHello/Hello
to the servlet.Hello class:
url-pattern: /Hello, meaning that
the URL /WebHello/Hello activates the servlet
servlet-name: Hello, this relates the
servlet and servlet-mapping groups.
servlet-class: servlet.Hello, the actual class
that is executed
JSP usage
A JSP script initially appears as an HTML file with embedded
Java code.
Much of the HTML content of a generated Web page is static
and so it is often easier
to embed the dynamic aspects of
a page within the static content in contrast to servlets which
must generate all the HTML code.
Going from HTML to Java mode is effected by
tag pairs, the most basic being this:
<%
/* Java code here */
%>
When a JSP file is functioning more in "Java Mode",
it is often convenient to replace
out.println
statements by the actual HTML code.
Towards this end, the Java entry tags
are often used in reverse to effect
HTML entry from Java, like this:
for (int i=0; ... ) {
%>
<!-- HTML code -->
<%
}
It is common to work mostly in
HTML mode make Java control structures "look like tag pairs," e.g.:
<% for (String s: some_list) { %>
<!-- HTML code -->
<% } %>
<% if (x == 5) { %>
<!-- HTML code -->
<% else if (x == 6) { %>
<!-- HTML code -->
<% } %>
One downside of this approach is that this new tag structure, with closing
tag "<% } %>" does not "look suitable" for a markup language.
A JSP script does not explicitly
specify the doGet and doPost
functions of a servlet, but these standard variables which
are used in servlets are automatically available to JSP execution:
HttpServletRequest request
HttpServletResponse response
JspWriter out (like PrintWriter in servlets)
HttpSession session
One can imagine the code within a JSP script
as residing inside the usual servlet
processRequest function.
Indeed, each JSP script,
including the static HTML along
with the Java code,
is converted automatically
to a Java class.
An HTTP request to the JSP script invokes
the function:
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
// converted HTML + Java code
}
Static HTML code is effectively
being dumped by out.print statements.
JSP vs. Servlets
One significant advantage of JSP is precisely
that you can write HTML code explicitly without
having to call Java print operations. In particular,
the abundance of double
quotes in HTML code makes Servlet
HTML generation quite painful.
On the other hand,
a Servlet is just
a Java class and notions of imports,
data members, etc. are the common Java notions, whereas
they have more obscure counterparts in JSP.
Thus a JSP file is likely to be more obscure and
messy with the mingling of Java and HTML, which
emphasis on HTML.
In terms of our MVC development, JSP files are considered
to be the View generators and special tag languages
such as JSTL are employed to make JSP usage more
like a markup language. Servlets are considered to
be part of the Controller and they are particularly
suited for AJAX-type invocations.