JSP Basics


Andy Meneely, Sarah Heckman, and Laurie Williams [Contact Authors]
CSC 326 - Software Engineering
Department of Computer Science
North Carolina State University

Back to Software Engineering Tutorials


0.0 Contents
1.0 What are JavaServer Pages?
2.0 Our Running Example: CoffeeMaker
3.0 A Simple JSP
4.0 A (Slightly) More Complex JSP
5.0 Using JSP in Larger Systems
6.0 Exercise
7.0 Resources

1.0 What are JavaServer Pages?

JavaServer Pages (JSP) is a Java-based technology for creating dynamic web applications; that is, for creating websites which respond to user input and create content at runtime. Consider a typical flow of events when a user goes to a regular, HTML website:

  1. The user clicks on a link to an HTML file, index.html which sends an HTTP request to a server.
  2. The server processes the HTTP request, finds the index.html file
  3. Since the file is just an HTML file, the server sends it back to the user "as is" in an HTTP response.
  4. The user's browser renders the HTML from the response, executing any client-side scripts or styles such as JavaScript or Cascading Style Sheets (CSS)

This is what's known as a static website, because the content of the website's page does not change based on any user input. A dynamic website, such as what JavaServer pages is capable of, works similarly but with one extra step. Consider a typical flow of events for going to a JSP website:

  1. The user clicks on a link to a JSP file, index.jsp which sends an HTTP request to a server.
  2. The server processes the HTTP request, finds the index.jsp file
  3. The server executes the code in index.jsp, passing along any HTTP parameters from the request.
  4. When index.jsp is done executing, the server sends the output (dynamically generated HTML) back to the user in an HTTP response.
  5. The user's browser renders the HTML from the response, executing an client-side scripts or styles such as JavaScript or Cascading Style Sheets (CSS)

JSPs are executed in a server program (often called a "container"), with access to an API for easier processing.

Top | Contents

2.0 Our Running Example: CoffeeMaker

For the rest of this tutorial, we will be working with a toy JSP application, called CoffeeMaker.

We all know that most computer scientists love caffeine, so the Computer Science department is looking to put a coffee kiosk in EBII building. The coffee kiosk must be able to make coffee for students to purchase. The department recently upgraded the CoffeeMaker hardware to include a network connection. Now students will be able to order their coffee online, and their order will be waiting for them when the go to the machine.

Download the CoffeeMaker_Web source and deploy just like iTrust (with the same versions of Tomcat and Eclipse). See the lab deployment instructions or home deployment instructions on the iTrust website for more information.

Start up Tomcat and surf to

http://localhost:8080/CoffeeMaker_Web

You should see a webpage like this:


Figure: Homepage of CoffeeMaker
Top | Contents

3.0 A Simple JSP

With CoffeeMaker deployed in your Eclipse workspace, open up the WebContent/index.jsp file from the Package Explorer.

As you can imagine, index.jsp is a very basic page, with very little code. (If you have worked with HTML before, this should look familiar to you). In fact, this is mostly just a basic HTML page with a few JSP directives. All JSP directives are surrounded by the following tags:

<%@ ... %>

The first directive is the page directive:

<%@ page language="java" 
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

This is a basic definition of a JSP, usually required for every page. You can just copy-and-paste this to the top of every JSP you work with. The second directive is an include directive, which takes the content of the included file and inserts it into the page. We use the include directive here to have a header for styles (this is done in iTrust in a similar fashion):

<%@include file="head.jsp"%>

Eclipse Tip If you Ctrl + click the "head.jsp" in the include statement, Eclipse will take you to the file head.jsp, which stores all of our styles for the page.

Additionally, we create a session variable on index.jsp. A session variable is a container for an object that is passed between pages, and the variable is specific to a user. Therefore, each user connected to the webpage has a session, and the session can contain one or more variables.

The code snip-it below demonstrates how to get and set a session variable. The session object is always called session. The getAttribute() method returns an Object associated with the String parameter containing the name of the session variable, in this instance "cm". The setAttribute() method always returns an Object; therefore, you must cast the returned object into the type of object it should be.

A session variable is set using the setAttribute() method. This method may be used when creating a new session variable or updating an already existent session variable. The first argument to the setAttribute() method is the name of the session variable, and the second argument is the object.

CoffeeMaker cm = (CoffeeMaker)session.getAttribute("cm");
if (cm == null) {
session.setAttribute("cm", new CoffeeMaker());
}

All other information on this page is HTML to be rendered by the user's browser.

Top | Contents

4.0 A (Slightly) More Complex JSP

In your browser, click on the link "Add a Recipe ". Fill out the form to add a recipe, for example:


Figure: Using the Add Recipe page

