JSP Expression Scripting Element

JSP Expressions scripting elements

  • To embed Java coding into a JSP page, you need to use scripting elements. There are three scripting elements. available: Declarations, Scriptlets, and Expressions.
  • Expressions scripting elements are used to output values to the JSP pages.
  • Expressions scripting cannot be used to define a method; only declarations scripting can be used for that.
  • Expressions scripting cannot be used to define program flow.
  • Expressions scripting must not end with a semicolon as statement must end with in declarations or dcriptlets types.
  • You can have multiple expressions scripting elements within a single JSP page.
  • JSP expressions scripting elements are specified either in the form of XML tags, or in the form of a JSP style notations.
    Here is the notation for the Expressions scripting element:
    JSP Style or XML Description
    <%= expression %> or
    <jsp:expression > content </jsp:expression>
    The content of expression scripting is a java expression that returns a value.

Example of using JSP expression scripting element.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ExpressionScripting).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h1>Short Country List</h1>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr>
    Listing date <%= (new java.util.Date()).toString() %>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

In this example, we will add two java files, Country.java and CountryControl.java.

  • We need a java class with information about each country that we want to list through a CountryControl class.
    Here is the Country.java:
    package app;
    
    public class Country {
    
      private String flag;
      private String name;
      private String fullName;
      private String capital;
      private String phoneCode;
      private String topLevelDomain;
      private String region;
    
      public Country(String flag, String name, String fullName, 
              String capital, String phoneCode, 
              String topLevelDomain, String region) {
        this.flag = flag;
        this.name = name;
        this.fullName = fullName;
        this.capital = capital;
        this.phoneCode = phoneCode;
        this.topLevelDomain = topLevelDomain;
        this.region = region;
      }
    
      public String getFlag() {
        return flag;
      }
    
      public String getName() {
        return name;
      }
    
      public String getFullName() {
        return fullName;
      }
    
      public String getCapital() {
        return capital;
      }
    
      public String getPhoneCode() {
        return phoneCode;
      }
    
      public String getTopLevelDomain() {
        return topLevelDomain;
      }
    
      public String getRegion() {
        return region;
      }
     }

    For those who participate in the review: create a java class in Netbeans and replace generated code for the java file with that shown above (the java file name is Country and package should be app).

  • We want to to list flag image, name, full name, capital, phone code, top level domain endings and region of each country through help of the CountryControl class.
  • We need a Java class, CountryControl.java, that handles the existence of each country in a list and can give us the list when we need it in our JSP.
    Here is the CountryControl.java:
    package app;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CountryControl {
      private List<Country>  countries= new ArrayList<Country>();
    
      public CountryControl() {
        countries.add(new Country("images/azerbaijan.png","Azerbaijan",
                "Republic of Azerbaijan","Baku","+994",".az","Asia"));
        
        countries.add(new Country("images/bahamas.png","Bahamas",
                "Commonwealth of the Bahamas","Nassau","+1-242",".bs","America"));
        
        countries.add(new Country("images/bahrain.png","Bahrain",
                "Kingdom of Bahrain","Manama","+973",".bx","Asia"));
        
        countries.add(new Country("images/bangladesh.png","Bangladesh",
                "People's Republic of Bangladesh","Dhaka","+880",".bd","Asia"));
      }
    
      public List<Country> getCountries() {
        return countries;
      }
      
    }

    For those who participate in the review: create a java class in Netbeans and replace generated code for the java file with that shown above (the java file name is CountryControl and package should be app).

  • In this class we have a member variable, countries, which shall contain all the registered countries at current time. This is instantiated when an instance of the class is created. We have also added some countries in the default constructor.
  • We have created a method that returns a list of all the registered countries at current time.
  • All the flag photos we need so far must be placed under the web/images directory. You can download the pictures of all the flags here and extract them to the web directory of the project.

Then we need a JSP file to demonstrate how we use the Expression Scripting Element.

  • Here is the main JSP file:
    <%@page import="java.util.List"%>
    <%@page import="app.Country"%>
    <%@page import="app.CountryControl"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Country Liste</title>
        <style>
          .gradientdown {
            background:  #e0e6ff;
            background: -webkit-linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
            background: -o-linear-gradient(#e0e6ff, #eeeeee); /* For Opera 11.1 to 12.0 */
            background: -moz-linear-gradient(top, #e0e6ff, #eeeeee); /* For Firefox 3.6 to 15 */
            background: linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* W3C Standard syntax (must be last) */
          }
          table tr.data:nth-of-type(odd) { 
            background: #eeeeee; 
          }
        </style>
      </head>
      <body>
        <div style="max-width:500px; ">
          <%!
            CountryControl countryControl = new CountryControl();
            List<Country> contries = countryControl.getCountries();
          %>
          <%@ include file="/WEB-INF/header.jsp" %>
          <table >
            <tr class="gradientdown">
              <th style="width:40px;"><br /></th>
              <th style="width:100px;">Name</th>
              <th style="width:200px;">Full Name</th>
              <th style="width:80px;">Capital</th>
              <th style="width:60px;">Phone code</th>
              <th style="width:60px;">TLD</th>
              <th style="width:80px;">Region</th>
            </tr>    
              <%
                for (Country country : contries) {
              %>
            <tr class="data">
              <td style="text-align: center;">
                <img src="<%= country.getFlag()%>" width="20" height="20"
                     alt="<%= country.getName()%>" /></td>
              <td><%= country.getName()%></td>
              <td><%= country.getFullName()%></td>
              <td><%= country.getCapital()%></td>
              <td><%= country.getPhoneCode()%></td>
              <td><%= country.getTopLevelDomain()%></td>
              <td><%= country.getRegion()%></td>
            </tr>
              <%
                }
              %>
          </table>
    
          <%@ include file="/WEB-INF/footer.jsp" %>
        </div>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

How does this work?

  • We have created two JSP files, Header.jsp and Footer,jsp, which we have included in the JSP document, index.jsp.
  • In a declaration scripting elements (<%!) in the index.jsp file we have created an instance of our country controller class and fetched a list of the registered countries at current time.
  • All the java instances in declaration scripting elements (<%!) is related to the life of the JSP not the user session.
  • Because we want to use the CountryControl class and the Country class, we need to import these classes with the page directive.
  • We uses scriptlet scripting to go through the list of all the countries that exists at current time and uses the expression scripting to output data for each country.

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <servlet>
            <servlet-name>CountryList</servlet-name>
            <jsp-file>index.jsp</jsp-file>
        </servlet>
        <servlet-mapping>
            <servlet-name>CountryList</servlet-name>
            <url-pattern>/CountryList</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>CountryList</welcome-file>
        </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url CountryList. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ExpressionScripting) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a Glassfish deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ExpressionScripting</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.