Docstoc

Introduction to JSP

Document Sample
Introduction to JSP Powered By Docstoc
					   The University of Akron
       Summit College
 Dept of Business Technology
Computer Information Systems



    Introduction to JSP
  Professor: Enoch E. Damson
          Server-side Scripting: JSP
• Server-side scripts are executed on the Web server
• The server must be equipped with an engine that can
  interpret corresponding scripting code
   – For example, in order to run JSP, the server must be
     equipped with an engine that can interpret JSP scripts
• Independent of Browser:
   – Since the Web server sends the results (the execution of
     server-side script) of server-side scripts back to the client
     browser as regular HTML content, server-side scripts have
     nothing to do with the client browser
       • That means that the server-side scripts will work with any
         browser


                           Introduction to JSP                        2
                 JSP Example

The following JSP script:
<%= new java.util.Date() %>


Generate output to client browser similar to:


Thu Jan 30 20:02:01 EST 2003



                    Introduction to JSP         3
                  JSP versus HTML
JSP can perform the following tasks:
•   Create pages that can display things which will be of interest to a
    particular user
•   Collect data from users and return information to a visitor based
    on the data collected
•   Connect to and manipulate a database
•   Modify the content of a Web page, by updating a text file or the
    contents of a database rather than the HTML code itself
•   Access file systems via the Internet so that you can read, write,
    and update files
•   Utilize extensive Java Applications Programming Interface



                          Introduction to JSP                           4
             A Web Server and JSP

• A Web server and a JSP engine software needs to be installed
  on your computer to enable you to write and test JSP code
   – Any Web server that supports JSP can be used
• The Apache Tomcat Web server is a good choice for JSP
  scripting
   – Download from: http://tomcat.apache.org
• The Java Software Development Kit (Java SE) may need to be
  installed prior to installing the Apache Tomcat Server
   – Download from: http://java.sun.com



                          Introduction to JSP                    5
        Installing the Java Software
              Development Kit
• It is assumed that you are using Windows 2000
  Professional, Windows XP Professional, or
  Windows Vista
• Locate and download the software which is
  located at: http://java.sun.com
   – Choose the ―Java SE‖ link under ―Downloads‖
   – Download the ―JDK 6 Update x‖
• Follow the default instructions to install the Java
  JDK on your computer
                     Introduction to JSP                6
            Installing Apache Tomcat
• It is assumed that you are using Windows 2000 Professional,
  Windows XP Professional, or Windows Vista
• Locate and download the software which is located at:
  http://tomcat.apache.org
    – Choose the Tomcat version (e.g. ―Tomcat 7.0‖) link under
      ―Downloads‖
    – Download any of the ―Binary Distributions‖
        • Preferably the ―Windows Service Installer‖ under ―Core‖
• Follow the instructions to install the Apache Tomcat server to
  your computer
    – By default, Tomcat will be installed in the directory: C:\Program
      Files\Apache Software Foundation\Tomcat 7.0\

                            Introduction to JSP                           7
      Testing Apache Tomcat Server
      Installation and Configuration
• Once you have installed and configured the Tomcat
  server and your Web application, you should check to
  make sure that it works correctly
   – Start the Tomcat server if it is not started
   – Open a browser window and enter the following URL in the
     address box: http://localhost:8080
       • 8080 being the default port number used for the Apache
         Tomcat Server during installation
   – You should see the Tomcat default page displayed



                          Introduction to JSP                     8
                Executing JSP Scripts

• By default, your JSP scripts must be saved at:
  C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ROOT

   – This path is the default location for publishing Web
     files on the Apache Tomcat Web server
• You test your scripts by opening a browser window
  and entering the following URL in the address box:
  http://localhost:8080/script.jsp
  • Where 8080 is the Web service port number specified
    during installation and script.jsp is the file to be
    executed on the Apache Tomcat Web server

                               Introduction to JSP                      9
             Collecting Information

