Java EE JavaServer Pages, JSPs

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
ViGOur (Обсуждение | вклад)
(Новая: In this part of the Java EE 5 tutorials, we will work with JavaServer Pages (JSPs). JavaServer Pages is a technology, that enables to create HTML dynamically. JSPs are compiled into ser...)
Следующая правка →

Версия 09:38, 25 февраля 2009

In this part of the Java EE 5 tutorials, we will work with JavaServer Pages (JSPs).

JavaServer Pages is a technology, that enables to create HTML dynamically. JSPs are compiled into servlets by a JSP compiler. A JSP page is a text-based document. It can contain two types of text: static data and JSP elements, which determine how the page constructs dynamic content.

JavaServer pages is an integral part of the Java EE platform. Huge enterprise applications are layered. The JSP pages represent the presentation layer of the application. In the MVC (Model, View, Controller) pattern, this is the View part. The data is processed by the business logic of the application. The model loads the data from the database. The data is sent by the controller to the appropriate JSP page for displaying.

The JavaServer Pages consists of several key features:

  • Scripting elements
  • Standard directives
  • Standard actions
  • Tag extensions

JSP pages go through two phases. Translation phase and execution phase. The JSP page is translated once per page. The JSP page is executed once per request. Internally, the JSP page is transformed into servlet, which is then compiled.

The JSP pages have a .jsp extension.


Содержание

Scripting elements

We have declarations, expressions and scriptlets. Scripting elements are used to manipulate objects and perform calculations. Scripting in done in the Java language. Each of them is put inside specific tags.

<%! declaration %>
<% scriptlet %>
<%= expression %>

Declaration is used to declare variables and methods in a JSP page. Scriptlet is a piece of java code. It performs some dynamic action within a JSP page. It can manipulate objects or print some text or html data. Expression outputs data, which is displayed in a browser.

Celsius to Fahrenheit

In the following example, we use all three elements. We will convert Celsius temperature to Fahrenheit.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
 
<html>
  <head>
      <title>Fahrenheit</title>
 
      <style>
          * { font-size: 12px; font-family: Verdana }
      </style>
  </head>
  <body>
      <h2>Fahrenheit</h2>
 
      <%!
        double fahr1, fahr2, fahr3;
        int cels1 = 20;
        int cels2 = 36;
        int cels3 = 45;
 
        double calculate(int cels) {
            return cels * 9 / 5.0 + 32;
        }
      %>
 
      <%
        fahr1 = calculate(cels1);
        fahr2 = calculate(cels2);
        fahr3 = calculate(cels3);
      %>
 
      <p>
       <%= cels1 %> Celsius is <%= fahr1 %> Fahrenheit<br>
 
       <%= cels2 %> Celsius is <%= fahr2 %> Fahrenheit<br>
       <%= cels3 %> Celsius is <%= fahr3 %> Fahrenheit<br>
 
      </p>
 
  </body>
</html>
  <%!
    double fahr1, fahr2, fahr3;
    int cels1 = 20;
    int cels2 = 36;
    int cels3 = 45;
 
    double calculate(int cels) {
        return cels * 9 / 5.0 + 32;
    }
  %>

In this declaration, we declare six variables and one function.

  <%
    fahr1 = calculate(cels1);
    fahr2 = calculate(cels2);
    fahr3 = calculate(cels3);
  %>

In the scriptlet, we perform the computation.

  <p>
   <%= cels1 %> Celsius is <%= fahr1 %> Fahrenheit<br>
   <%= cels2 %> Celsius is <%= fahr2 %> Fahrenheit<br>
 
   <%= cels3 %> Celsius is <%= fahr3 %> Fahrenheit<br>
  </p>

In the expression, we output the variables.

center


From JSP to a servlet

Next we will show, how a container transforms a JSP page to a servlet.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
<html>
    <head>
        <style>
            * { font-size: 12px; font-family: Verdana }    
        </style>
 
        <title>SimpleJSP</title>
    </head>
    <body>
 
        <%= "Simple JSP page" %>
 
    </body>
 
</html>

