Tecnologie Web: Parte 6d [Martedì, 9 Maggio 2006]

Home /  Teaching


Da JSP a servlet

La pagina jsp, PageCount.jsp, vista a lezione la scorsa volta, viene trasformata dal container Tomcat per poter essere eseguita. Ecco la servlet che si ottiene

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class PageCount_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

 int pageCount = 0;
  void addCount() {
    pageCount++;
  }

  private static java.util.List _jspx_dependants;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    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 {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      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;

      out.write("\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<title>PageCounter.jsp</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
 addCount(); 
      out.write("\r\n");
      out.write("This page has been visited\r\n");
      out.print( pageCount );
      out.write(" times.\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } 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 {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

Scope delle variabili

Le variabili che utilizziamo in una pagina JSP hanno un ben definito "scope", cioè ambito di esistenza. Gli scope predefiniti sono degli oggetti a cui possiamo "legare" altri oggetti durante l'esecuzione della nostra applicazione:

Per legare un oggetto ad un dato contesto, esistono metodi opportuni. Vediamo il caso più utilizzato, quello del contesto di sessione.

I metodi istanza dell'oggetto HttpSession da utilizzare sono:

Verso JSTL: JSP Expression Language

A partire dalla versione 2 di JSP, è stato introdotto un "Expression Language" (EL). JSP EL permette di accedere facilmente a dati di applicazione ed eseguire semplici operazioni, senza dover ricorrere a Java. L'idea (verso cui andremo nel seguito del corso) è quella di tentare di separare, se possibile, completamente la parte Java da quella simil-HTML di JSP. Questo perchè anche un programmatore capace di scrivere pagine HTML fa poca fatica ad apprendere qualche TAG in più. Di certo apprendere Java è tutta un'altra cosa!

Impariamo a prendere confidenza con il JSP EL, tramite alcuni esempi (presi da Tomcat):

L' Expression Language, è un linguaggio semplice che permette di accedere alle variabili contenute nello scope di pagina (PageContext) ed ha un set di oggetti impliciti. Permette di utilizzare in una pagina HTML degli elementi run-time, senza dover ricorrere a scriptlet.

Esistono numerose variabili implicite. Eccone un elenco (da www.oracle.com).

The JSP expression language defines a set of implicit objects, many of which are available in JSP scriplets and expressions:

Term Definition

pageContext

The context for the JSP page. It can be used to access the JSP implicit objects such as request, response, session, out, servletContext etc. For example, ${pageContext.response} evaluates to the response object for the page.

In addition, several implicit objects are available that allow easy access to the following objects:

Term Definition

param

maps a request parameter name to a single String parameter value (obtained by calling ServletRequest.getParameter (String name). The getParameter (String) method returns the parameter with the given name. The expression $(param.name) is equivalent to request.getParameter (name).

paramValues

maps a request parameter name to an array of values (obtained by calling ServletRequest.getParameter (String name). It is very similar to the param implicit object except that it retrieves a string array rather than a single value. The expression ${paramvalues.name) is equivalent to request.getParamterValues(name).

header

maps a request header name to a single String header value (obtained by calling ServletRequest.getHeader(String name). The expression ${header.name} is equivalent to request.getHeader(name).

headerValues

maps a request header name to an array of values (obtained by calling ServletRequest.getHeaders(String)). It is very similar to the header implicit object. The expression ${headerValues.name} is equivalent to request.getHeaderValues(name).

cookie maps cookie names to a single cookie object. A client request to the server can contain one or more cookies. The expression ${cookie.name.value} returns the value of the first cookie with the given name. If the request contains multiple cookies with the same name, then you should use the ${headerValues.name} expression.
initParam maps a context initialization parameter name to a single value (obtained by calling ServletContext.getInitparameter(String name)).