Difference between revisions of "SCWCD"

From no name for this wiki
Jump to: navigation, search
(tld)
(FORM)
 
(16 intermediate revisions by the same user not shown)
Line 345: Line 345:
  
 
==== FORM ====
 
==== FORM ====
 +
 +
Example of form based login jsp or html page:
 +
 +
<form method="POST" action="j_security_check">
 +
  <input type="text" name="j_username"/>
 +
  <input type="password" name="j_password"/>
 +
</form>
 +
 
==== CLIENT-CERT ====
 
==== CLIENT-CERT ====
  
Line 375: Line 383:
 
* import
 
* import
 
* info
 
* info
 +
* pageEncoding
 +
* contentType
  
 
==== include ====
 
==== include ====
Line 394: Line 404:
 
* tagdir: Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used.  
 
* tagdir: Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used.  
 
* prefix
 
* prefix
 +
 +
==== tag ====
 +
Definiert ein tag.
 +
 +
Attributes:
 +
* display-name:
 +
* body-content: scriptless | tagdependent | empty
 +
* dynamic-attributes: page-scoped attribute
 +
* small-icon: relativeURL
 +
* large-icon: relativeURL
 +
* description: text
 +
* example: text
 +
* language: Nur java
 +
* import:
 +
* pageEncoding:
 +
* isELIgnored: true | false
 +
 +
==== attribute ====
 +
Definiet ein Attribut eines Tags.
 +
 +
 +
Attributes:
 +
 +
* name: "attribute-name"
 +
* required: true | false
 +
* fragment: true | false
 +
* rtexprvalue: true | false
 +
* type: java.lang.String | a non-primitive type. Wenn ein primitiver Typ angegeben wird, wird eine Runtime-Exception geworfen.
 +
* description: text
 +
 +
==== variable ====
 +
Definiert eine Variable eines Tags.
 +
 +
Attributes:
 +
 +
* name-given: scripting variable. Es kann entweder name-given oder name-from-attribute angegeben werden. Ist name-given gewählt, dann enthält das page-scoped Attribut den namen des page-scoped Attributes, welches dann wiederum den Namen der Variable enthält.
 +
* name-from-attribute: scripting variable.  Es kann entweder name-given oder name-from-attribute angegeben werden. Das entsprechende Attribut enthält den Namen der Variable. Kann in Kombination mit alias verwendet werden.
 +
* alias: Defines a variable, local to the tag file, to hold the value of the EL variable. The container will synchronize this value with the variable whose name is given in name-from-attribute. Nur mit name-from-variable gültig.
 +
* variable-class: java.lang.String" | name of the variable class
 +
* declare: true | false
 +
* scope: AT_BEGIN | AT_END | NESTED
 +
* description: text
  
 
=== JSP Document (xml) ===
 
=== JSP Document (xml) ===
Line 545: Line 597:
  
 
=== jsp:include ===
 
=== jsp:include ===
[http://java.sun.com/products/jsp/syntax/2.0/syntaxref2020.html#8828 jsp:include] Es gibt statische und dynamische includes. Der AppServer entschieded selber.  
+
[http://java.sun.com/products/jsp/syntax/2.0/syntaxref2020.html#8828 jsp:include] Es gibt statische und dynamische includes. Der AppServer entscheidet selber.  
 
Exapmles:
 
Exapmles:
 
  <jsp:include page="scripts/login.jsp" />
 
  <jsp:include page="scripts/login.jsp" />
Line 769: Line 821:
 
Die Klasse ist [http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/JspContext.html JSPContext].
 
Die Klasse ist [http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/JspContext.html JSPContext].
  
Methoden sind:
+
Methoden von PageContext sind:
 
* getErrorData
 
* getErrorData
 
* getException
 
* getException
Line 908: Line 960:
  
 
mytaglib.tld Dateien werden entweder im WEB-INF, META-INF, oder in der Jar Datei einer Taglibrary. In diesen Dateien können auch Listeners registriert werden, wie im web.xml. Validatoren können ebenfalls registriert werden.
 
mytaglib.tld Dateien werden entweder im WEB-INF, META-INF, oder in der Jar Datei einer Taglibrary. In diesen Dateien können auch Listeners registriert werden, wie im web.xml. Validatoren können ebenfalls registriert werden.
 +
 +
==== body-content element ====
 +
Mögliche Werte:
 +
* scriptless: Enthält EL und andere Tags.
 +
* tagdependent: Der Inhalt wird vom Tag interpretiert.
 +
* empty: Kein Body.
  
 
=== dynamische attribute in taghandlers ===  
 
=== dynamische attribute in taghandlers ===  

Latest revision as of 09:13, 24 October 2009

Contents

Section 1: The Servlet Technology Model

HTTP Methods

For each of the HTTP Methods (such as GET, POST, HEAD, and so on) describe the purpose of the method and the technical characteristics of the HTTP Method protocol, list triggers that might cause a Client (usually a Web browser) to use the method; and identify the HttpServlet method that corresponds to the HTTP Method.

  • GET doGet
  • POST doPost
  • HEAD, Wie GET, aber kein Message-Body in der Response. doHead
  • DELETE doDelete
  • PUT doPut
  • TRACE loop- back of the request message doTrace
  • CONNECT This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel.
  • OPTIONS Gibt dem Client Antwort, welche Methoden unterstützt sind. doOptions

HttpServletRequest

Using the HttpServletRequest interface, write code to retrieve HTML form parameters from the request, retrieve HTTP request header information, or retrieve cookies from the request.

HttpServletResponse

Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.

public class RedirectWithLinkServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  
    Cookie cookie = new Cookie("name", "val");
    response.addCookie(cookie);

    response.setHeader("Refresh", "5");


    PrintWriter out = response.getWriter();



    response.setContentType("text/html");
    out.println("<html><body></body></html>");   
   
    return;
  }
}