We will have this simple JSP page. All it does is print some text. We will look, how a container transforms the page into a servlet.

package org.apache.jsp;
 
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
 
public final class index_jsp extends 
                   org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
 
  private static final JspFactory _jspxFactory = 
                   JspFactory.getDefaultFactory();
 
  private static java.util.Vector _jspx_dependants;
 
  private org.apache.jasper.runtime.ResourceInjector 
                   _jspx_resourceInjector;
 
  public Object getDependants() {
    return _jspx_dependants;
  }
 
  public void _jspService(HttpServletRequest request, 
               HttpServletResponse response)
        throws java.io.IOException, ServletException {
 
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;
 
 
    try {
      response.setContentType("text/html;charset=UTF-8");
      response.setHeader("X-Powered-By", "JSP/2.1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector)
         application.getAttribute("com.sun.appserv.jsp.resource.injector");
 
      out.write("\n");
      out.write("\n");
      out.write("<html>\n");
      out.write("  <head>\n");
      out.write("      <style>\n");
      out.write("       * { font-size: 12px; font-family: Verdana } \n");
      out.write("      </style>\n");
      out.write("      <title>SimpleJSP</title>\n");
      out.write("  </head>\n");
      out.write("  <body>\n");
      out.write("      \n");
      out.write("        ");
      out.print( "Simple JSP page" );
      out.write("\n");
      out.write("      \n");
      out.write("  </body>\n");
      out.write("</html>\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) 
            _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

This is the code generated by the Glassfish. Note that different containers will generate different code. To see the servlet code in Netbeans IDE, we run the application first. Then we right click on the jsp page in the Projects window and select option View Servlet.

center

Directives

Directives are messages to the JSP container. There are three main directives.

  • page
  • include
  • taglib

The page directive defines several properties for a JSP page.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
 
<html>
  <head>
    <style>
 
      * { font-size: 12px; font-family: Verdana }
    </style>
    <title>Партизанская</title>
  </head>
 
 <body>
 <h3>По долинам и по взгорьям</h3>
 
 <pre>
   По долинам и по взгорьям
Шла дивизия вперед,
Чтобы с бою взять Приморье -
Белой армии оплот.
 
Наливалися знамена
кумачом последних ран,
Шли лихие эскадроны
Приамурских партизан.
 
Этих лет не смолкнет слава,
Не померкнет никогда,
Партизанские отряды
Занимали города.
 
И останутся как в сказке,
Как манящие огни,
Штурмовые ночи Спасска,
Волочаевские дни.
 
Разгромили атаманов,
Разогнали воевод,
И на Тихом океане
Свой закончили поход. 
 </pre>
 </body>
</html>

The example illustrates the pageEncoding attribute of the page directive. We display text of a song in russian language.

 <%@page contentType="text/html" pageEncoding="UTF-8"%>

The directive sets the encoding to UTF-8. It covers also the russian language. If we would not set this encoding, the JSP page would use the default ISO-8859-1 encoding. The page would not display the text correctly.

center

The contentType attribute defines the MIME type. It tells the browser, how to interprete the data. The default contentType is text/html. In this case, the client browser interpretes all the html code. The
is a new line,

a paragraph etc.
<%@page contentType="text/plain" pageEncoding="UTF-8"%>
 
<html>
    <head>
        <style>
            * { font-size: 12px; font-family: Verdana }    
        </style>
 
        <title>ContentType</title>
    </head>
    <body>
 
       <b>Plain text content type</b>
 
    </body>
</html>

If we set the contentType to text/plain, we tell the browser to interprete all textual data as simple text. So the html tags are not interpreted and are simply displayed.

center

Error page

We can use the errorPage attribute to handle exceptions in the JSP page.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
<%@page errorPage="errorPage.jsp" %>
 
<html>
    <head>
        <title>JSP Page</title>
    </head>
 
    <body>
        <%
            int num = 77 / 0;  
        %>
    </body>
</html>

An exception occurs in this JSP page. Our exception will raise, when we try to divide by zero.

 <%@page errorPage="errorPage.jsp" %>

With the errorPage attribure, we tell the container to show the errorPage.jsp, if there is some exception.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page isErrorPage="true" %>
 
<html>
    <head>
        <title>Error occured</title>
        <style>
 
            * { font-size: 12px; font-family: Verdana }    
        </style>
    </head>
    <body>
        <h2>Error</h2>
 
        <%= exception.getMessage() %>
 
    </body>
</html>

Here we process the exception.

 <%@page isErrorPage="true" %>

With the isErrorPage attribute, we make the exception object available to this JSP page.

 <%= exception.getMessage() %>

We display the error message.

center

If we do not provide an error page, we get an error message from the container.

center

The include directive enables us to organize the code effectively. All websites have repeating code. An example is the common copyright notice or navigation menu. If the website grows larger, it gets time consuming to correct the code in all files. When the year changes, we should change the copyright notice in all files. This is not possible with simple html.

.left {
    position: absolute;
    left:10px;
    top:55px;
    width:200px; height:200px;
    border:1px solid #4B8699;
}
 
.center {
    position: relative;
    top:1px;
    margin-left: 210px;
    margin-right:210px;
    border:1px solid #4B8699;
    height:200px;
}
 
.right {
    position: absolute;
    right:10px;
    top:55px;
    width:200px; height:200px;
    border:1px solid #4B8699;
}
 
 
.banner {
  border:1px solid #4B8699;
  height:44px;
}
 
.footer {
  margin-top:3px;
  border: 1px solid #4B8699;
  height:35px;
  text-align:center;
  padding-top:9px;
}
 
 
* { font-size: 12px; font-family: Verdana }
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 
<html>
    <head>
        <title>Include</title>
 
        <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
 
      <div class="banner">
      </div>
 
      <div class="left">
      </div>
 
      <div class="center">
      </div>
 
      <div class="right">
 
      </div>
 
      <div class="footer">
          <%@ include file="WEB-INF/jspf/footer.jspf" %>
      </div>
 
    </body>
 
</html>

We divide our page into five parts. We use include directive to include the copyright notice into the footer.

 <%@ include file="WEB-INF/jspf/footer.jspf" %>

Here we include the footer. The included code fragments have a .jspf ending.

<%@ page pageEncoding="UTF-8" %>
 
<div><b>ZetCode</b> @ 2007 - 2008 Jan Bodnar</div>

If we use include files, we need to update the text only once.

center

The taglib directive defines a tag library and prefix for the custom tags used in the JSP page. We will use this directive later in our Java EE 5 tutorials. When we will work with custom JSP tags.

Deploying a web application

We will deploy our first web application, using the Resin application server.

<html>
<head>
 
<title>Date</title>
</head>
<body>
 
<p>
Date: <%= new java.util.Date() %>
</p>
 
</body>
 
</html>

The simple jsp file consists of html code and java code. Here we use a jsp expression, which will output the current date.

$ ls
index.jsp

In our working directory, we have only one file named index.jsp. And now, we need to deploy it to the server.

Deployment of web applications is similar to installing classical programs on desktop. These are steps needed to run the web application.

In Java EE a web application is called a web module. It is the simplest deployable unit.

$ ./httpd.sh start
Resin/3.1.3 started -server ''.

First, we start the Resin server. The httpd.sh script is located in the bin directory.

$ jar -cvf date.war *
added manifest
adding: index.jsp(in = 110) (out= 85)(deflated 22%)

We create a web archive.

$ ls
date.war  index.jsp

We have created a war file.

$ mv date.war /home/vronskij/bin/resin/webapps/

We move the war file to the Resin AS webapps subdirectory. Here you must provide your own path to the directory depending on where you have installed the Resin server. By moving the war file to the webapps directory, the application is deployed and we can test it. Note that it is possible to deploy a web application, while the server is running.


Our JSP file displays current date. We write http://localhost:8080/date/ to our web browser to test the outcome. The localhost:8080 means, that we test our application on our local machine and the Resin server listens on 8080 port. The date path is called the context path. It is the context root or path to our application. We can have several applications deployed at one time. The context path can be specified in configuration files. When it is not, than it is equal to the war file name.

center