sun certification scjp

Upload: ponsethu

Post on 30-May-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Sun Certification SCJP

    1/60

    Please send your comments to: [email protected]

    1

    Sun Certified Web Component Developer Study Guide - v2

    Sun Certified Web Component Developer Study Guide .................................................. 1

    Authors Note...................................................................................................................2

    Servlets ........................................................................................................................... 3The Servlet Model................................................................................................... 3The Structure and Deployment of Modern Servlet Web Applications .................... 10

    The Servlet Container Model................................................................................. 13Designing and Developing Servlets to Handle Server-side Expectations................ 17

    Designing and Developing Servlets Using Session Management ........................... 21Designing and Developing Secure Web Applications ............................................ 24

    Designing and Developing Thread-safe Servlets .................................................... 32JSPs .............................................................................................................................. 35

    The JSP Model ...................................................................................................... 35Designing and Developing Reusable Web Components......................................... 41

    Designing and Developing JSPs Using JavaBeans ................................................. 42Designing and Developing JSPs Using Custom Tags............................................. 45Designing and Developing a Custom Tag Library.................................................. 47

    J2EE Design Patterns ................................................................................................ 52Value Objects................................................................................................................53

    Model View and Control (MVC)...................................................................................54Data Access Object (DAO) ........................................................................................... 57

    Business Delegate ......................................................................................................... 59

  • 8/14/2019 Sun Certification SCJP

    2/60

    Please send your comments to: [email protected]

    2

    Authors Note

    The following document was put together as a guide to study for the Sun

    Certified Web Component Developer Exam. This document is actually aformatted version of the study notes that were used to study for the certificationexam.

    Most of the following document comes straight from the Servlet 2.3 and JSP 1.2specifications, literally cut and paste!

    The intent of this document is to share resources with other Java developers andshould be freely distributed. If this document is used, please feel free to drop theauthor a message with your comments.

    **Please Note***

    With regards to Objective Section 8.5about the order of events of a Jsp, the firstversion of this guide was incorrect. It has been updated thanks to feedbackreceived from www.javaranch.com.

    I appreciate the feedback that I have received up to this point. Remember thisdocument was intended to filter the important (potentially tested) parts from theJsp and Servlet specification and not as an all-encompassing guide on how topass every possible question on the exam.

    Thanks

    Please forward comments to:

    Ken ZrobokSCJP2, SCJD2, [email protected]

    Java Developer / Trainerhttp://www.SetFocus.com

  • 8/14/2019 Sun Certification SCJP

    3/60

    Please send your comments to: [email protected]

    3

    Servlets

    The Servlet Model

    1.1 For each of the HTTP methods, GET, POST and PUT, identify thecorresponding method in the HttpServlet class.

    HttpServlet is an abstract class that requires sub classing to create an HTTPservlet suitable for a Web site. HttpServlet must override at least one method,usually one of the following:

    doGet, if the servlet supports HTTP GET requestsdoPost for the HTTP POST requestsdoPut for the HTTP put requests

    There is no reason to override the classs service method since service handlesHTTP requests by dispatching them to handler methods for each type of HTTPrequest.

    1.2 For each of the HTTP methods, GET, POST and HEAD identify the triggers thatmight cause a browser to use the method and identify benefits or functionality ofthe method.

    HTTP POST method allows the client to send data of unlimited length to the Webserver a single time and is useful when posting information such as credit cardnumbers. The information is usually posted from a HTML form.

    HTTP GET method retrieves whatever information (in the form of an entity) isidentified by the Request-URI. If the Request-URI refers to a data-producingprocess, it is the produced data which shall be returned as the entity in theresponse and not the source text of the process, unless that text happens to bethe output of the process.

    HTTP HEAD method is a GET request that returns no body in the response, onthe request header fields. The client sends a HEAD request when it wants to seeonly the headers of a response, such as Content-Type or Content-Length. TheHTTP HEAD method counts the number of output bytes in the response to setthe Content-Length header accurately. This method can be used for obtaining

    meta-information about the entity implied by the request without transferring theentity-body itself. This method is often used for testing hypertext links for validity,accessibility, and recent modification.

    The servlet container must write the headers before committing the response,because in HTTP the headers must be sent before the response body.

  • 8/14/2019 Sun Certification SCJP

    4/60

    Please send your comments to: [email protected]

    4

    1.3 For each of the following operations, identify the interface and method namethat should be used:

    Retrieve HTML form parameters from the request

    Request parameters are strings sent by the client to a servlet container as part of

    a request.

    When the request is an HttpServletRequest, the attributes are populated from theURI query string and posted form data. The parameters are stored by the servletcontainer as a set of name-value pairs.

    Multiple parameter values can exist for any given parameter name. The followingmethods of the ServletRequest interface are available to access parameters:

    o getParametero getParameterNameso getParameterValues

    The getParameterValuesmethod returns an array of String objects containingall the parameter values associated with a parameter name. The value returnedfrom the getParametermethod must be the first value in the array of Stringobjects returned by getParameterValues.

    All form data from both the query string and the post body are aggregated intothe request parameter set. The order of the aggregation puts the query stringdata before post body data. For example, if a request is made with a query stringof a=hello and a post body of a=goodbye&a=world, the resulting parameter setwould be ordered a=(hello, goodbye, world).

    Retrieve a servlet initialization parameter

    The ServletConfiginterface has the getInitParameter(String) as well as thegetInitParameterNames() methods.

    public String getInitParameter(String)

    Returns a String containing the value of the named initializationparameter, or null if the parameter does not exist.

    public Enumeration getInitParameterNames()

    Returns the names of the servlets initialization parameters as anEnumeration of String objects.

  • 8/14/2019 Sun Certification SCJP

    5/60

    Please send your comments to: [email protected]

    5

    Retrieve HTTP request header information

    A servlet can access the headers of an HTTP request through the followingmethods of the HttpServletRequest interface:

    o getHeader

    o getHeaderso getHeaderNames

    The getHeadermethod returns a header given the name of the header. Therecan be multiple headers with the same name, e.g. Cache-Control headers, in anHTTP request.

    If there are multiple headers with the same name, the getHeader method returnsthe first head in the request. The getHeaders method allows access to all theheader values associated with a particular header name, returning anEnumeration of String objects.

    Headers may contain String representations of int or Date data. The followingconvenience methods of the HttpServletRequest interface provide access toheader data in a one of these formats:

    o getIntHeadero getDateHeader

    If the getIntHeader method cannot translate the header value to an int, aNumberFormatException is thrown. If the getDateHeader method cannottranslate the header to a Date object, an IllegalArgumentException is thrown.

    Set an HTTP response header

    A servlet can set headers of an HTTP response via the following methods of theHttpServletResponse interface:

    o setHeadero addHeader

    The setHeader method sets a header with a given name and value. A previousheader is replaced by the new header. Where a set of header values exist for thename, the values are cleared and replaced with the new value.

    The addHeader method adds a header value to the set with a given name. Ifthere are no headers already associated with the name, a new set is created.

    Headers may contain data that represents an int or a Date object. The followingconvenience methods of the HttpServletResponseinterface allow a servlet to seta header using the correct formatting for the appropriate data type:

    o setIntHeadero setDateHeader

  • 8/14/2019 Sun Certification SCJP

    6/60

    Please send your comments to: [email protected]

    6

    o addIntHeadero addDateHeader

    To be successfully transmitted back to the client, headers must be set before theresponse is committed. Headers set after the response is committed will beignored by the servlet container.

    Set the content type of the response

    The ServletResponseinterface has the method setContentType(String).

    public void setContentType(java.lang.String type)

    Sets the content type of the response being sent to the client. The contenttype may include the type of character encoding used,for example: text/html; charset=ISO-8859-4.

    Acquire a text stream for the response

    The ServletResponseinterface has the method getWriter(). To send characterdata, use the PrintWriter object returned by getWriter().

    public java.io.PrintWriter getWriter() throws java.io.IOException

    Returns a PrintWriter object that can send character text to the client.

    Calling flush() on the PrintWriter commits the response.

    Acquire a binary stream for the response

    The ServletResponseinterface has the method getOutputStream(). To sendbinary data in a MIME body response, use the ServletOutputStream returned bygetOutputStream().

    public ServletOutputStream getOutputStream() throws IOException

    Returns a ServletOutputStream suitable for writing binary data in theresponse. The servlet container does not encode the binary data.

    Calling flush() on the ServletOutputStream commits the response.

    Redirect an HTTP request to another URL

    The HttpServletResponseinterface has the method sendRedirect(String)method that sends a temporary redirect response to the client using the specifiedredirect location URL.

    public void sendRedirect(String location) throws IOException

  • 8/14/2019 Sun Certification SCJP

    7/60

    Please send your comments to: [email protected]

    7

    Sends a temporary redirect response to the client using the specifiedredirect location URL. This method can accept relative URLs; the servletcontainer must convert the relative URL to an absolute URL beforesending the response to the client. If the location is relative without aleading '/' the container interprets it as relative to the current request URI.

    If the location is relative with a leading '/' the container interprets it asrelative to the servlet container root.

    If the response has already been committed, this method throws anIllegalStateException. After using this method, the response should beconsidered to be committed and should not be written to.

    1.4 Identify the interface and method to access values and resources and to setobject attributes within the following three Web scopes:

    Request

    ServletRequest interface has the following methods:

    public java.lang.Object getAttribute(java.lang.String name)

    Returns the value of the named attribute as an Object, or null if noattribute of the given name exists.

    public java.util.Enumeration getAttributeNames()

    Returns an Enumeration containing the names of the attributes availableto this request.

    public ServletInputStream getInputStream() throws java.io.IOException

    Retrieves the body of the request as binary data using aServletInputStream.

    public void setAttribute(java.lang.String name, java.lang.Object o)

    Stores an attribute in this request. Attributes are reset between requests.This method is most often used in conjunction with RequestDispatcher.

    public void removeAttribute(java.lang.String name)

    Removes an attribute from this request. This method is not generallyneeded as attributes only persist as long as the request is being handled.

    Session

    The HttpSessioninterface has the following methods:

  • 8/14/2019 Sun Certification SCJP

    8/60

    Please send your comments to: [email protected]

    8

    public java.lang.Object getAttribute(java.lang.String name)

    Returns the object bound with the specified name in this session, or null ifno object is bound under the name

    public java.util.Enumeration getAttributeNames()

    Returns an Enumeration of String objects containing the names of all theobjects bound to this session.

    public void setAttribute(java.lang.String name, java.lang.Object value)

    Binds an object to this session, using the name specified.

    public void removeAttribute(java.lang.String name)

    Removes the object bound with the specified name from this session. Ifthe session does not have an object bound with the specified name, this

    method does nothing.

    Context

    The ServletContexthas the following methods:

    A servlet can bind an object attribute into the context by name. Any attributebound into a context is available to any other servlet that is part of the same webapplication. The following methods of ServletContextinterface allow access tothis functionality:

    o setAttribute

    o getAttributeo getAttributeNameso removeAttribute

    The ServletContext interface provides direct access to the hierarchy of staticcontent documents that are part of the web application, including HTML, GIF,and JPEG files, via the following methods of the ServletContextinterface:

    o getResourceo getResourceAsStream

    The getResource and getResourceAsStream methods take a String with aleading / as argument which gives the path of the resource relative to the root ofthe context. This hierarchy of documents may exist in the servers file system, ina web application archive file, on a remote server, or at some other location.These methods are not used to obtain dynamic content.

    For example, in a container supporting the JavaServer Pages specification 1, amethod call of the form getResource("/index.jsp") would return the JSP sourcecode and not the processed output.

  • 8/14/2019 Sun Certification SCJP

    9/60

    Please send your comments to: [email protected]

    9

    1.5 Given a life-cycle method: init, service or destroy, identify correct statementsabout its purpose or about how and when it is invoked.Servlet:

    This interface defines methods to initialize a servlet, to service requests, and toremove a servlet from the server. These are known as life-cycle methods and arecalled in the following sequence:

    The servlet is constructed, and then initialized with the init method. Any callsfrom clients to the service method are handled. The servlet is taken out ofservice, then destroyed with the destroy method, then garbage collected andfinalized.

    In addition to the life-cycle methods, this interface provides the getServletConfigmethod, which the servlet can use to get any startup information, and thegetServletInfo method, which allows the servlet to return basic information

    about itself, such as author, version, and copyright.

    1.6 Use a RequestDispatcher to include or forward to a web resource.

    ServletContext

    Servlets (and JSP pages also) may be given names via server administration orvia a web application deployment descriptor. A servlet instance can determine itsname using ServletConfig.getServletName().

    Returns a RequestDispatcher object that acts as a wrapper for the resource

    located at the given path. A RequestDispatcher object can be used to forward arequest to the resource or to include the resource in a response. The resourcecan be dynamic or static.

    The pathname must begin with a "/" and is interpreted as relative to the currentcontext root. Use getContext to obtain a RequestDispatcher for resources inforeign contexts.

    This method returns null if the ServletContext cannot return aRequestDispatcher.

    ServletRequest

    The pathname specified may be relative, although it cannot extend outside thecurrent servlet context. If the path begins with a "/" it is interpreted as relative tothe current context root. This method returns null if the servlet container cannotreturn a RequestDispatcher.

  • 8/14/2019 Sun Certification SCJP

    10/60

    Please send your comments to: [email protected]

    10

    The difference between this method andServletContext.getRequestDispatcher(java.lang.String) is that this method cantake a relative path.

    Forward

    Forwards a request from a servlet to another resource (servlet, JSP file, or HTMLfile) on the server. This method allows one servlet to do preliminary processing ofa request and another resource to generate the response.

    For a RequestDispatcher obtained via getRequestDispatcher(), theServletRequest object has its path elements and parameters adjusted to matchthe path of the target resource.

    forward should be called before the response has been committed to the client(before response body output has been flushed). If the response already hasbeen committed, this method throws an IllegalStateException. Uncommittedoutput in the response buffer is automatically cleared before the forward.

    Include

    Includes the content of a resource (servlet, JSP page, HTML file) in theresponse. In essence, this method enables programmatic server-side includes.

    The ServletResponseobject has its path elements and parameters remainunchanged from the caller's. The included servlet cannot change the responsestatus code or set headers; any attempt to make a change is ignored.

    The Structure and Deployment of Modern Servlet Web Applications

    2.1 Identify the structure of the Web Application and Web Archive file, the name ofthe WebApp deployment descriptor and the name of the directories where youplace the following:

    The WebApp deployment descriptor.The WebApp class files.Any auxiliary JAR files

    A web application exists as a structured hierarchy of directories. The root of thishierarchy serves as a document root files that are part of the application. Forexample, for a web application with the context path /catalog in a web container,the index.html file the base of the web application hierarchy can be served tosatisfy a request f rom /catalog/index.html.

    Since the context path of an application determines the URL namespace of thecontents of the web application, web containers must reject web applicationsdefining a context path that is the same, determined case sensitively, as thecontext path of a web application already deployed that exposes a potentiallyconflicting URL namespace.

  • 8/14/2019 Sun Certification SCJP

    11/60

    Please send your comments to: [email protected]

    11

    A special directory exists within the application hierarchy named WEB-INF.This directory contains all things related to the application that arent in thedocument root of the application. The WEB-INF node is not part of the publicdocument tree of the application. No file contained in the WEB-INF directory maybe served directly to a client by the container. However, the contents of the WEB-

    INF directory are visible to servlet code using the getResource() andgetResourceAsStream() method calls on the ServletContext.

    Any application specific configuration information that the developer needsaccess to from servlet code yet does not wish to be exposed to the web clientmay be placed under this directory.

    Since requests are matched to resource mappings case-sensitively, clientrequests for /WEB-INF/ foo, /WEb-iNf/foo, for example, should not result incontents of the web application located under /WEB-INF being returned, nor anyform of directory listing thereof.

    The contents of the WEB-INF directory are:

    The /WEB-INF/web.xml

    Deployment descriptor

    The /WEB-INF/classes/*

    Directory for servlet and utility classes. The classes in this directory are availableto the application class loader.

    The /WEB-INF/lib/*.jar

    Area for Java ARchive files. These files contain servlets, beans, and other utilityclasses useful to the web application. The web application class loader can loadclass from any of these archive f iles. The web application classloader loadsclasses from the WEB-INF/classes directory first, and then from library JARs inthe WEB-INF/lib directory. Library JARs are loaded from in the same order asthey appear in the WAR archive entries.

    2.2 Match the name with a description of purpose or functionality, for each of thefollowing deployment descriptor elements:

    Servlet instance

    The servlet element contains the declarative data of a servlet. If a jsp-file isspecified and the load-on-startup element is present, then the JSP should beprecompiled and loaded.

  • 8/14/2019 Sun Certification SCJP

    12/60

    Please send your comments to: [email protected]

    12

    Servlet name

    The servlet-name element contains the canonical name of the servlet. Eachservlet name is unique within the web application.

    Servlet class

    The servlet-class element contains the fully qualified class name of the servlet.

    Initialization parameters

    The init-param element contains a name/value pair as an initialization param ofthe servlet

    URL to named servlet mapping

    The servlet-mapping element defines a mapping between a servlet and a urlpattern

    The servlet-name element contains the canonical name of the servlet. Eachservlet name is unique within the web application.

    The url-pattern element contains the url pattern of the mapping. Must follow therules specified in Section 11.2 of the Servlet API Specification.

    Example

    catalogcom.mycorp.CatalogServlet

    catalogSpring

  • 8/14/2019 Sun Certification SCJP

    13/60

    Please send your comments to: [email protected]

    13

    catalog/catalog/*

    The Servlet Container Model

    3.1 Identify the uses for and the interfaces (or classes) and methods to achievethe following features:

    Servlet context init parameters

    ServletContext

    The following methods of the ServletContext interface allow the servlet access tocontext initialization parameters associated with a web application through its

    deployment descriptor:

    o getInitParametero getInitParameterNames

    Initialization parameters are used by an application developer to convey setupinformation. Typical examples are a webmasters e-mail address, or the name ofa system that holds critical data.

    Servlet context listener

    ServletContextListener

    Implementations of this interface receive notifications about changes to theservlet context of the web application they are part of. To receive notificationevents, the implementation class must be configured in the deploymentdescriptor for the web application.

    public void contextInitialized(ServletContextEvent sce)

    Notification that the web application is ready to process requests.

    public void contextDestroyed(ServletContextEvent sce)

    Notification that the servlet context is about to be shut down.

    Servlet context attribute listener

    ServletContextAttributeListener

  • 8/14/2019 Sun Certification SCJP

    14/60

    Please send your comments to: [email protected]

    14

    Implementations of this interface receive notifications of changes to the attributelist on the servlet context of a web application. To receive notification events, theimplementation class must be configured in the deployment descriptor for theweb application.

    public void attributeAdded(ServletContextAttributeEvent scab)

    Notification that a new attribute was added to the servlet context. Calledafter the attribute is added.

    public void attributeRemoved(ServletContextAttributeEvent scab)

    Notification that an existing attribute has been removed from the servletcontext. Called after the attribute is removed.

    public void attributeReplaced(ServletContextAttributeEvent scab)

    Notification that an attribute on the servlet context has been replaced.Called after the attribute is replaced.

    Session attribute listeners

    HttpSessionAttributeListener

    This listener interface can be implemented in order to get notifications of changesto the attribute lists of sessions within this web application.

    public void attributeAdded(HttpSessionBindingEvent se)

    Notification that an attribute has been added to a session. Called after theattribute is added.

    public void attributeRemoved(HttpSessionBindingEvent se)

    Notification that an attribute has been removed from a session. Calledafter the attribute is removed.

    public void attributeReplaced(HttpSessionBindingEvent se)

    Notification that an attribute has been replaced in a session. Called afterthe attribute is replaced.

  • 8/14/2019 Sun Certification SCJP

    15/60

    Please send your comments to: [email protected]

    15

    Other Listeners

    HttpSessionListener

    Implementations of this interface may are notified of changes to the list of active

    sessions in a web application. To receive notification events, the implementationclass must be configured in the deployment descriptor for the web application.

    public void sessionCreated(HttpSessionEvent se)

    Notification that a session was created.

    public void sessionDestroyed(HttpSessionEvent se)

    Notification that a session was invalidated.

    HttpSessionActivationListener

    Objects that are bound to a session may listen to container events notifying themthat sessions will be passivated and that session will be activated. A containerthat migrates session between VMs or persists sessions is required to notify allattributes bound to sessions implementing HttpSessionActivationListener.

    HttpSessionBindingListener

    Causes an object to be notified when it is bound to or unbound from a session.The object is notified by an HttpSessionBindingEvent object. This may be as aresult of a servlet programmer explicitly unbinding an attribute from a session,due to a session being invalidated, or die to a session timing out.

    3.2 Identify the WebApp deployment descriptor element name that declares thefollowing features:

    Servlet context init parameters

    The context-param element contains the declaration of a web applications

    servlet context initialization parameters.

    The param-name element contains the name of a parameter. Each parametername must be unique in the web application.

    The param-value element contains the value of a parameter.

  • 8/14/2019 Sun Certification SCJP

    16/60

    Please send your comments to: [email protected]

    16

    Example

    [email protected]

    Servlet context listener & Session attribute listeners & Servlet context attributelisteners

    The listener element indicates the deployment properties for a web applicationlistener bean.

    The listener-class element declares a class in the application must be registeredas a web application listener bean. The value is the fully qualified class name ofthe listener class.

    Example

    The following example is the deployment grammar for registering two servlet

    context lifecycle listeners and an HttpSession listener.

    Suppose that com.acme.MyConnectionManager andcom.acme.MyLoggingModule both implement

    javax.servlet.ServletContextListener, and that com.acme.MyLoggingModuleadditionally implements javax.servlet.HttpSessionListener. Also the developerwants com.acme.MyConnectionManager to be notified of servlet context lifecycleevents before com.acme.MyLoggingModule. Here is the deployment descriptorfor this application:

    MyListeningApplication

    com.acme.MyConnectionManager

    com.acme.MyLoggingModule

  • 8/14/2019 Sun Certification SCJP

    17/60

    Please send your comments to: [email protected]

    17

    RegistrationServlet

    3.3 Distinguish the behavior of the following in a distributable:o Servlet context init parameterso Servlet context listenero Servlet context attribute listenerso Session attribute listeners

    See 3.2

    Designing and Developing Servlets to Handle Server-sideExpectations

    4.1 For each of the following cases, identify correctly constructed code forhandling business logic exceptions and match that code with the correctstatements about the codes behavior: Return an HTTP error using the sendErrorresponse method; Return and HTTP error using the setStatus method.

    Error Pages

    To allow developers to customize the appearance of content returned to a web

    client when a servlet generates an error, the deployment descriptor defines a listof error page descriptions. The syntax allows the configuration of resources to bereturned by the container either when a servlet sets a status code to indicate anerror on the response, or if the servlet generates a Java exception or error thatpropagates to the container.

    If a status code indicating an error is set on the response, the container consultsthe list of error page declarations for the web application that use the status-codesyntax and attempts a match. If there is a match, the container serves back theresource as indicated by the location entry.

    A Servlet may throw the following exceptions during processing of a request:

    o runtime exceptions or errorso ServletExceptions or subclasses thereofo IOExceptions or subclasses thereof

    The web application may have declared error pages using the exception-typesyntax. In this case the container matches the exception type by comparing theexception thrown with the list of error-page definitions that use the exception-type

  • 8/14/2019 Sun Certification SCJP

    18/60

    Please send your comments to: [email protected]

    18

    syntax. A match results in the container serving back the resource indicated inthe location entry. The closest match in the class hierarchy wins.

    If no error-page declaration containing an exception-type fits using the class-hierarchy match, and the exception thrown is a ServletException or subclassthereof, the container extracts the wrapped exception, as defined by the

    ServletException.getRootCause() method. It makes a second pass over theerror page declarations, again attempting the match against the error pagedeclarations, but using the wrapped exception instead. Error-page declarationsusing the exception-type syntax in the deployment descriptor must be unique upto the classname of the exception-type. Similarly, error-page declarations usingthe status-code syntax must be unique in the deployment descriptor up to thestatus code.

    The error page mechanism described does not intervene when errors occur inservlets invoked using the RequestDispatcher. In this way, a servlet using theRequestDispatcher to call another servlets has the opportunity to handle errorsgenerated in the servlet it calls.

    If a Servlet generates an error that is unhandled by the error page mechanism asdescribed above, the container must ensure the status code of the response isset to status code 500.

    The following convenience methods exist in the HttpServletResponse interface:

    o sendRedirecto sendError

    The sendRedirect method will set the appropriate headers and content body toredirect the client to a different URL. It is legal to call this method with a relative

    URL path, however the underlying container must translate the relative path to afully qualified URL for transmission back to the client.If a partial URL is given and, for whatever reason, cannot be converted into avalid URL, then this method must throw an IllegalArgumentException.

    The sendError method will set the appropriate headers and content body for anerror message to return to the client. An optional String argument can beprovided to the sendError method which can be used in the content body of theerror.

    These methods will have the side effect of committing the response, if it has notalready been committed, and terminating it. No further output to the client should

    be made by the servlet after these methods are called. If data is written to theresponse after these methods are called, the data is ignored.

    If data has been written to the response buffer, but not returned to the client (i.e.the response is not committed), the data in the response buffer must be clearedand replaced with the data set by these methods. If the response is committed,these methods must throw an IllegalStateException.

  • 8/14/2019 Sun Certification SCJP

    19/60

    Please send your comments to: [email protected]

    19

    HttpServletResponse

    public void sendError(int sc) throws java.io.IOException

    Sends an error response to the client using the specified status code andclearing the buffer.

    If the response has already been committed, this method throws anIllegalStateException. After using this method, the response should beconsidered to be committed and should not be written to.

    public void sendError(int sc, String msg) throws IOException

    Sends an error response to the client using the specified status clearingthe buffer. The server defaults to creating the response to look like anHTML-formatted server error page containing the specified message,setting the content type to "text/html", leaving cookies and other headers

    unmodified. If an error-page declaration has been made for the webapplication corresponding to the status code passed in, it will be servedback in preference to the suggested msg parameter.

    If the response has already been committed, this method throws anIllegalStateException. After using this method, the response should beconsidered to be committed and should not be written to.

    public void setStatus(int sc)

    Sets the status code for this response. This method is used to set the

    return status code when there is no error (for example, for the statuscodes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, andthe caller wishes to invoke an defined in the web application, thesendError method should be used instead.

    4.2 Given a set of business logic exceptions, identify the following: Theconfiguration that the deployment descriptor uses to handle each exception; Howto use the RequestDispatcher to forward the request to an error page; specify thehandling declaratively in the deployment descriptor.

    The error-page element contains a mapping between an error code or exception

    type to the path of a resource in the web application

    The error-code contains an HTTP error code, ex: 404

  • 8/14/2019 Sun Certification SCJP

    20/60

    Please send your comments to: [email protected]

    20

    The exception type contains a fully qualified class name of a Java exceptiontype.

    The location element contains the location of the resource in the web application

    relative to the root of the web application. The value of the location must have aleading /.

    Example 1

    404/404.html

    Example 2

    java.lang.NumberFormatException/MyException.html

    4.3 Identify the method used for the following: Write a message to the WebApplog; Write a message and an exception to the WebApp log.

    HttpServlet (inherited from GenericServlet)

    public void log(java.lang.String msg)

    Writes the specified message to a servlet log file, prepended by theservlet's name.

    public void log(java.lang.String message, java.lang.Throwable t)

  • 8/14/2019 Sun Certification SCJP

    21/60

    Please send your comments to: [email protected]

    21

    Writes an explanatory message and a stack trace for a given Throwableexception to the servlet log file, prepended by the servlet's name

    ServletContext

    public void log(java.lang.String msg)

    Writes the specified message to a servlet log file, usually an event log.

    The name and type of the servlet log file is specific to the servletcontainer.

    public void log(java.lang.String message, java.lang.Throwable throwable)

    Writes an explanatory message and a stack trace for a given Throwableexception to the servlet log file.

    The name and type of the servlet log file is specific to the servletcontainer, usually an event log.

    Designing and Developing Servlets Using Session Management

    5.1 Identify the interface and method for each of the following:

    Retrieve a session object across multiple requests to the same or differentservlets within the same WebApp.

    HttpSession

    Provides a way to identify a user across more than one page request or visit to aWeb site and to store information about that user.

    The servlet container uses this interface to create a session between an HTTPclient and an HTTP server. The session persists for a specified time period,across more than one connection or page request from the user. A sessionusually corresponds to one user, who may visit a site many times. The servercan maintain a session in many ways such as using cookies or rewriting URLs.

    Store objects into a session object.

    public void setAttribute(String name, Object value)

    Binds an object to this session, using the name specified. If an object ofthe same name is already bound to the session, the object is replaced.

  • 8/14/2019 Sun Certification SCJP

    22/60

    Please send your comments to: [email protected]

    22

    Retrieve objects from a session object.

    public Object getAttribute(String name)

    Returns the object bound with the specified name in this session, or null ifno object is bound under the name.

    Respond to the event when a particular object is added to a session.

    HttpSessionBindingListener

    Causes an object to be notified when it is bound to or unbound from a session.The object is notified by an HttpSessionBindingEvent object. This may be as aresult of a servlet programmer explicitly unbinding an attribute from a session,due to a session being invalidated, or die to a session timing out.

    After setAttribute(String) method executes and if the new object implementsHttpSessionBindingListener, the container callsHttpSessionBindingListener. valueBound. The container then notifies anyHttpSessionAttributeListeners in the web application.

    If an object was already bound to this session of this name that implementsHttpSessionBindingListener, its HttpSessionBindingListener.valueUnboundmethod is called.

    If the value passed in is null, this has the same effect as callingremoveAttribute().

    Respond to the event when a session is created and destroyed.

    HttpSessionListener

    Implementations of this interface may are notified of changes to the list of activesessions in a web application. To receive notification events, the implementationclass must be configured in the deployment descriptor for the web application.

    public void sessionCreated(HttpSessionEvent se)

    Notification that a session was created.

    public void sessionDestroyed(HttpSessionEvent se)

    Notification that a session was invalidated.

    Expunge a session object.

  • 8/14/2019 Sun Certification SCJP

    23/60

    Please send your comments to: [email protected]

    23

    Invalidate

    public void invalidate()

    Invalidates this session then unbinds any objects bound to it.

    5.2 Given a scenario, state whether a session object will be invalidated.

    In the HTTP protocol, there is no explicit termination signal when a client is nolonger active. This means that the only mechanism that can be used to indicatewhen a client is no longer active is a timeout period. The default timeout periodfor sessions is defined by the servlet container and can be obtained via thegetMaxInactiveInterval method of the HttpSessioninterface.

    This timeout can be changed by the Developer using the setMaxInactiveIntervalmethod of the HttpSessioninterface. The timeout periods used by these methods

    are defined in seconds. By definition, if the timeout period for a session is set to -1, the session will never expire.

    The session-config element defines the session parameters for this webapplication.

    The session-timeout element defines the default session timeout interval for allsessions created in this web application. The specified timeout must beexpressed in a whole number of minutes. If the timeout is 0 or less, the containerensures the default behavior of sessions is never to time out.

    Example

    .

    30..

    5.3 Given that URL-rewriting must be used for session management, identify thedesign requirement on session-related HTML pages.

    Session tracking through HTTP cookies is the most used session trackingmechanism and is required to be supported by all servlet containers.

  • 8/14/2019 Sun Certification SCJP

    24/60

    Please send your comments to: [email protected]

    24

    The container sends a cookie to the client. The client will then return the cookieon each subsequent request to the server, unambiguously associating therequest with a session. The name of the session tracking cookie must beJSESSIONID.

    URL rewriting is the lowest common denominator of session tracking. When a

    client will not accept a cookie, URL rewriting may be used by the server as thebasis for session tracking.

    URL rewriting involves adding data, a session id, to the URL path that isinterpreted by the container to associate the request with a session. The sessionid must be encoded as a path parameter in the URL string. The name of theparameter must be jsessionid.

    Here is an example of a URL containing encoded path information:

    http://www.myserver.com/catalog/index.html;jsessioid=1234

    Designing and Developing Secure Web Applications

    6.1 Identify correct descriptions or statements about the security issues:

    o authenticationo authorizationo data integrity

    o auditingo malicious codeo Web site attacks

    A web application contains resources that can be accessed by many users.These resources often traverse unprotected, open networks such as the Internet.In such an environment, a substantial number of web applications will havesecurity requirements.

    Although the quality assurances and implementation details may vary, servletcontainers have mechanisms and infrastructure for meeting these requirementsthat share some of the following characteristics:

    Authentication: The means by which communicating entities prove to one an-other that they are acting on behalf of specific identities that are authorized foraccess.

    Access control for resources: The means by which interactions with resourcesare limited to collections of users or programs for the purpose of enforcingintegrity, confidentiality, or availability constraints.

  • 8/14/2019 Sun Certification SCJP

    25/60

    Please send your comments to: [email protected]

    25

    Data Integrity: The means used to prove that information has not been modifiedby a third party while in transit.

    Confidentiality or Data Privacy: The means used to ensure that information ismade available only to users who are authorized to access it.

    6.2 Identify the deployment descriptor element names, and their structure, thatdeclare the following:

    o a security constrainto a Web resourceo the login configurationo a security role

    Security constraints are a declarative way of annotating the intended protectionof web content.

    A constraint consists of the following elements:

    o web resource collectiono authorization constrainto user data constraint

    A web resource collectionis a set of URL patterns and HTTP methods that

    describe a set of resources to be protected. All requests that contain a requestpath that matches a URL pattern described in the web resource collection issubject to the constraint. The container matches URL patterns defined in securityconstraints using the same algorithm described in this specification for matchingclient requests to servlets and static resources.

    An authorization constraintis a set of security roles to which users mustbelong for access to resources described by the web resource collection. If theuser is not part of an allowed role, the user must be denied access to theresource requiring it. If the authorization constraint defines no roles, no user isallowed access to the portion of the web application defined by the securityconstraint.

    A user data constraintdescribes requirements for the transport layer of theclient server: The requirement may be for content integrity (preventing datatampering in the communication process) or for confidentiality (preventingreading while in transit). The container must at least use SSL to respond torequests to resources marked integral or confidential. If the original request wasover HTTP, the container must redirect the client to the HTTPS port.

  • 8/14/2019 Sun Certification SCJP

    26/60

    Please send your comments to: [email protected]

    26

    Where there are multiple security constraints specified, the container matchesauthentication methods and authorizations to security constraints on a firstmatch wins basis.

    A security roleis a logical grouping of users defined by the ApplicationDeveloper or Assembler. When the application is deployed, roles are mapped by

    a Deployer to principals or groups in the runtime environment.

    A servlet container enforces declarative or programmatic security for the principalassociated with an incoming request based on the security attributes of theprincipal. This may happen in either of the following ways:

    A deployer has mapped a security role to a user group in the operationalenvironment.

    The user group to which the calling principal belongs is retrieved from its securityattributes. The principal is in the security role only if the principals user groupmatches the user group to which the security role has been mapped by the

    deployer.

    A deployer has mapped a security role to a principal name in a security policydomain. In this case, the principal name of the calling principal is retrieved fromits security attributes. The principal is in the security role only if the principalname is the same as a principal name to which the security role was mapped.

    The security-constraint element is used to associate security constraints with oneor more web resource collections.

    auth-constraint?, user-data-constraint?)>

    The web-resource-collection element is used to identify a subset of the resourcesand HTTP methods on those resources within a web application to which asecurity constraint applies. If no HTTP methods are specified, then the securityconstraint applies to all HTTP methods.

    The web-resource-name contains the name of this web resource collection

    The http-method contains an HTTP method (GET | POST |...)

    The user-data-constraint element is used to indicate how data communicatedbetween the client and container should be protected

  • 8/14/2019 Sun Certification SCJP

    27/60

    Please send your comments to: [email protected]

    27

    The transport-guarantee element specifies that the communication betweenclient and server should be NONE, INTEGRAL, or CONFIDENTIAL.

    NONE means that the application does not require any transport guarantees.

    A value of INTEGRAL means that the application requires that the data sentbetween the client and server be sent in such a way that it cant be changed intransit.

    CONFIDENTIAL means that the application requires that the data be transmittedin a fashion that prevents other entities from observing the contents of thetransmission.

    In most cases, the presence of the INTEGRAL or CONFIDENTIAL flag willindicate that the use of SSL is required.

    The auth-constraint element indicates the user roles that should be permittedaccess to this resource collection. The role-name used here must eithercorrespond to the role-name of one of the security-role elements defined for thisweb application, or be the specially reserved role-name "*" that is a compactsyntax for indicating all roles in the web application. If both "*" and rolenamesappear, the container interprets this as all roles.

    If no roles are defined, no user is allowed access to the portion of the webapplication described by the containing security-constraint.

    The container matches role names case sensitively when determining access.

    The role-name element contains the name of a security role.

    The login-config element is used to configure the authentication method thatshould be used, the realm name that should be used for this application, and theattributes that are needed by the form login mechanism.

    The realm name element specifies the realm name to use in HTTP Basicauthorization

  • 8/14/2019 Sun Certification SCJP

    28/60

    Please send your comments to: [email protected]

    28

    The security-role element contains the declaration of a security role which isused in the security-constraints placed on the web application.

    The security-role-ref element defines a mapping between the name of role called

    from a Servlet using isUserInRole(String name)and the name of a security roledefined for the web application.

    For example, to map the security role reference "FOO" to the security role withrole-name "manager" the syntax would be:

    FOOmanager

    In this case if the servlet called by a user belonging to the "manager" security

    role made the API call isUserInRole("FOO") the result would be true.

    Since the role-name "*" has a special meaning for authorization constraints, itsvalue is not permitted here.

    The role-link element is used to link a security role reference to a defined securityrole. The role-link element must contain the name of one of the security rolesdefined in the security-role elements.

    Example

    A Secure Application

    manager

    catalogcom.mycorp.CatalogServlet

    catalogSpring

    MGRmanager

  • 8/14/2019 Sun Certification SCJP

    29/60

    Please send your comments to: [email protected]

    29

    catalog/catalog/*

    SalesInfo/salesinfo/*GETPOST

    manager

    CONFIDENTIAL

    6.3 Given an authentication type: BASIC, DIGEST, FORM and CLIENT-CERT,identify the correct definition of its mechanism.

    A web client can authenticate a user to a web server using one of the followingmechanisms:

    o HTTP Basic Authentication

    o HTTP Digest Authenticationo HTTPS Client Authenticationo Form Based Authentication

    HTTP Basic Authentication

    HTTP Basic Authentication, which is based on a username and password, is theauthentication mechanism defined in the HTTP/1.0 specification. A web serverrequests a web client to authenticate the user.

    As part of the request, the web server passes the realm(a string) in which the

    user is to be authenticated. The realm string of Basic Authentication does nothave to reflect any particular security policy domain (confusingly also referred toas a realm). The web client obtains the username and the password from theuser and transmits them to the web server. The web server then authenticatesthe user in the specified realm.

    Basic Authentication is not a secure authentication protocol. User passwords aresent in simple base64 encoding, and the target server is not authenticated.

  • 8/14/2019 Sun Certification SCJP

    30/60

    Please send your comments to: [email protected]

    30

    HTTP Digest Authentication

    Like HTTP Basic Authentication, HTTP Digest Authentication authenticates auser based on a username and a password. However the authentication isperformed by transmitting the password in an encrypted form which is much

    more secure than the simple base64 encoding used by Basic Authentication, e.g.HTTPS Client Authentication.

    As Digest Authentication is not currently in wide-spread use, servlet containersare encouraged but not required to support it.

    HTTPS Client Authentication

    End user authentication using HTTPS (HTTP over SSL) is a strongauthentication mechanism. This mechanism requires the user to possess aPublic Key Certificate (PKC). Currently, PKCs are useful in e-commerce

    applications and also for a single-signon from within the browser. Servletcontainers that are not J2EE compliant are not required to support the HTTPSprotocol.

    Form Based Authentication

    The look and feel of the login screen cannot be varied using the web browsersbuilt-in authentication mechanisms. This specification introduces a required formbased authentication mechanism which allows a Developer to control the lookand feel of the login screens.

    The web application deployment descriptor contains entries for a login form anderror page. The login form must contain fields for entering a username and apassword. These fields must be named j_username and j_password,respectively.

    When a user attempts to access a protected web resource, the container checksthe users authentication. If the user is authenticated and possesses authority toaccess the resource, the requested web resource is activated and a reference toit is returned. If the user is not authenticated, all of the following steps occur:

    The login form associated with the security constraint is sent to the client and theURL path triggering the authentication is stored by the container.

    The user is asked to fill out the form, including the username and passwordfields.

    The client posts the form back to the server.

    The container attempts to authenticate the user using the information from theform.

  • 8/14/2019 Sun Certification SCJP

    31/60

    Please send your comments to: [email protected]

    31

    If authentication fails, the error page is returned using either a forward or a re-direct, and the status code of the response is set to 401.

    If authentication succeeds, the authenticated users principal is checked to see ifit is in an authorized role for accessing the resource.

    If the user is authorized, client is redirected to the resource using the stored URLpath. The error page sent to a user that is not authenticated contains informationabout the failure.

    Form Based Authentication has the same lack of security as Basic Authenticationsince the user password is transmitted as plain text and the target server is notauthenticated.

    Form based login and URL based session tracking can be problematic toimplement. Form based login should be used only when sessions are beingmaintained by cookies or by SSL session information.

    In order for the authentication to proceed appropriately, the action of the loginform must always be j_security_check. This restriction is made so that the loginform will work no matter which resource it is for, and to avoid requiring the serverto specify the action field of the outbound form.

    Here is an example showing how the form should be coded into the HTML page:

    If the form based login is invoked because of an HTTP request, the originalrequest parameters must be preserved by the container for use if, on successfulauthentication, it redirects the call to the requested resource.

    The form-login-config element specifies the login and error pages that should beused in form based login. If form based authentication is not used, theseelements are ignored.

    The form-login-page element defines the location in the web app where the pagethat can be used for login can be found. The path begins with a leading / and isinterpreted relative to the root of the WAR.

    The form-error-page element defines the location in the web app where the errorpage that is displayed when login is not successful can be found. The pathbegins with a leading / and is interpreted relative to the root of the WAR.

  • 8/14/2019 Sun Certification SCJP

    32/60

    Please send your comments to: [email protected]

    32

    The auth-method element is used to configure the authentication mechanism forthe web application. As a prerequisite to gaining access to any web resourceswhich are protected by an authorization constraint, a user must have

    authenticated using the configured mechanism.

    Legal values for this element are "BASIC", "DIGEST", "FORM", or "CLIENT-CERT".

    Designing and Developing Thread-safe Servlets

    7.1 Identify which attribute scopes are thread-safe:

    o local variableso instance variableso class variableso request attributeso session attributeso context attributes

    Number of Instances

    For a servlet not implementing SingleThreadModeland not hosted in adistributed environment (the default), the servlet container must use only oneinstance per servlet declaration.

    For a servlet implementing the SingleThreadModelinterface, the servletcontainer may instantiate multiple instances to handle a heavy request load andserialize requests to a particular instance.

    In the case where a servlet was deployed as part of an application marked in thedeployment descriptor as distributable, a container may have only one instanceper servlet declaration per VM. If the servlet in a distributable applicationimplements the SingleThreadModel interface, the container may instantiatemultiple instances of that servlet in each VM of the container.

    Note about SingleThreadModel

    The use of the SingleThreadModel interface guarantees that only one thread at atime will execute in a given servlet instances service method. It is important tonote that this guarantee only applies to each servlet instance, since the containermay choose to pool such objects.

  • 8/14/2019 Sun Certification SCJP

    33/60

    Please send your comments to: [email protected]

    33

    Objects that are accessible to more than one servlet instance at a time, such asinstances of HttpSession, may be available at any particular time to multipleservlets, including those that implement SingleThreadModel.

    Multithreading Issues

    A servlet container may send concurrent requests through the service method ofthe servlet. To handle the requests the developer of the servlet must makeadequate provisions for concurrent processing with multiple threads in theservice method.

    An alternative for the developer is to implement the SingleThreadModelinterfacewhich requires the container to guarantee that there is only one request thread ata time in the service method. A servlet container may satisfy this requirement byserializing requests on a servlet, or by maintaining a pool of servlet instances.

    If the servlet is part of a web application that has been marked as distributable,the container may maintain a pool of servlet instances in each VM that the

    application is distributed across.

    For servlets not implementing the SingleThreadModelinterface, if the servicemethod (or methods such as doGet or doPost which are dispatched to theservice method of the HttpServlet abstract class) has been defined with thesynchronized keyword, the servlet container cannot use the instance poolapproach, but must serialize requests through it.

    It is strongly recommended that developers not synchronizethe servicemethod (or methods despatched to it) in these circumstances because ofdetrimental effects on performance.

    Thread Safety

    Implementations of the request and response objects are not guaranteed to bethread-safe. This means that they should only be used within the scope of therequest handling thread.

    References to the request and response objects must not be given to objectsexecuting in other threads as the resulting behavior may be nondeterministic.

    Session Semantics and Threading Issues

    Multiple servlets executing request threads may have active access to a singlesession object at the same time. The Developer has the responsibility forsynchronizing access to session resources as appropriate.

    Listener Instances and Threading

    The container is required to complete instantiation of the listener classes in aweb application prior to the start of execution of the first request into the

  • 8/14/2019 Sun Certification SCJP

    34/60

    Please send your comments to: [email protected]

    34

    application. The container must reference each listener instance until the lastrequest is serviced for the web application.

    Attribute changes to ServletContextand HttpSessionobjects may occurconcurrently.

    The container is not required to synchronize the resulting notifications to attributelistener classes. Listener classes that maintain state are responsible for theintegrity of the data and should handle this case explicitly.

    7.2 Identify correct statements about differences between multi-threaded andsingle-threaded servlet models.

    See 7.1

    7.3 Identify the interface used to declare that a servlet must use the single threadmodel.

    SingleThreadModel

    Ensures that servlets handle only one request at a time. This interface has nomethods.

    If a servlet implements this interface, you are guaranteedthat no two threads willexecute concurrently in the servlet's service method. The servlet container canmake this guarantee by synchronizing access to a single instance of the servlet,or by maintaining a pool of servlet instances and dispatching each new requestto a free servlet.

    This interface does not prevent synchronization problems that result fromservlets accessing shared resources such as static class variables or classesoutside the scope of the servlet.

  • 8/14/2019 Sun Certification SCJP

    35/60

    Please send your comments to: [email protected]

    35

    JSPs

    The JSP Model

    8.1 Write the opening and closing tags for the following JSP tag types:

    directive

    Directive elements have a syntax of the form Directives have this syntax: .

    declaration

    Declarations follow the syntax ;

    scriptlet

    Scriptlets follow the syntax ;

    expression

    Expressions follow the syntax.

    8.2 Given a type of JSP tag identify correct statements about its purpose or use.

    Directives provide global information that is conceptually valid independent ofany specific request received by the JSP page. They provide information for thetranslation phase. Directives are messages to the JSP container.

    o The pagedirective defines a number of page dependentproperties and communicates these to the JSP container.

    o The taglibdirective in a JSP page declares that the page uses atag library, uniquely identifies the tag library using a URI andassociates a tag prefix that will distinguish usage of the actions inthe library.

    o The includedirective is used to substitute text and/or code at JSPpage translation-time.

  • 8/14/2019 Sun Certification SCJP

    36/60

    Please send your comments to: [email protected]

    36

    Scripting elements provide gluearound template text and actions. There arethree types of scripting elements: declarations, scriptletsand expressions.

    Declarationsare used to declare variables and methods in the scripting language

    used in a JSP page. A declaration should be a complete declarative statement,or sequence thereof, according to the syntax of the scripting language specified.Declarations do not produce any output into the current out stream. Declarationsare initialized when the JSP page is initialized and are made available to otherdeclarations, scriptlets, and expressions.

    Scriptletscan contain any code fragments that are valid for the scriptinglanguage specified in the language directive. Whether the code fragment is legaldepends on the details of the scripting language. Scriptlets are executed atrequest-processing time. Whether or not they produce any output into the outstream depends on the code in the scriptlet.

    An expressionelement in a JSP page is a scripting language expression that isevaluated and the result is coerced to a String. The result is subsequentlyemitted into the current out JspWriter object.

    8.3 Given a JSP tag type identify the equivalent XML-based tags.

    Directive: page

    or

    Directive: include

    or

    Scripting Element: Declaration

    or

  • 8/14/2019 Sun Certification SCJP

    37/60

    Please send your comments to: [email protected]

    37

    int i=0;

    Scripting Element: Scriptlet

    or

    if (Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM) {Good Morning}else {Good Afternoon}

    Scritping Element: Expression

    or

    (new java.util.Date()).toLocaleString()

    8.4 Identify the page directive attributes and its values, that:

    imports a Java class into the JSP page

    declares that a JSP page exists within a session

  • 8/14/2019 Sun Certification SCJP

    38/60

    Please send your comments to: [email protected]

    38

    declares that a JSP page uses an error page

    declares that a JSP page is an error page

    8.5 Identify and put in sequence the following elements of the JSP life-cycle:o page translationo JSP compilationo load classo create instanceo call jspInito call _jspService

    o call _jspDestroy

    JSP Life Cycle Information

    JSP pages are textual components. They go through two phases: a translationphase, and a request phase. Translation is done once per page. The requestphase is done once per request.

    The JSP page is translated to create a servlet class, the JSP pageimplementation class that is instantiated at request time. The instantiated JSPpage object handles requests and creates responses.

    JSP pages may be translated prior to their use, providing the web application,with a servlet class that can serve as the textual representation of the JSP page.

    The translation may also be done by the JSP container at deployment time or on-demand as the requests reach an untranslated JSP page.

    In the execution phase the container manages one or more instances of thisclass in response to requests and other events.

    During the translation phasethe container locates or creates the JSP pageimplementation class that corresponds to a given JSP page. This process isdetermined by the semantics of the JSP page. The container interprets the

    standard directives and actions, and the custom actions referencing tag librariesused in the page. A tag library may optionally provide a validation method tovalidate that a JSP page is correctly using the library.

    A JSP container has flexibility in the details of the JSP page implementationclass that can be used to address quality-of-service, most notably performance-issues.

  • 8/14/2019 Sun Certification SCJP

    39/60

    Please send your comments to: [email protected]

    39

    During the execution phasethe JSP container delivers events to the JSP pageimplementation object. The container is responsible for instantiating request andresponse objects and invoking the appropriate JSP page implementation object.

    Upon completion of processing, the response object is received by the containerfor communication to the client.

    The translation of a JSP source page into its implementation class can occur atany time between initial deployment of the JSP page into the JSP container andthe receipt and processing of a client request for the target JSP page.

    When the first request is delivered to a JSP page, a jspInit()method, if present,will be called to prepare the page. Similarly, a JSP container may invoke a JSPs

    _jspDestroy() method to reclaim the resources used by the JSP page at anytime when a request is not being serviced. This is the same life-cycle as forservlets.

    A JSP page may be compiledinto its implementation class plus deployment

    information during development. (A JSP page can also be compiled atdeployment time.)

    Compilation of a JSP page in the context of a web application provides resolutionof relative URL specifications in include directives (and elsewhere), taglibreferences, and translation-time actions used in custom actions.

    A JSP page can also be compiled at deployment time.

    Order of Events

    The translation of a JSP source page into its implementation class can occur atany time between initial deployment of the JSP page into the JSP container andthe receipt and processing of a client request for the target JSP page.

    A JSP page can be compiled at development time or wait until deployment timeto compile. During the compilation the JSP page is converted to the pageimplementation class (in other words a Servlet).

    page translation?JSP compilation

    Once the page is requested the container loads the class and creates andinstance of that class.

    load class?create instance

    The first time the JSP page is requested the jspInit() method is called, and therequest is handled by the_jspService() method.

    ?call jspInit?call _jspService

  • 8/14/2019 Sun Certification SCJP

    40/60

    Please send your comments to: [email protected]

    40

    When the container is done with the page, the _jspDestroy() method is called.This is where any cleanup (database connection) may be handled.

    _jspDestroy

    8.6 Match correct descriptions about purpose, function, or use with any of the

    following implicit objects:

    request

    The request object represents a sub class of:javax.servlet.ServletRequeste.g: javax.servlet.HttpServletRequest

    The request object can be used like the HttpServletRequest parameter of theservice() method of a Servlet.

    response

    The response object represents a sub class of:javax.servlet.ServletResponsee.g: servlet.HttpServletResponse

    The response object can be used like the HttpServletResponse parameter of theservice() method of a Servlet.

    out

    The out object represents a JspWriter that will write to the JSPs output stream.

    session

    The session object represents a users session (HttpSession) created for therequesting client.

    configThe config object represents the servlet config (ServletConfig) that representsthe servlets configuration.

    application

    The application object represents the servlet context (ServletContext) obtainedfrom the servlet config.

    pageThe instance of this pages implementation class processing the currentrequest.

    pageContext

    The page context for this JSP page.

  • 8/14/2019 Sun Certification SCJP

    41/60

    Please send your comments to: [email protected]

    41

    exception

    The uncaught Throwable that resulted in the error page being invoked.

    8.7 Distinguish correct and incorrect scriptlet code for:

    a conditional statement

    Good Morning

    Good Afternoon

    an iteration statement

    HelloWorld Counter

    Designing and Developing Reusable Web Components

    9.1 Given a description of required functionality, identify the JSP directive orstandard tag in the correct format with the correct attributes required to specifythe inclusion of a Web Component into the JSP page.

    The directive inserts the text of thespecified resource into the .jsp file. The included file is subject to the accesscontrol available to the JSP container.

    Examples

    The following example requests the inclusion, at translation time, of a copy-rightfile. The file may have elements which will be processed too.

  • 8/14/2019 Sun Certification SCJP

    42/60

    Please send your comments to: [email protected]

    42

    Syntax

    A element provides for the inclusion of static and dynamic

    resources in the same context as the current page.

    Examples

    Syntax

    and

    {}*

    An include directive regards a resource like a JSP page as a static object; i.e. thebytes in the JSP page are included. An include action regards a resource like aJSP page as a dynamic object; i.e. the request is sent to that object and theresult of processing it is included.

    Designing and Developing JSPs Using JavaBeans

    10.1 For any of the following tag functions, match the correctly constructed tag,with attributes and values as appropriate, with the corresponding description ofthe tags functionality.

    Declare the use of a JavaBean within the page.

    A jsp:useBean action associates an instance of a Java programming languageobject defined within a given scope and available with a given id with a newlydeclared scripting variable of the same id.

    Examples

    In the following example, a Bean with name connection of typemyco.myapp.Connection is available after actions on this element, eitherbecause it was already created and found, or because it is newly created.

  • 8/14/2019 Sun Certification SCJP

    43/60

    Please send your comments to: [email protected]

    43

    Specify, for jsp:useBean or jsp:getProperty tags, the name of an attribute.

    Specify, for a jsp:useBean tag, the class of the attribute.Specify, for a jsp:useBean tag, the scope of the attribute.

    typeSpec ::=class=className ||class=className type=typeName ||type=typeName class=className ||beanName=beanName type=typeName ||type=typeName beanName=beanName ||type=typeName

    If the action has a body, it is of the form:

    body

    In this case, the body will be invoked if the Bean denoted by the action iscreated. Typically, the bodywill contain either scriptlets or jsp:setProperty tagsthat will be used to modify the newly created object, but the contents of the bodyare not restricted.

    The tag has the following attributes:

    id

    The name used to identify the object instance in the specified scopesnamespace, andalso the scripting variable name declared and initializedwith that object reference.

    The name specified is case sensitive and shall conform to the currentscripting language variable-naming conventions.

    scope

    The scope within which the reference is available. The default value ispage . The fully qualified name of the class that defines theimplementation of the object. The class name is case sensitive.

    If the class and beanName attributes are not specified the object must bepresent in the given scope.

    beanName

  • 8/14/2019 Sun Certification SCJP

    44/60

    Please send your comments to: [email protected]

    44

    The name of a Bean, as expected by the instantiate() method of the java.beans.Beans class.

    This attribute can accept a request-time attribute expression as a value.

    type

    If specified, it defines the type of the scripting variable defined. Thisallows the type of the scripting variable to be distinct from, but related to,the type of the implementation class specified.The type is required to be either the class itself, a superclass of the class,or an interface implemented by the class specified.

    The object referenced is required to be of this type, otherwise a

    java.lang.ClassCastException shall occur at request time when theassignment of the object referenced to the scripting variable is attempted.

    If unspecified, the value is the same as the value of the class attribute.

    Access or mutate a property from a declared JavaBean.Specify, for a jsp:getProperty tag, the property of the attribute.Specify, for a jsp:setProperty tag, the property of the attribute to mutate and thenew value.

    Examples

    The following two elements set a value from the request parameter values.

    The following element sets a property from a value

    Syntax

    prop_expr ::=property="*"|property=propertyName |property=propertyName param=="parameterName"|property=propertyName value==propertyValue propertyValue ::=string

    The value propertyValue can also be a request-time attribute value.

  • 8/14/2019 Sun Certification SCJP

    45/60

    Please send your comments to: [email protected]

    45

    Examples

    Syntax

    10.2 Given JSP attribute scopes: request, session, application, identify theequivalent servlet code.

    Bean Scope: Servlet Scope:

    Request HttpServletRequestSession HttpSessionApplication ServletContext

    10.3 Identify techniques that access a declared JavaBean.

    A jsp:useBean action associates an instance of a Java programming languageobject defined within a given scope and available with a given id with a newlydeclared scripting variable of the same id.

    The jsp:useBean action is quite flexible; its exact semantics depends on theattributes given. The basic semantic tries to find an existing object using id andscope. If the object is not found it will attempt to create the object using the otherattributes.

    It is also possible to use this action to give a local name to an object definedelsewhere, as in another JSP page or in a Servlet. This can be done by using thetype attribute and not providing class or beanName attributes.

    At least one of type and class must be present, and it is not valid to provide bothclass and beanName. If type and class are present; class must be assignable totype (in the Java platform sense). For it not to be assignable is a translation-timeerror.

    Designing and Developing JSPs Using Custom Tags

    Identify properly formatted taglib directive in a JSP page.

    The web.xml file can include a map between URIs and TLD resource paths. Themap is described using the taglib element of the Web Application Deploymentdescriptor in WEB-INF/web.xml, as described in the Servlet 2.3 spec and inhttp://java.sun.com/j2ee/dtds/web-app_2_3.dtd.

  • 8/14/2019 Sun Certification SCJP

    46/60

    Please send your comments to: [email protected]

    46

    A taglib element has two sub-elements: taglib-uri and taglib-location.

    A taglib is a sub-element of web-app:

    The taglib element provides information on a tag library that is used by a JSPpage within the Web Application.

    A taglib element has two sub-elements and one attribute:

    A taglib-uri element describes a URI identifying a tag library used in theweb application.

    It may be either an absolute URI specification, or a relative URI.

    A taglib-location contains the location (as a resource) of the Tag LibraryDescription File for the tag library.

    Where to find the Tag Library Descriptor file.

    Example

    The use of relative URI specifications enables very short names in the taglibdirective. For example:

    /myPRlibrary/WEB-INF/tlds/PRlibrary_1_4.tld

    11.2 Identify properly formatted taglib directive in a JSP page.

    11.3 Given a custom tag library identify properly formatted custom tag usage in aJSP page. Uses include:

    Assuming prefix x and custom tag sample

    an empty custom tag

  • 8/14/2019 Sun Certification SCJP

    47/60

    Please send your comments to: [email protected]

    47

    a custom tag with attributes

    a custom tag that surrounds other JSP code

    some JSP code as the body

    nested custom tags

    some condition

    Designing and Developing a Custom Tag Library

    12.1 Identify the tag library descriptor element names that declare the following:

    the name of the tagthe class of the tag handlerthe type of content that the tag acceptsany attributes of the tag

    The element syntax is as follows:

    Defines the tag handler class implementing thejavax.serlvet.jsp.tagext.Tag interface. This element is required.

    The fully qualified Java class name.

    Defines the subclass of javax.servlet.jsp.tagext.TagExtraInfo for this tag.This element is optional.

    The fully qualified Java class name.

    Provides a hint as to the content of the body of this action. Primarilyintended for use by page composition tools.

  • 8/14/2019 Sun Certification SCJP

    48/60

    Please send your comments to: [email protected]

    48

    There are currently three values specified:

    tagdependent

    The body of the action is passed verbatim to be interpreted by thetag handler itself, and is most likely in a different language, e.g.embedded SQL statements. The body of the action may beempty.

    JSPThe body of the action contains elements using the JSP syntax.The body of the action may be empty.

    empty

    The body must be empty. The default value is JSP.

    12.2 Identify the tag library descriptor element names that declare the following:

    the name of a tag attribute.whether a tag attribute is required.whether or not the attributes value can be dynamically specified.

    Defines the canonical name of a tag or attribute being defined

    Defines if the nesting attribute is required or optional.

    Values are: true | false | yes | noIf not present then the default is false, i.e. the attribute is optional.

    Defines if the nesting attribute can have scriptlet expressions as a value,

    i.e the value of the attribute may be dynamically calculated at requesttime, as opposed to a static value determined at translation time.

    Values are: true | false | yes | noIf not present then the default is false, i.e the attribute has a static value.

  • 8/14/2019 Sun Certification SCJP

    49/60

    Please send your comments to: [email protected]

    49

    Defines the Java type of the attributes value. For static values (thosedetermined at translation time) the type is always java.lang.String. If thertexprvalue element is true, that is the value of the nesting attribute maybe calculated from an expression scriptlet during request processing thenthe type defines the return type expected from any scriptlet expressionspecified as the value of this attribute.

    The fully qualified Java class name of result type

    An example is:java.lang.Object

    12.3 Given a custom tag, identify the necessary value for the bodycontent TLDelement for any of the following tag types:

    empty-tagcustom tag that surrounds other JSP code

    custom tag that surrounds content that is used only by the tag handler

    Provides a hint as to the content of the body of this action. Primarilyintended for use by page composition tools.

    There are currently three values specified:

    tagdependentThe body of the action is passed verbatim to be interpreted by thetag handler itself, and is most likely in a different language, e.g.

    embedded SQL statements. The body of the action may beempty.

    JSPThe body of the action contains elements using the JSP syntax.The body of the action may be empty.

    empty

    The body must be empty. The default value is JSP.

    12.4 Given a tag event method (doStartTag, doAfterBody and doEndTag), identify

    the correct description of the methods trigger.

    When a tag is first encountered the doStartTag() method is invoked.When the custom tag implements IterationTaginterface, when the body of thecustom tag has completed, the doAfterBody() method is invoked.When the custom tag reached the end tag the doEndTag() method is invoked.

    12.5 Identify valid return values for the following methods:

  • 8/14/2019 Sun Certification SCJP

    50/60

    Please send your comments to: [email protected]

    50

    doStartTag()

    Empty and Non-Empty Action

    If the action is an empty action, the doStartTag() method must returnSKIP_BODY.

    If the action is a non-empty action, the doStartTag() method may returnSKIP_BODY or EVAL_BODY_INCLUDE.

    If SKIP_BODY is returned the body is not evaluated.If EVAL_BODY_INCLUDE is returned, the body is evaluated and "passedthrough" to the current out.

    doAfterBody()

    If doAfterBody() returns EVAL_BODY_AGAIN, a new evaluation of the body will

    happen (followed by another invocation of doAfterBody()).

    If doAfterBody() returns SKIP_BODY no more body evaluations will occur, thevalue of out will be restored using the popBody method in pageContext, and thendoEndTag will be invoked.

    doEndTag()

    If this method returns EVAL_PAGE, the rest of the page continues to beevaluated.

    If this method returns SKIP_PAGE, the rest of the page is not evaluated and therequest is completed. If this request was forwarded or included from anotherpage (or Servlet), only the current page evaluation is completed.

    pageContext.getOut()

    Returns the current JspWriter stream being used for client response.

    12.6 Given a BODY or PAGE constant, identify a correct description of theconstants use in the following methods:

    doStartTag()doAfterBody()doEndTag()

    SKIP_BODY

    Skip body evaluation.Valid return value for doStartTag and doAfterBody.

  • 8/14/2019 Sun Certification SCJP

    51/60

    Please send your comments to: [email protected]

    51

    EVAL_BODY_INCLUDE

    Evaluate body into existing out stream.Valid return value for doStartTag.

    SKIP_PAGE

    Skip the rest of the page.Valid return value for doEndTag.

    EVAL_PAGE

    Continue evaluating the page.Valid return value for doEndTag().

    EVAL_BODY_AGAIN

    Request the reevaluation of some body.Returned from doAfterBody. For compatibility with JSP 1.1, the value iscarefully selected to be the same as the, now deprecated,BodyTag.EVAL_BODY_TAG,

    EVAL_BODY_BUFFERED

    Request the creation of new buffer, a BodyContent on which to evaluatethe body of this tag.Returned from doStartTag when it implements BodyTag.This is an illegal return value for doStartTag when the class does notimplement BodyTag.

    12.7 Identify the method is the custom tag handler that accesses:

    a given JSP implicit variable

    A PageContext instance provides access to all the namespaces associated witha JSP page, provides access to several page attributes, as well as a layer abovethe implementation details.

    The following methods provide convenient access to implicit objects:getOut(), getException(), getPage() getRequest(), getResponse(), getSession(),

    getServletConfig() and getServletContext().

    The following methods provide support for forwarding, inclusion and errorhandling: forward(), include(), and handlePageException().

    the JSP pages attributes.

    PageContext.findAttribute()

  • 8/14/2019 Sun Certification SCJP

    52/60

    Please send your comments to: [email protected]

    52

    public abstract java.lang.Object findAttribute(java.lang.String name)

    Searches for the named attribute in page, request, session (if valid), andapplication scope(s) in order and returns the value associated or null.

    PageContext.getAttributeNamesInScope()

    public abstract java.util.Enumeration getAttributeNamesInScope (int scope)

    Enumerate all the attributes in a given scope

    12.8 Identify methods that return