• A form serves as a container that holds controls
  such as text fields, labels, buttons, and images
• Form tags:
   <form name="formName" action="getUserData.jsp"
     method=“post">
      <!-- form elements go inside of form tags -->
   </form>




                     Introduction to JSP              10
                   Form Attributes
• Name:
   – is required if you want form controls processed on the client
     side; otherwise, it is optional
• Action:
   – Specify the destination Web page where the form is
     processed
• Method:
   – Specify how to send form to the Web server, either POST or
     GET




                         Introduction to JSP                     11
       Control Elements in a Form

• The input fields on a form are called controls and
  are created with the <input>, <button>,
  <select> and <textarea> tags:
• The most commonly used tag is the <input> tag
   – E.g.
      <form name="formName" action="getUserData.jsp"
        method=“post">
      Name: <input type="text" name=“lastName">
      </form>

                     Introduction to JSP               12
        Control Elements’ Attributes

• TYPE:
  – Specifies the input type
• NAME:
  – Each control in a form must have a NAME. The data entered
    by the user is retrieved by referencing the name of its control
    field. Without a name, the data stored in the control field
    cannot be retrieved
• VALUE:
  – A default value may be assigned to a control element



                         Introduction to JSP                     13
    Submitting Form for Processing

• In order to process form data, you need to submit
  the form to the server, and then retrieve and
  process data on the server-side
• To submit a form, the submit() method of the
  form must be called:
   – Using Submit button
   – Explicitly call the submit method of a form



                      Introduction to JSP          14
               Using Submit Button

<form name="formName― action="getUserData.jsp"
   method=―post">
        First Name:<input type="text" name="firstName">
        <input type=“submit" value="Send">
        <input type=―reset" value=―Clear">
</form>




                         Introduction to JSP              15
                GET Method

• Form data is appended to the end of the
  designated URL after a question mark

• The URL is the one specified as the ACTION
  value in a form

• If you do not explicitly set the METHOD
  attribute for a form, by default the form is sent
  using the GET method


                   Introduction to JSP                16
             POST Method

• When you use the POST method, the form
  element data is sent to the server as a
  transaction message body
• Unlike the GET method, the POST method
  does not append form element data to the
  URL
• Note that when the POST method is used,
  you can generate a query string by attaching
  a query string to the URL directly

                Introduction to JSP              17
             Form Elements Example
<html>
          <head>
                 </title> Web Forms </title>
          </head>
          <body>
            <form name="formName“ action="getUserData.jsp"
                  method=“post">
                  First Name:<input type="text" name="firstName">
                  <input type=“submit" value="Send">
                  <input type=“reset" value=“Clear">
            </form>
          </body>
</html>


                           Introduction to JSP                      18
                  Programming Elements
•   Every programming language uses the following programming
    elements:
    –   Syntax
    –   Comments
    –   Constant data
    –   Data input
    –   Data output
    –   Data types
    –   Keywords and Variables
    –   Operators and expressions
    –   Selections (Condition Testing)
    –   Repetitions (Looping structures)
    –   Arrays
    –   File handling


                                     Introduction to JSP        19
              Content Comments

• Comments are not displayed on the browser
• The same syntax as comments in HTML:
  <!– content comments -->




                      Introduction to JSP     20
             Server-side Comments
• They are ignored at translation time
• They are not sent to clients
   <%--
      Multiple line comments
   -- %>
   <%
       /* Multiple line
          comments
       */
   %>
   <% // Single line comment %>




                          Introduction to JSP   21
Retrieve Data Stored in a Control
            Element

• To retrieve data stored in Web form control
  element from the server-side using JSP, use:
      request.getParameter(“elementName”)
  where elementName is the value assigned to
  the name attribute of the form’s control
• Example:
      request.getParameter(“firstName”);


                 Introduction to JSP             22
             Retrieve Form Data