Now take a look at WebContent/add_recipe.jsp. Let's step through this just like in the flow of events from the introduction. Feel free to use your browser's "View Source" to see what HTML has been generated at each step.

  1. First, the user is presented with six text fields and a button, called an HTML form. The code for that form is abbreviated below:
    <form method="post" action="add_recipe.jsp">
    <table>
    <tr>
    <td><input type="text" name="name"></td><td><span class="font1">Recipe Name</span></td>
    </tr> ... </table> <input type="submit" value="Add Recipe!"> </form>
    A few things to note:
    • The action field specifies that this form submits to this very page, (most forms in iTrust do this).
    • The name of the parameter that the content of this text box will be name (note: the field name is named for users to enter name of the coffee. Also, these parameter names are case-sensitive!).
    • The submit button has the value "Add Recipe! ", which is what is displayed in the actual button.
  2. Once the user submits the form, a request with the value of the parameter "name" is passed to the current page. The chunk of code in the if-statement is now run, and the text in the font is included in the HTTP response. The code responsible for all this is:
    <%@ page import="edu.ncsu.csc326.coffeemaker.*, edu.ncsu.csc326.coffeemaker.exceptions.*" %>
    ...
    <html>
    <body>
    <%
       String name = request.getParameter("name");
       ...
    
       CoffeeMaker cm = (CoffeeMaker)session.getAttribute("cm");
    
       if (name != null && !"null".equals(name)) {
          ...
       if (recipeAdded) {
    %>
    <span class="font_success"><%=name + " successfully added." %> </span><br>
    <%
    } else {
    out.println("<span class=\"font_failure\">" + name + " could not be added.</span><br>");
    } %> </body> </html>

    There are many things to note here:
    • Anything between <% and %> is Java code.
    • Anything between <%= and %&> is a Java expression (use this to print your output to the JSP's response).
    • The variable request is a Java object that represents the HTTP request that the user made. The method request.getParameter("myText") retrieves what was in that text box in the form of a string. Under some circumstances, empty parameters can be passed as a Java null, or sometimes as the Java string "null" (don't ask me why, it's a JSP quirk...)
    • Tags starting with <%@ import import packages and classes into the JSP. Using imports you can instantiate objects from your Model. Further down in the code we instantiate a CoffeeMaker object.
    • Additionally, you can print HTML code from java code. This is done by using out.println(); In the example above we have an example of this if the recipe is not successfully added.

That covers the basics of JSP. Most of iTrust is built using this format.

Top | Contents

5.0 Using JSP in Larger Systems (such as iTrust)

As one can imagine, JSP is capable of a whole lot more than what we have shown here. However, most of the JSP development you will need to do in iTrust this semester has already been done in similar features. That being said, I must emphasize that it is up to you to spend some time going through iTrust to learn how the code works. You don't have to learn how the whole system works, but try to understand all that you can (and need) to complete your assignment. I suggest that, rather than specializing in one area of the system (eg JSP), work on knowing how every part of a single feature works. Start with the JSP, dive into the Java classes, study how the database interactions works for that feature, and follow how the content makes its way back to the user's browser.

Although JSP may not appear to be the traditional environment in which you will develop code, the same rules of good software design apply. Consider the page in iTrust called "Edit Patient Demographics", or editPatient.jsp - one of the simplest pages in the whole system (at least in principle). The purpose of the page is to take in over twenty different pieces of information about a patient, and store them away in a database. Every single parameter needs to be checked against a particular format (for both security and functionality reasons). Errors and status messages need to be reported properly. Furthermore, proper authorization needs to take place. If we tried to do this all in one JSP, the page would be incredibly complex! (not to mention none of the code would be easily reusable) That's where a consistent design needs to take over.

iTrust loosely follows the Model-View-Controller design pattern. If you have a Gang of Four book, take a look; otherwise, scour the internet for various definitions (it's not a unanimously well-defined pattern, unfortunately). The design of MVC in the context of iTrust goes like this:

  • The View is the visual part of the system that has very little logic other than displaying the information it is given. The view in iTrust are your JSPs and what we call Action classes. The intent is to have very little logic in your JSPs and your Actions, and to delegate all logic to other classes. Actions tend to do exception handling, but shouldn't have methods that are longer than 15 lines (yes, there are exceptions in the code where former students did not follow this convention, consider those to be misleading examples...).
  • The Model is part of the system that stores all of the data. In iTrust, these are our database system and our DAOs (Database Access Objects). DAOs ought to reflect what is in the database and provide functionality for interacting with the database. Generally speaking, DAOs should not have many branches (if-statements), but should simply query and update the database.
  • The Controller sits between the view and the model and is the part of the system that handles all of the logic. In iTrust, the Action classes delegate responsibilities to other classes based on the feature. For example, a Validator is in charge of checking strings for proper formats. Everything between Action classes and DAO classes are considered to be the Controller
Top | Contents

6.0 Exercise

Download the CoffeeMaker_Web.zip file to complete the exercise.

  1. Have the current values of price, units coffee, milk, sugar, and chocolate display to the user in the text boxes when editing a recipe. Here's an example of how to provide a value for a HTML input text box.
    <input type="text" name="firstName" value="Enter your first name here">
    				  
  2. Create a JSP file to complete the AddInventory user story. The file must be called add_inventory.jsp. See Main.java to see the command line interface implementation of the AddInventory user story and use the other .jsp files as examples. Submit the CoffeeMaker_Web project with the completed AddInventory user story.
  3. Submit a file named "jsp_answers.txt" which has the answers to following questions:
    • What are the output of these two code snippets if the parameter "myText" has the value "JSP is fun"?
      <% request.getParameter("myText"); %>
      
      ...and...
      <%= request.getParameter("myText") %>
      
Top | Contents

7.0 Resources and Other Handy JSP Features

Below is a list of additional resources

Also below are a few extra JSP tricks that are found throughout iTrust and will help you in your assignments

  • Parameters can be added to an HTTP request by including them in the URL. For example,
    http://localhost:8080/CoffeeMaker_Web/
    add_recipe.jsp?name=Latte&price=50&amtCoffee=3&amtMilk=2&amtSugar=1&amtChocolate=0
    Will add a recipe called Latte with the given information. If there is more than one parameter put the & symbol between each parameter.
Top | Contents

Back to Software Engineering Tutorials
JSP Basics Tutorial © 2008 North Carolina State University, Laurie Williams, Andy Meneely, and Sarah Heckman
Email the authors with any questions or comments about this tutorial.
Last Updated: Monday, August 25, 2008 11:10 AM