JSP Scriptlet Scripting Element.

JSP Scriptlet 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.
  • Scriptlet scripting elements are used to control flow of data to the JSP pages.
  • Scriptlet scripting cannot be used to define a method; only declarations scripting can be used for that.
  • A programming language variable created within a scriptlet scriptlet is accessible from anywhere within the JSP page.
  • You can have multiple scriptlet scripting elements within a single JSP page. The JSP container will merge them into one when processing the page, so it isn’t necessary to separate them.
  • JSP scriptlet 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 Scriptlet scripting element:
    JSP Style or XML Description
    <% scriptlet code %> or
    <jsp:scriptlet > content </jsp:scriptlet>
    The content of scriptlet scripting is actually code fragments written in Java.

Example of using JSP scriptlet 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 ScriptletScripting).

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>Book inventory control</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>
    Status on <%= (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, Book.java and Library.java.

  • We need a java class with information about each book in a library.
    Here is the Book.java:
    package doc;
    
    public class Book {
    
      private String isbn_no;
      private String short_desc;
      private double price;
    
      public Book(String isbn_no, String short_desc, double price) {
        this.isbn_no = isbn_no;
        this.short_desc = short_desc;
        this.price = price;
      }
    
      public String getIsbn_no() {
        return isbn_no;
      }
    
      public String getShort_desc() {
        return short_desc;
      }
    
      public double getprice() {
        return price;
      }
    }

    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 Book and package should be doc).

  • We want to register isbn number, description and price of each book we have in our library (Perhaps not the most suitable properties for a book in a library, but anyway ...).
  • We need a java class to control what books we have in our library.
    Here is the Library.java:
    package doc;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Library {
    
      private List<Book> books;
    
      public void addBook(Book book) {
        books.add(book);
      }
    
      public Library() {
        books = new ArrayList<Book>();
        addBook(new Book("0201703092", "The Practical SQL", 39));
        addBook(new Book("0471777781", "Professional Ajax", 32));
        addBook(new Book("0764557599", "Professional C#", 42));
      }
    
      public List<Book> getBooks() {
        return books;
      }
    
      public void DeleteBooks(String[] isbns) {
        for (String isbn : isbns) {
          for (Book book : books) {
            if (book.getIsbn_no().equals(isbn)) {
              books.remove(book);
              break;
            }
          }
        }
      }
    }

    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 Library and package should be doc).

  • In this class we have a member variable, books, which shall contain all the books in the library. This is instantiated in the default constructor. We've also added some books in this constructor.
  • Moreover, we have a method to add new books and a method of removing books from the library.
  • Finally, we have created a method that returns a list of all the books in the library.

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

  • Here is the main JSP file:
    <%@page import="java.util.regex.Pattern"%>
    <%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.*, doc.*" %>
    <!DOCTYPE html >
    <html>
      <head>
        <title>Library Book Control</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; 
          }
    
          input[type=text] {
            width: 150px;
            padding:5px; 
            border:2px solid #ccc; 
            -webkit-border-radius: 5px;
            border-radius: 5px;
            background-color: lemonchiffon;
          }
    
          input[type=text]:focus {
            border-color:#000ff;
          }
          input[type=submit] {
            width: 166px;
            padding:5px; 
            background:#e0e6ff; 
            cursor:pointer;
            -webkit-border-radius: 5px;
            border-radius: 5px; 
            border: outset #333 2px;
            margin-top: 10px;
          }
        </style>
      </head>
      <body>
        <div style="max-width:400px; ">
          <%@ include file="/WEB-INF/header.jsp" %>
          <%!
            Library library = new Library();
    
          %>
          <%
            String action = request.getParameter("action");
            if (action != null) {
              if (action.equals("del")) {
                String[] isbns = request.getParameterValues("isbns");
                if (isbns != null) {
                  library.DeleteBooks(isbns);
                }
              }
              if (action.equals("add")) {
                String decimalPattern = "[0-9]+(\\.[0-9][0-9]*)*";
                String isbn_no = request.getParameter("isbn_no");
                String short_desc = request.getParameter("short_desc");
                double price = 0;
                String priceStr = request.getParameter("price");
                boolean match = Pattern.matches(decimalPattern, priceStr);
                if (match) {
                  price = Double.parseDouble(priceStr);
                }
                Book book = new Book(isbn_no, short_desc, price);
                library.addBook(book);
              }
            }
          %>
          <h3>Library book list</h3>
          <form action='index.jsp' method="POST">
            <table  >
              <tr class="gradientdown">
                <th style="width:100px;">Isbn_no</th> 
                <th style="width:150px;">Short desc</th> 
                <th style="width:90px;">Price</th> 
                <th style="width:60px;">Del.</th>
              </tr>
              <%
                List<Book> books = library.getBooks();
                for (Book book : books) {
              %>
              <tr class="data">
                <td><%= book.getIsbn_no()%></td> 
                <td><%= book.getShort_desc()%></td> 
                <td><%= book.getprice()%></td> 
                <td><input type="checkbox" name="isbns" 
                           value="<%= book.getIsbn_no()%>" />
                </td> 
              </tr>       
              <%
                }
              %>
            </table>
            <input type="hidden" name="action" value="del"/>
            <input type="submit"  value="Delete book(s)" />
          </form> 
          <hr>        
          <h3>Add a book</h3>
          <form action='index.jsp' method="POST">
            <table>
              <tr>
                <td><input type="text" name="isbn_no" 
                           placeholder="Isbn number" /></td> 
              </tr>
              <tr>
                <td><input type="text" name="short_desc" 
                           placeholder="Short desc."/></td> 
              </tr>
              <tr>
                <td><input type="text" name="price" 
                           placeholder="Price" /></td> 
              </tr>
            </table>
            <input type="hidden" name="action" value="add"/>
            <input type="submit"  value="Add book" />
          </form>
          <%@ 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 library. Remember that this is not user session related, but is related to the life of the JSP.
  • In a scriptlet scripting we expect one of two action, delete on or more books from the library or add a new book to the library. Java code is implemented for these action in index.jsp file also
  • Because we want to use the library class and the book class, we need to import these classes with the page directive.
  • When any delete or add is finish we uses scriptlet scripting to list all the books that exists in the library with the possibility to delete any of them.
  • At last we have created a form to add a new book to the library.

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>BookControl</servlet-name>
            <jsp-file>/index.jsp</jsp-file>
        </servlet>
        <servlet-mapping>
            <servlet-name>BookControl</servlet-name>
            <url-pattern>/BookControl</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>BookControl</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 BookControl. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ScriptletScripting) for the application will in most cases be specified by a server vendor deployment descriptor.
    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.