<html>
  <head>
      </title> Retrieving Data from Web Forms </title>
  </head>
  <body>
      Hello, <%= request.getParameter(“firstName") %>
  </body>
</html>




                    Introduction to JSP                 23
             Output to the Client


• JSP output to the client can be done in two
ways:
      <%= “Your message goes here” %>
      <% out.println(“Your message goes here”); %>

Unlike the first output method: <%= %>, you can put
many statements within a single pair of <% %>, with
the out.print( ) method,



                    Introduction to JSP               24
           Storing Form Information
• There are many situations in which you will need to store
  form information and use it later in your JSP scripts. Like
  all programming languages, JSP uses variables to
  temporarily store information

• A variable is a location in computer memory where a
  value is stored for use by a program

• In JSP script, all variables must be declared before you
  can use them

• After a variable has been declared, a value can be stored
  in the variable, and this value can be used throughout
  your JSP page

                        Introduction to JSP                     25
                      Variables
• A variable is a location in the computer's memory where a
  data value is stored, or a location that references to
  another location where an actual object resides
• There are two types of data types in JSP: primitive data
  types and classes
• For primitive data types, the data value is stored in the
  location specified by the variable name; for classes, the
  actual data value is stored somewhere in memory and the
  data value is referenced using the variable name



                       Introduction to JSP                   26
              Primitive Data Types
• A data type describes the information that a variable
  stores. For example, int variables store integers, or whole
  numbers
• A variable’s data type also determines how many bytes of
  memory are required to store that variable
• Each data type has a range of values. Memory space is
  allocated to store each variable according to its data type
• JSP provides eight primitive data types:
   – Six of them are numeric
   – One is character, used for characters in Unicode encoding
   – One is Boolean, used for true/false values

                        Introduction to JSP                      27
         Numerical Data Types

Name        Range                     Storage
                                      Requirement

byte        -27 to 27 -1              1 byte
short       -215 to 215 -1            2 bytes
int         -231 to 231 - 1           4 bytes
long        -263 to 263 - 1           8 bytes
float       -3.4E38 to 3.4E38         4 bytes
double      -1.7E308 to               8 bytes
            1.7E308



                Introduction to JSP                 28
          Character Data Type

•The character data type is used to
represent a single character
•Unlike the string type, a character value is
enclosed within single quotation marks
•Example:
   char letter = 'A';
   char numChar = '6';


                   Introduction to JSP          29
              Boolean Data Type

• The Boolean data type has two values, true and
  false

• It is used for logical testing using the relational
  operators

• Boolean values are integral part of control
  structures such as if statements and loops


                      Introduction to JSP               30
          Variable Declaration


dataType variableName;


E.g.,
   int x, y;
   char a;
   String s1;



                Introduction to JSP   31
                 Assignment

• The equal sign = is used as an assignment
  operator
• E.g.,
   String s1;
   s1= “Hi, there.”;




                   Introduction to JSP        32
            Variable Initialization

• You can declare and initialize a variable in
one step:
• E.g.,
   String s2 =“Hi, there.”;




                   Introduction to JSP           33
                    Naming Variables

• A variable name is any valid identifier
• An identifier is a series of characters, consisting of letters, digits,
  and underscores, that does not begin with a digit. JSP script is
  case sensitive—uppercase and lowercase letters are different,
  so varname and VARNAME are different identifiers
• A variable name can be any length
• All of the following are valid identifiers:
        String s;
        String aLongVariableNameButStillValid;
        int an_integer_variable_name;
• Variable names cannot contain spaces or dashes


                            Introduction to JSP                        34
               Using Variables
<html>
   <head>
       </title> Getting Data into JSP Variables </title>
   </head>
   <body>
       <%
        String fname = request.getParameter(“major”);
        out.println(fname);
        %>
   </body>
</html>




                      Introduction to JSP                  35
        Converting String Values
• Data from Web pages (forms elements) are sent to
  the Web server in String values
• JSP has some class methods that allow String
  values to be converted to any of the 8 primitive data
  types
• The methods that convert String values to the
  numeric data types are:
    –   Long.parseLong()  converts Strings to long values
    –   Integer.parseInt()  converts Strings to int values
    –   Short.parseShort()  converts Strings to short values
    –   Byte.parseByte()  converts Strings to byte values
    –   Double.parseDouble()  converts Strings to double values
    –   Float.parseFloat()  converts Strings to float values




                         Introduction to JSP                       36
  Converting String Values Example
<html>
   <head>
       </title> Getting Data into JSP Variables </title>
   </head>
   <body>
         <%
    int myage = Integer.parseInt(request.getParameter(“age”));
    double mysalary = Double.parseDouble(request.getParameter(“salary”));
    out.println(myage);
    out.println(mysalary);

         %>
   </body>
</html>



                              Introduction to JSP                           37
            Arithmetic Operations

Operation        Arithmetic        Algebraic      JSP
                  operator        expression   expression


Addition             +                x+y        x+y

Subtraction          -                x–y         x-y

Multiplication       *                x*y         x*y

Division             /                x/y         x/y

Modulus              %              x mod y      x%y



                    Introduction to JSP                     38
       Comparison Operators

Operator   Example           Meaning


  ==       x == y            x is equal to y
  !=       x != y            x is not equal to y
   >       x>y               x is greater than y
  >=       x >= y            x is greater than or equal to y
   <       x<y               x is less than y
  <=       x <= y            x is less than or equal to y




                    Introduction to JSP                        39
         Conditional Statements
• Conditional statements in JSP use if/else statements
  to test for conditions before performing tasks
• The structure of the JSP if/else statement is:
    if (condition)
    {
        statement(s);
    }
    else
    {
        statement(s);
    }




                        Introduction to JSP              40
Conditional Statements Example
<html>
   <head>
       </title> JSP Conditional Statement </title>
   </head>
   <body>
        <%
                if (yourGrade >= 60)
                {
                            out.println("passed");
                }
                else
                {
                            out.println("failed");
                }
        %>
   </body>
</html>
                       Introduction to JSP           41
               switch/case Structure

•   The switch/case structure is used as an alternative to the
    if/else/if statements that involve testing for equality
    conditions on values of numeric data types and the single
    character data type
•   The structure is:
     switch (switch-expression)
     {
         case value1:
           statements1;
           break;
         case value2:
           statements2;
           break;
         …
         case valueN:
           statementsN;
           break;
         default:
           statements-for-default-case;
     }



                                 Introduction to JSP             42
 switch/case Structure Example
<html>
   <head>
        </title> JSP Conditional Statement </title>
   </head>
   <body>
         <%
                  switch (year)
                  {
                    case 1:
                              out.println("You are a Freshman");
                    case 2:
                              out.println("You are a Sophomore");
                    case 3:
                              out.println("You are a Junior");
                    case 4:
                              out.println("You are a Senior");
                     default:
                              out.println(" ");
                  }

         %>
   </body>
</html>                Introduction to JSP                          43
 Logical Operators


Operator    Meaning


!           Logical NOT
&&          Logical AND
||          Logical OR
^           Logical exclusive




       Introduction to JSP      44
                        For loop

for (initialize-control-variable; condition-testing;
   modifying-condition)
{
    statements;
}
Example:
<% for(int i = 0; i<10; i++){ %>
        Welcome to JSP<br>
<% } %>
                        Introduction to JSP            45
                              While loop

while (condition-testing)
{
     statements;
}


Example:
    int i = 0;
     while(i < 10)
     {
            out.println("Welcome to JSP<br>");
            i--;
     }


                                Introduction to JSP   46
                            Do loop

do
{
     statements;
}
while(condition-testing);


Example:
    <% int counter = 1;
         do { %>
        <%= counter %> <br>
     <% }while (++counter <=10); %>
                            Introduction to JSP   47

				
DOCUMENT INFO
Categories:
Tags:
Stats:
views:1
posted:12/5/2011
language:English
pages:47