Other Methods:

Servlet life cycle

Describe the purpose and event sequence of the servlet life cycle:

  • servlet class loading
  • servlet instantiation
  • call the init method
  • call the service method
  • call destroy method.

Section 2: The Structure and Deployment of Web Applications

Construct the file and directory structure of a Web Application that may contain (a) static content, (b) JSP pages, (c) servlet classes, (d) the deployment descriptor, (e) tag libraries, (d) JAR files, and (e) Java class files; and describe how to protect resource files from HTTP access.

Deployment descriptor

Describe the purpose and semantics of the deployment descriptor. Construct the correct structure of the deployment descriptor.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <description>a desc</description>
    <display-name>a name</display-name>
    <context-param>
        <param-name>parametersample</param-name>
        <param-value>parameter value</param-value>
    </context-param>
    <context-param>
        <description>a param desc</description>
        <param-name>anotherparam</param-name>
        <param-value>anothervalue</param-value>
    </context-param>
    <filter>
        <filter-name>NewSimpleFilter</filter-name>
        <filter-class>demo.NewSimpleFilter</filter-class>
        <init-param>
            <param-name>aparam</param-name>
            <param-value>avalue</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>NewSimpleFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <description>sdfsd</description>
        <listener-class>demo.SessionListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>Demoservlet</servlet-name>
        <servlet-class>demo.Demoservlet</servlet-class>
        <init-param>
            <description>sdfsd</description>
            <param-name>servletparam</param-name>
            <param-value>servletvalue</param-value>
        </init-param>
        <init-param>
            <description>sadfds</description>
            <param-name>sfs</param-name>
            <param-value>safs</param-value>
        </init-param>
        <run-as>
            <role-name>restrictedrole</role-name>
        </run-as>
        <security-role-ref>
            <description>sdfsd</description>
            <role-name>aref</role-name>
            <role-link>restrictedrole</role-link>
        </security-role-ref>
        </servlet>
    <servlet-mapping>
        <servlet-name>Demoservlet</servlet-name>
        <url-pattern>/Demoservlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    <error-page>
        <error-code>402</error-code>
        <location>/errormy.jsp</location>
    </error-page>
    <jsp-config>
        <jsp-property-group>
            <description>sdfsd</description>
            <display-name>mygourp</display-name>
            <url-pattern>/index.jsp</url-pattern>
            <url-pattern>/blabla.jsp</url-pattern>
            </jsp-property-group>
        </jsp-config>
    <security-constraint>
        <display-name>Constraint1</display-name>
        <web-resource-collection>
            <web-resource-name>a resource</web-resource-name>
            <description/>
            <url-pattern>/**</url-pattern>
            <url-pattern>/index.jsp</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>sdfsd</description>
            <role-name>restrictedrole</role-name>
            </auth-constraint>
        <user-data-constraint>
            <description/>
            <transport-guarantee>INTEGRAL</transport-guarantee>
        </user-data-constraint>
        </security-constraint>
    <security-role>
        <description>a desc</description>
        <role-name>restrictedrole</role-name>
    </security-role>
    </web-app>


Explain the purpose of a WAR file and describe the contents of a WAR file, how one may be constructed.

Section 3: The Web Container Model

ServletContext

For the ServletContext initialization parameters: write servlet code to access initialization parameters; and create the deployment descriptor elements for declaring initialization parameters.

Scopes

For the fundamental servlet attribute scopes (request, session, and context): write servlet code to add, retrieve, and remove attributes; given a usage scenario, identify the proper scope for an attribute; and identify multi-threading issues associated with each scope.

request processing model

Describe the Web container request processing model; write and configure a filter; create a request or response wrapper; and given a design problem, describe how to apply a filter or a wrapper.

Web container life cycle

Describe the Web container life cycle event model for requests, sessions, and web applications;create and configure listener classes for each scope life cycle; create and configure scope attribute listener classes; and given a scenario, identify the proper attribute listener to use.

  • javax.servlet.http.HttpSessionListener: Wird aufgerufen, wenn eine Session erstellt oder entfernt wird.
  • javax.servlet.ServletContextListener: Wird aufgerufen, wenn die Applikation startet oder gestoppt wird.
  • javax.servlet.ServletRequestListener: Bei jedem Request wird der aufgerufen.
  • javax.servlet.http.HttpSessionAttributeListener: Für Attribute in der Session.
  • javax.servlet.ServletRequestAttributeListener: Für Attribute im Request.
  • javax.servlet.http.HttpSessionAttributeListener: Für Attribute in der Session.


Andere Listeners:

  • javax.servlet.http.HttpSessionBindingListener: Objekte werden informiert, wenn sie in die Session gespeichert werden.
  • javax.servlet.http.HttpSessionActivationListener: Ist nur in Cluster relevant. Wenn Session persistiert oder geladen werden, werden die Objekte informiert.

RequestDispatcher

Describe the RequestDispatcher mechanism; write servlet code to create a request dispatcher; write servlet code to forward or include the target resource; and identify and describe the additional request-scoped attributes provided by the container to the target resource.

   //Variante1
   RequestDispatcher disp = request.getRequestDispatcher("hello.jsp");//relative resource
   disp.forward(request, response);

   //Variante2
   RequestDispatcher disp = request.getSession().getServletContext().getRequestDispatcher("/someresource");//relative resource
   disp.forward(request, response);

   //Variante3
   RequestDispatcher disp = request.getSession().getServletContext().getNamedDispatcher("servletname");//servlet name
   disp.forward(request, response);

Zum Dispatcher kommt mann ueber request oder servletContext. Nur der vom Request verträgt relative URLs. Folgende page attribute werden bei include und forward gesetzt (aber nicht mit getNamedDispatcher):

  • javax.servlet.forward.request_uri
  • javax.servlet.forward.context_path
  • javax.servlet.forward.servlet_path
  • javax.servlet.forward.path_info
  • javax.servlet.forward.query_string

AND

  • javax.servlet.include.request_uri
  • javax.servlet.include.context_path
  • javax.servlet.include.servlet_path
  • javax.servlet.include.path_info
  • javax.servlet.include.query_string

Erklärungen

  • request_uri: Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. Beispiel HEAD /xyz?a=b HTTP/1.1 ergibt /xyz
  • path_info: Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character. Same as the value of the CGI variable PATH_INFO.
  • servlet_path: Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME. This method will return an empty string ("") if the servlet used to process this request was matched using the "/*" pattern.
  • query_string: Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
  • context_path: Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.


Beispiel:

Werte für URL im Browser: http://localhost:8080/JspTests/newjsp.jsp?boss=claude

path_info: null
context_path: /JspTests 
servlet_path: /newjsp.jsp 
request_uri: /JspTests/newjsp.jsp
request_url: http://localhost:8080/JspTests/newjsp.jsp
query_string: boss=claude

Siehe:

Section 4: Session Management

session in servlet

Write servlet code to store objects into a session object and retrieve objects from a session object.

session access api

Given a scenario describe the APIs used to access the session object, explain when the session object was created, and describe the mechanisms used to destroy the session object, and when it was destroyed.

session listeners

Using session listeners, write code to respond to an event when an object is added to a session, and write code to respond to an event when a session object migrates from one VM to another.

session tracking

Given a scenario, describe which session management mechanism the Web container could employ, how cookies might be used to manage sessions, how URL rewriting might be used to manage sessions, and write servlet code to perform URL rewriting.

Section 5: Web Application Security

keywords

Based on the servlet specification, compare and contrast the following security mechanisms: (a) authentication, (b) authorization, (c) data integrity, and (d) confidentiality.

deployment descriptor

In the deployment descriptor, declare a security constraint, a Web resource, the transport guarantee, the login configuration, and a security role.

 <security-constraint>
        <display-name>Constraint1</display-name>
        <web-resource-collection>
            <web-resource-name>Restricted1</web-resource-name>
            <description>my description</description>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>My descritption</description>
            <role-name>visitor</role-name>
        </auth-constraint>
        <user-data-constraint>
            <description>My description</description>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
 </security-constraint>
 <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>admin-realm</realm-name>
 </login-config>
 <security-role>
        <description/>
        <role-name>visitor</role-name>
 </security-role>

Alternative login-config:

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name/>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/loginerror.jsp</form-error-page>
        </form-login-config>
   </login-config>

Authenticationtypes

Compare and contrast the authentication types (BASIC, DIGEST, FORM, and CLIENT-CERT); describe how the type works; and given a scenario, select an appropriate type.

BASIC

Der Browser zeigt ein Dialog mit Username und Passwort.

DIGEST

Digest authentication is just like basic authentication, except digest authentication uses encryption to protect passwords. In fact, digest authentication transmits a password's hash value, not the password itself. Im web.xml:

<login-config>
   <auth-method>DIGEST</auth-method> 
   <realm-name>Digest Authentication Example</realm-name> 
 </login-config>

FORM

Example of form based login jsp or html page:

<form method="POST" action="j_security_check">
  <input type="text" name="j_username"/>
  <input type="password" name="j_password"/>
</form>

CLIENT-CERT

Section 6: The JavaServer Pages (JSP) Technology Model

Siehe auch jsp

JSP elements

Identify, describe, or write the JSP code for the following elements: (a) template text, (b) scripting elements (comments, directives, declarations, scriptlets, and expressions), (c) standard and custom actions, and (d) expression language elements.

Directives

Write JSP code that uses the directives: (a) 'page' (with attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b) 'include', and (c) 'taglib'.


page

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

Siehe referenz

Attributes:

  • language
  • extends
  • isThreadSafe
  • session
  • buffer
  • autoFlush
  • errorPage
  • isErrorPage
  • isELIgnored
  • import
  • info
  • pageEncoding
  • contentType

include

Siehe referenz

Attributes:

  • file: If the relative URL starts with /, the path is relative to the JSP application's context, which is a javax.servlet.ServletContext object that is in turn stored in the application object. If the relative URL starts with a directory or file name, the path is relative to the JSP page.

taglib

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="i" uri="http://www.simpletag.com"%>

Siehe referenz

Attributes:

  • uri: The Uniform Resource Identifier (URI) that uniquely locates the TLD that describes the set of custom tags associated with the named tag prefix. A URI can be any of the following: Uniform Resource Locator (URL), A Uniform Resource Name (URN), An absolute or relative pathname. If the URI is a URL or URN, then the TLD is located by consulting the mapping indicated in web.xml extended using the implicit maps in the packaged tag libraries. If URI is pathname, it is interpreted relative to the root of the web application and should resolve to a TLD file directly, or to a JAR file that has a TLD file at location META-INF/taglib.tld.
  • tagdir: Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used.
  • prefix

tag

Definiert ein tag.

Attributes:

  • display-name:
  • body-content: scriptless | tagdependent | empty
  • dynamic-attributes: page-scoped attribute
  • small-icon: relativeURL
  • large-icon: relativeURL
  • description: text
  • example: text
  • language: Nur java
  • import:
  • pageEncoding:
  • isELIgnored: true | false

attribute

Definiet ein Attribut eines Tags.


Attributes:

  • name: "attribute-name"
  • required: true | false
  • fragment: true | false
  • rtexprvalue: true | false
  • type: java.lang.String | a non-primitive type. Wenn ein primitiver Typ angegeben wird, wird eine Runtime-Exception geworfen.
  • description: text

variable

Definiert eine Variable eines Tags.

Attributes:

  • name-given: scripting variable. Es kann entweder name-given oder name-from-attribute angegeben werden. Ist name-given gewählt, dann enthält das page-scoped Attribut den namen des page-scoped Attributes, welches dann wiederum den Namen der Variable enthält.
  • name-from-attribute: scripting variable. Es kann entweder name-given oder name-from-attribute angegeben werden. Das entsprechende Attribut enthält den Namen der Variable. Kann in Kombination mit alias verwendet werden.
  • alias: Defines a variable, local to the tag file, to hold the value of the EL variable. The container will synchronize this value with the variable whose name is given in name-from-attribute. Nur mit name-from-variable gültig.
  • variable-class: java.lang.String" | name of the variable class
  • declare: true | false
  • scope: AT_BEGIN | AT_END | NESTED
  • description: text

JSP Document (xml)

Write a JSP Document (XML-based document) that uses the correct syntax.

sample

Anbei ein Beispiel:

<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:jsp="http://java.sun.com/JSP/Page">
<head><title>Hello</title></head>
<body bgcolor="white">
<jsp:useBean id="adate" class="java.util.Date" scope="request"/>
<jsp:setProperty name="adate" property="time" value="${1000}" />
<c:out value="${adate}"/>
</body>
</html>

enabling xml

  • Dateien mit der Endung .jspx. Ab servlet 2.4.
  • In your application’s web.xml file, set the is-xml element of the jsp-property-group

element to true.

  • Include a jsp:root element in your JSP document. This method is backward-compatible

with JSP 1.2.

directives

<jsp:directive.page pageDirectiveAttrList />

jsp:root

<jsp:root 	
   xmlns:jsp="http://java.sun.com/JSP/Page"	
   xmlns:public="http://www.jspcentral.com/tags" 	
   version="2.0">	
   <public:loop>...</public:loop>	
</jsp:root>

JSP page life cycle

Describe the purpose and event sequence of the JSP page life cycle: (1) JSP page translation, (2) JSP page compilation, (3) load class, (4) create instance, (5) call the jspInit method, (6) call the _jspService method, and (7) call the jspDestroy method.

Die Methode jspInit und jspDestroy können in der JSP überschrieben werden, die _jspService Methode nicht.

implicit objects

Given a design goal, write JSP code using the appropriate implicit objects: (a) request, (b) response, (c) out, (d) session, (e) config, (f) application, (g) page, (h) pageContext, and (i) exception.

options and include

Configure the deployment descriptor to declare one or more tag libraries, deactivate the evaluation language, and deactivate the scripting language. 6.7 Given a specific design goal for including a JSP segment in another page, write the JSP code that uses the most appropriate inclusion mechanism (the include directive or the jsp:include standard action).

Unterschied zwischen jsp:include und include directive ist: include directive kann nur statischen content includen. Hier die beschreibung von inlude directive:

Includes a static file in a JSP page, parsing the file's JSP elements.

Unterschied zwischen static und dynamic:

The results of including static and dynamic resources are quite different. 
If the resource is static, its content is included in the calling JSP page. 
If the resource is dynamic, it acts on 
a request and sends back a result that is included in the JSP page.


Enabling and disabling EL:

    <jsp-config>
        <jsp-property-group>
            <description>sdfsd</description>
            <display-name>mygourp</display-name>
            <url-pattern>/index.jsp</url-pattern>
            <url-pattern>/blabla.jsp</url-pattern>
            <el-ignored>true</el-ignored>
            <is-xml>false</is-xml>
            <scripting-invalid>true</scripting-invalid>
         </jsp-property-group>
    </jsp-config>

Folgende Optionen können in jsp-property-group gesetzt werden:

  • description
  • display-name
  • url-pattern
  • page-encoding
  • el-ignored
  • is-xml
  • scripting-invalid
  • include-prelude: The include-prelude element is a context-relative path that must correspond to an element in the Web application. When the element is present, the given path will be automatically included (asin an include directive) at the beginning of each JSP page in this jsp-property-group.
  • include-coda: Wie oben, aber am Ende.
  • deferred-syntax-allowed-as-literal: The character sequence #{ is reserved for EL expressions. Consequently, a translation error occurs if the #{ character sequence is used as a String literal, unless this element is enabled (true). Disabled (false) by default.
  • trim-directive-whitespaces: Indicates that template text containing only whitespaces must be removed from the response output. It has no effect on JSP documents (XML syntax). Disabled (false) by default.


Importing taglibs

<taglib>
	<taglib-uri>/myPRlibrary</taglib-uri>
	<taglib-location>/WEB-INF/tlds/PRlibrary_1_4.tld</taglib-location>
</taglib>

Section 7: Building JSP Pages Using the Expression Language (EL)

implicit variables

Given a scenario, write EL code that accesses the following implicit variables including pageScope, requestScope, sessionScope, and applicationScope, param and paramValues, header and headerValues, cookie, initParam and pageContext.

operators

Given a scenario, write EL code that uses the following operators: property access (the . operator), collection access (the [] operator).

Undefinierte variable haben den Wert null, keine Exception wird geworfen:

${1+5+a} druckt 6.

Section 8: Building JSP Pages Using Standard Actions

jsp:useBean

Given a design goal, create a code snippet using the following standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, jsp:setProperty (with all attribute combinations), and jsp:attribute.

Dieses Tag kann einen Body aufweisen.


Nie Attribut class und beanName gleichzeitig anwenden!

Attribute von jsp:useBan:

  • id: A variable that identifies the bean in the scope you specify. You can use the variable name in expressions or scriptlets in the JSP page.
  • scope: "page|request|session|application"
  • class: Instantiates a bean from a class, using the new keyword and the class constructor.
  • type: If the bean already exists in the scope, gives the bean a data type other than the class from which it was instantiated. The value of type must be a superclass of class or an interface implemented by class. If you use type without class or beanName, no bean is instantiated.
  • beanName: Wie class, aber das Bean wir nicht mit dem new Operator erstellt, sondern mit Beans.instantiate.

jsp:setProperty

jsp:setProperty Sets a property value or values in a bean. The jsp:setProperty element sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with <jsp:useBean> before you set a property value with jsp:setProperty. Because jsp:useBean and jsp:setProperty work together, the bean instance names they use must match (that is, the value of name in jsp:setProperty and the value of id in jsp:useBean must be the same).


Attribute von jsp:setPorperty

  • name: The name of an instance of a bean that has already been created or located with a jsp:useBean element. The value of name must match the value of id in jsp:useBean. The jsp:useBean element must appear before jsp:setProperty in the JSP page.
  • property: "*" Stores all of the values of request parameters in bean properties. The names of the bean properties must match the names of the request parameters. A bean property is usually defined by a variable declaration with matching getter and setter methods (for more information, see http://java.sun.com/javase/technologies/desktop/javabeans/docs/).
  • property: "propertyName" [ param="parameterName" ] Sets one bean property to the value of one request parameter. In the syntax, property specifies the name of the bean property and param specifies the name of the request parameter by which data is being sent from the client to the server.
  • property: value="value" Sets one bean property to a specific value. The value can be a String or an expression that is evaluated at runtime. If the value is a String, it is converted to the bean property's data type according to the conversion rules shown above in TABLE 2. If it is an expression, its value must have a data type that matches the data type of the value of the expression must match the data type of the bean property.
  • param
  • value

jsp:getProperty

The jsp:getProperty element gets a bean property value using the property's getter methods and inserts the value into the response. You must create or locate a bean with <jsp:useBean> before you use jsp:getProperty. Attribute von jsp:getProperty

  • name: The name of an object (usually an instance of a bean) as declared in a <jsp:useBean> element.
  • property: The name of the bean property whose value you want to display. The property is declared as a variable in a bean and must have a corresponding getter method (for more information on declaring variables and writing getter methods in beans, see http://java.sun.com/javase/technologies/desktop/javabeans/docs/).

jsp:include

jsp:include Es gibt statische und dynamische includes. Der AppServer entscheidet selber. Exapmles:

<jsp:include page="scripts/login.jsp" />
<jsp:include page="copyright.html" />
<jsp:include page="/index.html" />
<jsp:include page="scripts/login.jsp">	
  <jsp:param name="username" value="jsmith" />	
</jsp:include>

Attribute:

  • page: Relative URL. Kann relativ oder absolut zur Seite sein. Darf aber weder Protokoll noch Portnummer enthalten.
  • flush: true oder false. Default ist false. Bei true wird ein flush vor dem include ausgeführt.

jsp:forward

<jsp:forward page="/servlet/login" />
<jsp:forward page="/servlet/login">	
  <jsp:param name="username" value="jsmith" />	
</jsp:forward>

Das einzige Attribut ist page.

jsp:param

Kann nur in jsp:include oder jsp:forward verwendet werden. Nur bei dynamischen includes sinnvoll.

Attribute von jsp:param:

  • name
  • value

Section 9: Building JSP Pages Using Tag Libraries

taglib directive

For a custom tag library or a library of Tag Files, create the 'taglib' directive for a JSP page.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core";%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

Einfache Tags in files

Given a design goal, create the custom tag structure in a JSP page to support that goal.

/WEB-INF/tags/sometag.tag:

<%@variable name-given="v" scope="AT_END"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core";%>
<c:set var="v" value="1"/>
 ${v}
<jsp:doBody/>
<c:set var="v" value="2"/>

jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"; %>
<html>
<body>
<c:set var="v" value="0"/>
${v}
<t:sometag>
${v}
</t:sometag>
${v}
</body>
</html>

JSTL 1.1

Given a design goal, use an appropriate JSP Standard Tag Library (JSTL v1.1) tag from the "core" tag library.

Der Namespace ist: http://java.sun.com/jsp/jstl/core:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

API Dokumentation: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html


catch

Catches any Throwable that occurs in its body and optionally exposes it.

Attributes:

  • var: Name of the exported scoped variable for the exception thrown from a nested action. The type of the scoped variable is the type of the exception thrown.

forEach

<c:forEach var="item" items="${sessionScope.cart.items}">
 ${item.quantity}
</c:forEach>

Attributes:

  • items: Collection of items to iterate over.
  • begin: If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.
  • end: If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.
  • step: Iteration will only process every step items of the collection, starting with the first one.
  • var: Name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visibility. Its type depends on the object of the underlying collection.
  • varStatus: Name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.

set

Sets the result of an expression evaluation in a 'scope'


Attributes:

  • var, value, scope
  • target: Target object whose property will be set. Must evaluate to a JavaBeans object with setter property property, or to a java.util.Map object.
  • property: Name of the property to be set in the target object.

remove

Removes a scoped variable (from a particular scope, if specified).

Attributes:

  • var, scope

choose

Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>

<c:choose>
  <c:when test="${count == 0}" >
    No records matched your selection.
  </c:when>
  <c:otherwise>
    ${count} records matched your selection.
  </c:otherwise>
</c:choose>

import

Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.

Attributes:

  • url: The URL of the resource to import.
  • var: Name of the exported scoped variable for the resource's content. The type of the scoped variable is String.
  • scope:
  • varReader: Name of the exported scoped variable for the resource's content. The type of the scoped variable is Reader.
  • context: Name of the context when accessing a relative URL resource that belongs to a foreign context.
  • charEncoding:

url

Creates a URL with optional query parameters.

<c:url var="url" value="/catalog" >
  <c:param name="Add" value="${bookId}" />
</c:url>
<a href="${url}">

Attributes:

  • var: Name of the exported scoped variable for the processed url. The type of the scoped variable is String.
  • value: URL to be processed.
  • scope: Scope for var.
  • context: Name of the context when specifying a relative URL resource that belongs to a foreign context.

if

Attributes:

  • test, var, scope

out

Attributes:

  • value, default, escapeXml

forTokens

Iterates over tokens, separated by the supplied delimeters.

<c:forTokens items="a,b,c,d;e;f;g" var="token" delims=",;a">
 X${token}X
</c:forTokens>

Der Output ist:

XbX XcX XdX XeX XfX XgX 

Attributes:

  • items: String of tokens to iterate over.
  • delims: The set of delimiters (the characters that separate the tokens in the string).
  • begin
  • end
  • step
  • var
  • varStatus

param

Attributes:

  • name, value

redirect

Attributes:

  • url: The URL of the resource to redirect to.
  • context: Name of the context when redirecting to a relative URL resource that belongs to a foreign context.

when

Subtag of <choose> that includes its body if its condition evalutes to 'true'

Attributes:

  • test: The test condition that determines whether or not the body content should be processed.

Section 10: Building a Custom Tag Library

Lifecycle

Describe the semantics of the "Classic" custom tag event model when each event method (doStartTag, doAfterBody, and doEndTag) is executed, and explain what the return value for each event method means; and write a tag handler class.

Tag interface

LifeCycle für Tag Interface:

  • 1. Initialisierung: setParent, setPageContext, setters.
  • 2. doStartTag() wird ausgeführt. EVAL_BODY_INCLUDE oder SKIP_BODY sind mögliche Rückgabewerte
  • 3. doEndTag() wird ausgeführt. SKIP_PAGE oder EVAL_PAGE sind mögliche Rückgabewerte.

IterationTag interface

LifeCycle für IterationTag. Siehe BodyTag, aber ohne setBodyContent() Methode und ohne EVAL_BODY_BUFFERED.

Implementierende Klasse: TagSupport

BodyTag interface

LifeCycle für BodyTag Interface:

  • 1. Attribute werden gesetzt.
  • 2. doStartTag() wird ausgeführt. Rückgabewerte sind EVAL_BODY_INCLUDE, EVAL_BODY_BUFFERED oder SKIP_BODY
  • 3. setBodyContent(BodyContent b) wird ausgeführt. BodyContent erbt von JspWriter. Diese Methode wird nur ausgeführt, wenn doStartTag() EVAL_BODY_BUFFERED zurückgibt.
  • 4. doInitBody() wird ausgeführt.
  • 5. doAfterBody() wird ausgeführt. Rückgabewerte sind SKIP_BODY oder EVAL_BODY_AGAIN.
  • 6. doEndTag() wird ausgeführt. SKIP_PAGE oder EVAL_PAGE sind mögliche Rückgabewerte.

Bei Rückgabewert EVAL_BODY_INCLUDE wird das Resultat des Body in den JspWriter geschrieben.

Bei Rückgabewert EVAL_BODY_BUFFERED wird der Body in das Property bodyContent abgelegt.

Implementation BodyTagSupport

JSPContext

Using the PageContext API, write tag handler code to access the JSP implicit variables and access web application attributes. Die Klasse ist JSPContext.

Methoden von PageContext sind:

  • getErrorData
  • getException
  • getPage (Servlet)
  • getRequest
  • getResponse
  • getServletConfig
  • getServletContext
  • getSession
  • handlePageException
  • include
  • release (nur für Container)
  • init (nur für Container)
  • pushBody
  • popBody
  • findAttribute
  • getAttribute

und ein paar mehr.

parent tag

Given a scenario, write tag handler code to access the parent tag and an arbitrary tag ancestor.

Die Klasse TagSupport bietet z.B. findAncestorWithClass

SimpleTag

Describe the semantics of the "Simple" custom tag event model when the event method (doTag) is executed; write a tag handler class; and explain the constraints on the JSP content within the tag. SimpleTag

  • SimpleTag Handlers werden nie gecached
  • Anstatt doStartTag und doEndTag gibt es nur doTag

Der Lifecycle ist wie folgt:

  • 1. Neue Instanz wird mit new kreiert.
  • 2. setJspContext wird ausgeführt.
  • 3. Falls es ein Parent Tag gibt, wird setParent ausgeführt.
  • 4. Setters der Attribute wird aufgerufen.
  • 5. setJspBody wird aufgerufen und ein JspFragment übergeben, falls ein Body vorhanden ist. Blank zeichen ist bereits ein Body.
  • 6. doTag wird aufgerufen
  • 7. Nach return doTag werden Variablen synchronisiert.

Implementierende Klasse: SimpleTagSupport

TagFile

Describe the semantics of the Tag File model; describe the web application structure for tag files; write a tag file; and explain the constraints on the JSP content in the body of the tag.

Es gibt tag-files und tag-handlers. tag-files sind analog zu jsp. tag-handlers sind analog zu servlets.

Tag Files werden im Verzeichnis WEB-INF/tags hinzugefügt. Es braucht kein expliziter Deskriptor, pro unterverzeichnis mit tag-files wird eine Taglib angelegt. Folgende Struktur erstellt 3 Libraries:

/WEB-INF/tags/
/WEB-INF/tags/a.tag
/WEB-INF/tags/b.tag
/WEB-INF/tags/foo/
/WEB-INF/tags/foo/c.tag
/WEB-INF/tags/bar/baz/
/WEB-INF/tags/bar/baz/d.tag

Tag Files können auch in jar Dateien platziert werden: /META-INF/tags/ und die jars können ins WEB-INF/lib Verzeichnis abgelegt werden.

Simple Attribute

Client:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>   
   <body>
       <t:tagexample1 message="hellomessage"/>
   </body>
</html>

Tag:

<%@tag description="put the tag description here" pageEncoding="UTF-8"%>
<%@attribute name="message"%>

dymamic Attribute

Client:

<t:tagexample1 color1="yellow" color2="blue" color3="yellow"/>

Tag (example1.tag im Verzeichnis WEB-INF/tags):

<%@ tag dynamic-attributes="mydynattr"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="mything" items="${mydynattr}">
   ${mything.key} = ${mything.value}
</c:forEach>

fragmented Attributes

Client:

<t:tagexample1>
 <jsp:attribute name="afragmentedattr">
   ${"hello World!"}
 </jsp:attribute>
</t:tagexample1>

Tag:

<%@tag %>
<%@attribute name="afragmentedattr"  fragment="true"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:invoke fragment="afragmentedattr"/>

variable

Client:

<t:tagexample1>
  ${price}
</t:tagexample1>

Tag:

<%@tag %>
<%@variable  name-given="price" scope="NESTED"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="price" value="100"/>
<jsp:doBody/>
${message}

tld

<uri>MySimpleTag</uri>
<tag>
   <name>test</name>
   <tag-class>test.TestSimpleTag</tag-class>
   <body-content>scriptless</body-content>
   
   <attribute>
       <name>attr</name>
       <required>false</required>
       <rtexprvalue>true</rtexprvalue>
   </attribute> 
 
   <variable>
    <name-given>var</name-given>
    <variable-class>java.lang.String</variable-class>
    <declare>true</declare>
    <scope>NESTED</scope>
   </variable>

   <dynamic-attributes>true</dynamic-attributes>
    
</tag>

mytaglib.tld Dateien werden entweder im WEB-INF, META-INF, oder in der Jar Datei einer Taglibrary. In diesen Dateien können auch Listeners registriert werden, wie im web.xml. Validatoren können ebenfalls registriert werden.

body-content element

Mögliche Werte:

  • scriptless: Enthält EL und andere Tags.
  • tagdependent: Der Inhalt wird vom Tag interpretiert.
  • empty: Kein Body.

dynamische attribute in taghandlers

Will ein TagHandler dynamische Attribute unterstützen, muss es das DynamicAttributes Interface implementieren.

Section 11: Java EE Patterns

Given a scenario description with a list of issues, select a pattern that would solve the issues. The list of patterns you must know are: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object. Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Intercepting Filter, Model-View-Controller, Front Controller, Service Locator, Business Delegate, and Transfer Object.

Intercepting Filter

Front Controller

  • Der Front Controller ist ein Servler oder eine JSP, welche dann an den ApplicationController delegiert.
  • Der ApplicationController führt Actions aus und dispatched zu Views.

Resourcen