Disclaimers No claims are made about the accuracy of this document and no responsibility is taken for any errors. The exam objectives below are quoted, ‘as is’ from Sun Microsystems web site. This document can be used and distributed as long as the purpose is not commercial.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 1 of 40
SUN CERTIFIED WEB COMPONENT DEVELOPER FOR J2EE[tm] PLATFORM OBJECTIVES Section 1 - The Servlet Model 1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class. 1.2 For each of the HTTP methods, GET, POST, and HEAD, identify triggers that might cause a browser to use the method, and identify benefits or functionality of the method. 1.3 For each of the following operations, identify the interface and method name that should be used: • Retrieve HTML form parameters from the request • Retrieve a servlet initialization parameter • Retrieve HTTP request header information • 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 1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes: • Request • Session • Context 1.5 Given a life-cycle method: init, service, or destroy, identify correct statements about its purpose or about how and when it is invoked. 1.6 Use a RequestDispatcher to include or forward to a Web resource. Section 2 - The Structure and Deployment of Modern Servlet Web Applications 2.1 Identify the structure of a Web Application and Web Archive file, the name of the WebApp deployment descriptor, and the name of the directories where you place the following: • The WebApp deployment descriptor • The WebApp class files • Any auxiliary JAR files 2.2 Match the name with a description of purpose or functionality, for each of the following deployment descriptor elements: • Servlet instance • Servlet name • Servlet class • Initialization parameters • URL to named servlet mapping Section 3 - The Servlet Container Model 3.1 Identify the uses for and the interfaces (or classes) and methods to achieve the following features: • Servlet context init. parameters • Servlet context listener • Servlet context attribute listener Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 2 of 40
• Session attribute listeners 3.2 Identify the WebApp deployment descriptor element name that declares the following features: • Servlet context init. parameters • Servlet context listener • Servlet context attribute listener • Session attribute listeners 3.3 Distinguish the behavior of the following in a distributable: • Servlet context init. parameters • Servlet context listener • Servlet context attribute listener • Session attribute listeners Section 4 - Designing and Developing Servlets to Handle Server-side Expectations 4.1 For each of the following cases, identify correctly constructed code for handling business logic exceptions, and match that code with correct statements about the code's behavior: Return an HTTP error using the sendError response method; Return an HTTP error using the setStatus method. 4.2 Given a set of business logic exceptions, identify the following: The configuration that the deployment descriptor uses to handle each exception; How to use a RequestDispatcher to forward the request to an error page; Specify the handling declaratively in the deployment descriptor. 4.3 Identify the method used for the following: Write a message to the WebApp log; Write a message and an exception to the WebApp log. Section 5 - 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 different servlets within the same WebApp • Store objects into a session object • Retrieve objects from a session object • Respond to the event when a particular object is added to a session • Respond to the event when a session is created and destroyed • Expunge a session object 5.2 Given a scenario, state whether a session object will be invalidated. 5.3 Given that URL-rewriting must be used for session management, identify the design requirement on sessionrelated HTML pages. Section 6 - Designing and Developing Secure Web Applications 6.1 Identify correct descriptions or statements about the security issues: • Authentication, authorization • Data integrity • Auditing • Malicious code • Web site attacks 6.2 Identify the deployment descriptor element names, and their structure, that declare the following: • A security constraint • A Web resource Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 3 of 40
• The login configuration • A security role 6.3 Given an authentication type: BASIC, DIGEST, FORM, and CLIENT-CERT, identify the correct definition of its mechanism. Section 7 - Designing and Developing Thread-safe Servlets 7.1 Identify which attribute scopes are thread-safe: • Local variables • Instance variables • Class variables • Request attributes • Session attributes • Context attributes 7.2 Identify correct statements about differences between the multi-threaded and single-threaded servlet models. 7.3 Identify the interface used to declare that a servlet must use the single thread model. Section 8 - The Java Server Pages (JSP) Technology Model 8.1 Write the opening and closing tags for the following JSP tag types: • Directive • Declaration • Scriptlet • Expression 8.2 Given a type of JSP tag, identify correct statements about its purpose or use. 8.3 Given a JSP tag type, identify the equivalent XML-based tags. 8.4 Identify the page directive attribute, and its values, that: • Import a Java class into the JSP page • Declare that a JSP page exists within a session • Declare that a JSP page uses an error page • Declare that a JSP page is an error page 8.5 Identify and put in sequence the following elements of the JSP page lifecycle: • Page translation • JSP page compilation • Load class • Create instance • Call jspInit • Call _jspService • Call jspDestroy 8.6 Match correct descriptions about purpose, function, or use with any of the following implicit objects: • request • response • out • session • config • application Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 4 of 40
• • •
page pageContext exception
8.7 Distinguish correct and incorrect scriptlet code for: • A conditional statement; • An iteration statement Section 9 - Designing and Developing Reusable Web Components 9.1 Given a description of required functionality, identify the JSP page directive or standard tag in the correct format with the correct attributes required to specify the inclusion of a Web component into the JSP page. Section 10 - Designing and Developing JSP pages Using JavaBean Components 10.1 For any of the following tag functions, match the correctly constructed tag, with attributes and values as appropriate, with the corresponding description of the tag's functionality: • Declare the use of a JavaBean component within the page. • 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. • 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 the new value. 10.2 Given JSP page attribute scopes: request, session, application, identify the equivalent servlet code. 10.3 Identify techniques that access a declared JavaBean component. Section 11 - Designing and Developing JSP pages Using Custom Tags 11.1 Identify properly formatted tag library declarations in the Web application deployment descriptor. 11.2 Identify properly formatted taglib directives in a JSP page. 11.3 Given a custom tag library, identify properly formatted custom tag usage in a JSP page. Uses include: • An empty custom tag • A custom tag with attributes • A custom tag that surrounds other JSP code • Nested custom tags Section 12 - Designing and Developing a Custom Tag Library 12.1 Identify the tag library descriptor element names that declare the following: • The name of the tag • The class of the tag handler • The type of content that the tag accepts • Any attributes of the tag 12.2 Identify the tag library descriptor element names that declare the following: • The name of a tag attribute Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 5 of 40
• Whether a tag attribute is required • Whether or not the attribute's value can be dynamically specified 12.3 Given a custom tag, identify the necessary value for the bodycontent TLD element for any of the following tag types: • Empty-tag • Custom tag that surrounds other JSP code • Custom tag that surrounds content that is used only by the tag handler 12.4 Given a tag event method (doStartTag, doAfterBody, and doEndTag), identify the correct description of the methods trigger. 12.5 Identify valid return values for the following methods: • doStartTag • doAfterBody • doEndTag • PageConext.getOut 12.6 Given a "BODY" or "PAGE" constant, identify a correct description of the constant's use in the following methods: • doStartTag • doAfterBody • doEndTag 12.7 Identify the method in the custom tag handler that accesses: • A given JSP page's implicit variable • The JSP page's attributes 12.8 Identify methods that return an outer tag handler from within an inner tag handler. Section 13 13.1 Given a scenario description with a list of issues, select the design pattern (Value Objects, MVC, Data Access Object, or Business Delegate) that would best solve those issues. 13.2 Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: • Value Objects • MVC • Data Access Object • Business Delegate
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 6 of 40
1. The Servlet Model 1.1. Identify corresponding method in HttpServlet class for each of the following HTTP methods: 1.1.1. GET: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 1.1.2. POST: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 1.1.3. PUT: public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 1.2. GET, POST and HEAD 1.2.1. Identify triggers that might cause a browser to use: 1.2.1.1. GET: (a) typing url directly into a browser, (b) clicking on a hyperlink, (c) submitting html form with ‘method=get’ or no method attribute 1.2.1.2. POST: (a) submitting html form with ‘method=post’ 1.2.1.3. HEAD: (a) may be used by a browser to check modification time for purposes of caching 1.2.2. Identify benefits or functionality of: 1.2.2.1. GET: 1.2.2.1.1. designed for getting information (e.g. document, chart, results of query) 1.2.2.1.2. can include a query string (some servers limit this to about 240 characters) for sending information to server 1.2.2.1.3. requested page can be bookmarked 1.2.2.2. POST: 1.2.2.2.1. designed for posting information (e.g. credit card #, info to be stored in a db) 1.2.2.2.2. passes all its data (of unlimited length) to server directly over the socket connection as part of its http request body 1.2.2.2.3. posts cannot be bookmarked or, in some cases, even reloaded 1.2.2.2.4. hides sensitive information from server log by including it in the message body instead of the url query string 1.2.2.3. HEAD: 1.2.2.3.1. sent by a client when it wants to see only the headers of the response, to determine the document’s size, modification time, or general availability. 1.2.2.3.2. The service() method treats HEAD requests specially. It calls doGet with a modified response object, which suppresses any output but retains headers. 1.3. For each of the following operations, identify the interface and method name that should be used: 1.3.1. Retrieve HTML form parameters from the request: 1.3.1.1. Enumeration ServletRequest.getParameterNames() - returns empty enum if no parameters 1.3.1.2. String ServletRequest.getParameter(String name) - returns null if does not exist 1.3.1.3. String[] ServletRequest.getParameterValues(String name) - returns null if does not exist 1.3.2. Retrieve a servlet initialization parameter: 1.3.2.1. Enumeration ServletConfig.getInitParameterNames() - returns empty enum if no init parameters 1.3.2.2. String ServletConfig.getInitParameter(String name) - returns null if does not exist 1.3.3. Retrieve HTTP request header information: 1.3.3.1. Enumeration HttpServletRequest.getHeaderNames() - returns empty enum if no headers 1.3.3.2. String HttpServletRequest.getHeader(String name) - returns null if does not exist 1.3.3.3. Enumeration HttpServletRequest.getHeaders(String name) - returns empty enum if no headers 1.3.3.4. long getDateHeader(String name) - returns -1 if does not exist 1.3.3.5. int getIntHeader(String name) - returns -1 if does not exist 1.3.4. Set an HTTP response header; set the content type of the response 1.3.4.1. void HttpServletResponse.setHeader(String name, String value) - if header already exists, overwrites its value 1.3.4.2. void HttpServletResponse.setIntHeader(String name, int value) 1.3.4.3. void HttpServletResponse.setDateHeader(String name, long date) Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 7 of 40
1.3.4.4. void HttpServletResponse.addHeader(String name, String value) - if header already exists, adds an additional value 1.3.4.5. void HttpServletResponse.addIntHeader(String name, int value) 1.3.4.6. void HttpServletResponse.addDateHeader(String name, long date) 1.3.4.7. void HttpServletResponse.setContentType(String type) – if calling getWriter(), then setContentType should be called first 1.3.5. Acquire a text stream for the response 1.3.5.1. PrintWriter ServletResponse.getWriter() throws IOException - character encoding may be set by calling setContentType, which must be called before calling getWriter() 1.3.6. Acquire a binary stream for the response 1.3.6.1. ServletOutputStream ServletResponse.getOutputStream() throws IOException 1.3.7. Redirect an HTTP request to another URL 1.3.7.1. void HttpServletResponse.sendRedirect(String location) throws IllegalStateException IOException 1.3.7.2. sets status to SC_MOVED_TEMPORARILY, sets the Location header, and performs an implicit reset on the response buffer before generating the redirect page; headers set before sendRedirect() remain set 1.3.7.3. must be called before response body is committed, else throws IllegalStateException 1.3.7.4. the path may be relative or absolute 1.3.7.5. to support clients without redirect capability, method writes a short response body that contains a hyperlink to the new location; so do not write your own msg body 1.4. Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes: 1.4.1. Request (Interfaces: ServletRequest and HttpServletRequest) 1.4.1.1. Enumeration ServletRequest.getAttributeNames() - returns empty enumeration if no attributes 1.4.1.2. Object ServletRequest.getAttribute(String name) - returns null if does not exist 1.4.1.3. void setAttribute(String name, Object obj) - most often used in conjunction with RequestDispatcher; attrib names should follow same convention as pkg names 1.4.1.4. void removeAttribute(String name) 1.4.1.5. String ServletRequest.getCharacterEncoding() - returns encoding used in request body, or null if not specified 1.4.1.6. int ServletRequest.getContentLength() - returns length of request body or -1 if unknown 1.4.1.7. String ServletRequest.getContentType() - returns mime type of request body or null if unknown 1.4.1.8. String ServletRequest.getProtocol() - returns protocol/version, e.g. HTTP/1.1 1.4.1.9. String ServletRequest.getScheme() - scheme used to make this request, e.g. ftp, http, https 1.4.1.10.String ServletRequest.getServerName() 1.4.1.11.int ServletRequest.getServerPort() 1.4.1.12.String HttpServletRequest.getAuthType() - e.g. BASIC, SSL, or null if not protected 1.4.1.13.String HttpServletRequest.getContextPath() - e.g. “/myservlet” 1.4.1.14.String HttpServletRequest.getMethod() - e.g. GET, POST, HEAD, PUT 1.4.1.15.String HttpServletRequest.getPathInfo() - returns extra path info (string following servlet path but preceding query string); null if does not exist 1.4.1.16.String HttpServletRequest.getPathTranslated() - translates extra path info to a real path on the server 1.4.1.17.String HttpServletRequest.getQueryString() - returns query string; null if does not exist 1.4.1.18.String HttpServletRequest.getRemoteUser() - returns null if user not authenticated 1.4.1.19.Principal HttpServletRequest.getUserPrincipal() - returns null if user not authenticated 1.4.1.20.String HttpServletRequest.getRequestURI() - e.g. if request is “POST /some/path.html HTTP/1.1”, then returns “/some/path.html”
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 8 of 40
1.4.1.21.String HttpServletRequest.getServletPath() - returns servlet path and name, but no extra path info 1.4.1.22.HttpSession HttpServletRequest.getSession(boolean create) 1.4.1.23.HttpSession HttpServletRequest.getSession() - calls getSession(true) 1.4.2. Session (Interface: HttpSession) 1.4.2.1. Enumeration HttpSession.getAttributeNames() - returns empty enumeration if no attributes; IllegalStateException if session invalidated 1.4.2.2. Object HttpSession.getAttribute(String name) - returns null if no such object 1.4.2.3. void HttpSession.setAttribute(java.lang.String name, java.lang.Object value) 1.4.2.4. void HttpSession.removeAttribute(java.lang.String name) 1.4.2.5. String HttpSession.getId() - returns unique session identifier assigned by servlet container 1.4.2.6. long HttpSession.getLastAccessedTime() - time when client last sent a request associated with this session 1.4.2.7. int HttpSession.getMaxInactiveInterval() - returns number of seconds this session remains open between client requests; -1 if session should never expire 1.4.2.8. void HttpSession.setMaxInactiveInterval(int interval) 1.4.3. Context (Interface: ServletContext) 1.4.3.1. Enumeration getAttributeNames() - Returns an Enumeration containing the attribute names available within this servlet context. 1.4.3.2. Object getAttribute(String name) - Returns the servlet container attribute with the given name, or null if there is no attribute by that name. 1.4.3.3. void setAttribute(String name, java.lang.Object object) - Binds an object to a given attribute name in this servlet context. 1.4.3.4. void removeAttribute(String name) - Removes the attribute with the given name from the servlet context. 1.4.3.5. ServletContext getContext(String uripath) - Returns a ServletContext object that corresponds to a specified URL on the server. 1.4.3.6. String getInitParameter(String name) - Returns a String containing the value of the named context-wide initialization parameter, or null if does not exist. 1.4.3.7. Enumeration getInitParameterNames() - Returns names of the context's initialization parameters as Enumeration of String objects 1.4.3.8. int getMajorVersion() - Returns the major version of the Java Servlet API that this servlet container supports. 1.4.3.9. int getMinorVersion() - Returns the minor version of the Servlet API that this servlet container supports. 1.4.3.10.String getMimeType(String file) - Returns the MIME type of the specified file, or null if the MIME type is not known. 1.4.3.11.RequestDispatcher getNamedDispatcher(String name) - Returns a RequestDispatcher object that acts as a wrapper for the named servlet. 1.4.3.12.RequestDispatcher getRequestDispatcher(String path) - Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. 1.4.3.13.String getRealPath(String path) - Returns a String containing the real path for a given virtual path. 1.4.3.14.java.net.URL getResource(String path) - Returns a URL to the resource that is mapped to a specified path. 1.4.3.15.InputStream getResourceAsStream(String path) - Returns the resource located at the named path as an InputStream object. 1.4.3.16.String getServerInfo() - Returns the name and version of the servlet container on which the servlet is running. 1.5. For each of the following life-cycle method, identify its purpose and how and when it is invoked: 1.5.1. public void init() throws ServletException: 1.5.1.1. called after server constructs the servlet instance and before the server handles any requests
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 9 of 40
1.5.1.2. depending on the server and web app configuration, init() may be called at any of these times: (a) when server starts, (b) when the servlet is first requested, just before the service() method is invoked, (c) at the request of the server administrator 1.5.1.3. if servlet specifies
in its web.xml file, then upon server startup, the server will create an instance of the servlet and call its init() method. 1.5.1.4. typically used to perform servlet initialization, e.g. loading objects used by servlet to handle requests, reading in servlet init parameters, starting a background thread. 1.5.1.5. servlet cannot be placed into service if init method throws ServletException or does not return within a server-defined time period 1.5.1.6. init() can only be called once per servlet instance; so would still need to synchronize access to class variables 1.5.2. public void service() throws ServletException, IOException: 1.5.2.1. called by the servlet container to allow the servlet to respond to a request. 1.5.2.2. this method is only called after the servlet's init() method has completed successfully. 1.5.2.3. servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. developers must be aware to synchronize access to any shared resources such as files and network connections, as well as the servlet's class and instance variables. 1.5.3. public void destroy(): 1.5.3.1. called after the servlet has been taken out of service and all pending requests to the servlet have been completed or timed out 1.5.3.2. gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory 1.5.3.3. calling super.destroy() causes GenericServlet.destroy() to write a note to the log that the servlet is being destroyed 1.5.3.4. destroy()called once per servlet instance; destroy() not called if server crashes, so should save state (if needed) periodically after servicing requests 1.5.4. Note: servlet reloading 1.5.4.1. most servers automatically reload a servlet after its class file (under servlet dir, e.g. WEBINF/classes) changes. when a server dispatches a request to a servlet, it first checks whether the servlet’s class file has changed on disk. If it has, then the server creates a new custom class loader, and reloads the entire web application context. 1.5.4.2. class reloading is not based on support class changes or on changes in classes found in the server’s classpath, which are loaded by the core, primordial class loader. 1.6. Use a RequestDispatcher to include or forward to a Web resource 1.6.1. include: 1.6.1.1. public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException 1.6.1.2. Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. 1.6.1.3. The ServletRequest object has its path elements (e.g. attributes request_uri, context_path, and servlet_path) and parameters remain unchanged from the caller's. If the included element requires information on its own path elements, it’s available in request attributes (javax.servlet.include.request_uri, context_path etc) 1.6.1.4. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored. 1.6.1.5. The request and response parameters must be the same objects as were passed to the calling servlet's service method. 1.6.1.6. The included resource must use the same output mechanism (e.g. PrintWriter or ServletOutputStream) as the caller’s 1.6.1.7. Information can be passed to target using attached query string or using request attributes set with setAttribute() method. 1.6.1.8. include can be called at any time, even after the flush is called on the response. Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 10 of 40
1.6.2. forward: 1.6.2.1. public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException 1.6.2.2. Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response. The forwarding servlet generates no output, but may set headers. 1.6.2.3. The ServletRequest object has its path attributes adjusted to match the path of the target resource. Any new request parameters are added to the original. 1.6.2.4. forward() should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward. 1.6.2.5. The request and response parameters must be the same objects as were passed to the calling servlet's service method. 1.6.2.6. Information can be passed to target using attached query string or using request attributes set with setAttribute() method. 1.6.2.7. forwarding to an html page containing relative url’s included (e.g.
tags) is a bad idea, because forward() does not notify client about the directory from which the page is served, hence the links may be broken. Instead, use sendRedirect(). 1.6.3. Note: to get a request dispatcher object: 1.6.3.1. public javax.servlet.RequestDispatcher ServletRequest.getRequestDispatcher(String path) path may be relative, and cannot extend outside current servlet context 1.6.3.2. public javax.servlet.RequestDispatcher ServletRequest.getNamedDispatcher(String name) name is the registered name in web.xml file 1.6.3.3. ServletContext also supports these methods, but its getRequestDispatcher method accepts only absolute paths, and not relative paths. Use the request’s methods, ServletContext method may be depracted in future.
2. The Structure and Deployment of Modern Servlet Web Applications 2.1. Identify the following: 2.1.1. Structure of a Web Application 2.1.1.1. the following web application hierarchy is placed under a context root directory within the server’s webapps directory (or something similar, depending on the server) : 2.1.1.1.1. /[any files to be served to the client, e.g. index.html, images/banner.gif] 2.1.1.1.2. /WEB-INF/web.xml 2.1.1.1.3. /WEB-INF/lib/[any required jar files] 2.1.1.1.4. /WEB-INF/classes/[servlet and support class files in their package hierarchies, e.g. com/mycorp/frontend/CorpServlet.class] 2.1.2. Structure of a Web Archive file 2.1.2.1. this is a JAR archive of the Web Application structure above; it just has a WAR extension so that people and tools know to treat it differently 2.1.2.2. a WAR file can be placed in a server’s webapps directory, and the server will extract it on startup 2.1.3. Name of Web App deployment descriptor: web.xml 2.1.4. Name of directories where you place the following: 2.1.4.1. Web App deployment descriptor: see 2.1.1.2 2.1.4.2. Web App class file: see 2.1.1.4 2.1.4.3. Any auxhiliary JAR files: see 2.1.1.3 2.1.4.4. 2.2. Identify the purpose or functionality for each of the following deployment descriptor elements: Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 11 of 40
2.2.1. servlet instance: 2.2.1.1. <servlet> {servlet-name, servlet-class, init-param, etc.} 2.2.1.2. declares a servlet instance; included within <web-app> tags 2.2.2. servlet name: 2.2.2.1. <servlet-name> 2.2.2.2. registers the servlet under a specific name 2.2.3. servlet class: 2.2.3.1. <servlet-class> 2.2.3.2. contains the fully qualified class name of the servlet 2.2.4. initialization parameters: 2.2.4.1.
{param-name, param-value} 2.2.4.2. defines values that can be set at deployment time and read at run-time via ServletConfig.getInitParameter(String name) 2.2.5. url to named servlet mapping 2.2.5.1. <servlet-mapping> <servlet-name> helloServlet
/hello.html this maps http://server:port/context_root/hello.html to the helloServlet servlet. 2.2.5.2. zero or more mappings may be defined per web app 2.2.5.3. 4 types of mappings, searched in the following order: (a) explicit mappings, e.g. /hello.html (b) path prefix mappings e.g. /dbfile/* (c) extension mappings e.g. *.jsp or *.gif (d) the default mapping “/”, identifying the default servlet for the web app 3. The Servlet Container Model 3.1. Servlet Context Init Parameters 3.1.1.1. purpose: defines init parameters accessible by all servlets in the web application context; setable at deployment-time, but accessible at run-time 3.1.1.2. interfaces (or classes): javax.servlet.ServletContext 3.1.1.3. methods: public Enumeration getInitParameterNames() and public String getInitParameter(String name) 3.1.1.4. webapp deployment descriptor element name:
{param-name, param-value} 3.1.1.5. behavior in a distributable: Consider that a different instance of the ServletContext may exist on each different JVM and/or machine. Therefore, the context should not be used to store application state. Any state should be stored externally, e.g. in a database or ejb. 3.2. Servlet Context Listener 3.2.1.1. purpose: An object that implements the ServletContextListener interface is notified when its web app context is created or destroyed 3.2.1.2. interfaces (or classes): javax.servlet.ServletContextListener 3.2.1.3. methods: 3.2.1.3.1. void contextInitialized(ServletContextEvent e): called during web server startup or when context is added or reloaded; requests will not be handled until this method returns 3.2.1.3.2. void contextDestroyed(ServletContextEvent e): called during web server shutdown or when context is removed or reloaded; request handling will be stopped before this method is called 3.2.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class name} <listener> 3.2.1.5. behavior in a distributable: Each context instance (on different jvm’s and/or machines) will have its own instance of the listener object. Therefore, if a context on one jvm/machine is initialized or destroyed, it will not trigger a listener on any other jvm/machine. 3.3. Servlet Context Attribute Listener 3.3.1.1. purpose: An object that implements the ServletContextAttributeListener interface is notified when attributes are added to or removed from its web app context Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 12 of 40
3.3.1.2. interfaces (or classes): javax.servlet.ServletContextAttributeListener 3.3.1.3. methods: void attributeAdded/attributeRemoved/attributeReplaced(ServletContextAttributeEvent e) 3.3.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class name} <listener> 3.3.1.5. behavior in a distributable: Addition, removal or replacement of an attribute in a context will only affect the listener for that context, and not other context “instances” on other jvm’s and/or machines. 3.4. HttpSession Attribute Listener 3.4.1.1. purpose: An object that implements the HttpSessionAttributeListener interface is notified when a session attribute is added, removed or replaced 3.4.1.2. interfaces (or classes): javax.servlet.http.HttpSessionAttributeListener 3.4.1.3. methods: void attributeAdded/attributeRemoved/attributeReplaced(HttpSessionBindingEvent e) 3.4.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class name} <listener> 3.4.1.5. behavior in a distributable: sessions may migrate from one jvm or machine to another; hence the session unbind event may occur on a different jvm/machine than the session bind event. 3.5. Http Session Listener 3.5.1.1. purpose: An object that implements the HttpSessionListener interface is notified when a session is created or destroyed in its web app context 3.5.1.2. interfaces (or classes): javax.servlet.http.HttpSessionListener 3.5.1.3. methods: 3.5.1.3.1. void sessionCreated(HttpSessionEvent e) 3.5.1.3.2. void sessionDestroyed(HttpSessionEvent e) - called when session is destroyed (invalidated) 3.5.1.4. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class name} <listener> 3.5.1.5. behavior in a distributable: sessions may migrate from one jvm or machine to another; hence the session destroy event may occur on a different jvm/machine than the session create event. 3.6. Http Session Activation Listener 3.6.1.1. purpose: Designed to handle sessions that migrate from one server to another. The listener is notified when any session is about to passivate (move) and when the session is about to activate (become alive) on the second host. It gives an app the chance to, for example, persist nonserializable data across jvm’s. 3.6.1.2. mothods: 3.6.1.2.1. void sessionWillPassivate(HttpSessionEvent e) - session is about to move; it will already be out of service when this method is called 3.6.1.2.2. void sessionDidActivate(HttpSessionEvent e) - session has been activated on new server; session will not yet be in service when this method is called 3.6.1.3. webapp deployment descriptor element name: <listener> <listener-class> {fully qualified class name} <listener> 4. Designing and Developing Servlets to Handle Server-Side Exceptions 4.1. For each of the following cases, identify correctly constructed code for handling business logic exceptions, and match that code with correct statements about the code’s behavior: 4.1.1. return an http error using setStatus 4.1.1.1. public void HttpServletResponse.setStatus(int statusCode) 4.1.1.2. if this is not called, the server by default sets the status code to SC_OK(200). 4.1.1.3. example status codes: HttpServletResponse.SC_OK(200), SC_NOT_FOUND(404), SC_NO_CONTENT, SC_MOVED_TEMPORARILY/PERMANENTLY, SC_UNAUTHORIZED, SC_INTERNAL_SERVER_ERROR, SC_NOT_IMPLEMENTED, SC_SERVICE_UNAVAILABLE Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 13 of 40
4.1.1.4. calling setStatus() on an error leaves a servlet with the responsibility of generating the error page 4.1.1.5. must be called before the response is committed, otherwise call is ignored 4.1.2. return an http error using sendError 4.1.2.1. public void HttpServletResponse.sendError(int statusCode[, String statusMessage]) throws IllegalStateException, IOException 4.1.2.2. the sendError() method causes the server to generate and send an appropriate server-specific page describing the error (unless <error-page> defined in web.xml) 4.1.2.3. with the two argument version of this method, the server may include the status message in the error page, depending on the server implementation 4.1.2.4. must be called before response body is committed, else throws IllegalStateException 4.2. Given a set of business logic exceptions, identify the following: 4.2.1. configuring deployment descriptor for error handling 4.2.1.1. <web-app> … <error-page> <error-code>404 error-code>
/404.html … 4.2.1.2. this specifies that any call to sendError(), from within this web app, with 404 error code should display /404.html; this includes requests for static pages that result in 404 error code 4.2.1.3. the value of location must begin with ‘/’, is treated as based in the context root, and must refer to a resource within the context 4.2.1.4.
may be dynamic (e.g. jsp, servlet); for these, the server makes available the following request attributes: javax.servlet.error.status_code and javax.servlet.error.message 4.2.2. configuring deployment descriptor for exception handling 4.2.2.1. <web-app> … <error-page> <exception-type> javax.servlet.ServletException exception-type > /servlet/ErrorDisplay … 4.2.2.2. how the server handles exceptions thrown by a servlet is server-dependent, unless an <errorpage> entry exists for a specific exception type or a superclass 4.2.2.3. may be dynamic (e.g. jsp, servlet); for these, the server makes available the following request attributes: javax.servlet.error.exception_type & javax.servlet.error.message; the exception object itself is not made available; hence no way to get a stack trace 4.2.2.4. servlets must catch all exceptions except those that subclass ServletException, IOException and RuntimeException (IOException may be caused by client closing the socket by exiting the browser) 4.2.2.5. a ServletException may be created with a message and a “root cause”, both optional, e.g. { throw new ServletException(“execution interrupted”, InterruptedException); } 4.2.2.6. public Throwable ServletException.getRootCause() returns the root cause exception 4.2.2.7. javax.servlet package also defines a subclass of ServletException called UnavailableException(String msg[, int seconds]), which causes server to take servlet out of service 4.2.3. using RequestDispatcher to forward to an error page: see section 1.6 above 4.3. Identify the method used for the following: 4.3.1. writing a message to the Web App log: 4.3.1.1. void log(String msg) - Writes the specified message to a servlet log file, usually an event log. 4.3.1.2. void log(String message, java.lang.Throwable throwable) - Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. 4.3.1.3. these are methods are available in GenericServlet and ServletContext Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 14 of 40
4.3.2. writing a message and an exception to the Web App log: 4.3.2.1. public void GenericServlet.log(String msg, Throwable t) 4.3.2.2. writes the given message and the Throwable’s stack trace to a servlet log; exact output format and location of log are server specific 5. Designing and Developing Servlets Using Session Management 5.1. Identify the interface and method for each of the following: 5.1.1. retrieve a session object across multiple requests to the same or different servlets within the same webapp 5.1.1.1. public HttpSession HttpServletRequest.getSession([boolean create]) 5.1.1.2. if no argument provided, then server will automatically create a new session object if none exists for the user in the web app context 5.1.1.3. to make sure the session is properly maintained, getSession must be called at least once before committing the response 5.1.1.4. sessions are scoped at the web application level; so a servlet running inside one context cannot access session information saved by another context. 5.1.1.5. behind the scenes, the client’s session id is usually saved on the client in a cookie called JSESSIONID. For client that don’t support cookies, the session ID can be sent as part of a rewritten URL, encoded using a jsessionid path parameter. 5.1.1.6. note that a requested session id may not match the id of the session returned by the getSession() method, such as when the id is invalid. one can call req.isRequestedSessionIDValid() to test if the requested session id (that which was defined in the rewritten url or the persistent cookie) is valid. 5.1.2. store objects into a session object 5.1.2.1. public void HttpSession.setAttribute(String name, Object value) throws IllegalStateException 5.1.2.2. binds the specified object under the specified name. Any existing binding with the same name is replaced. 5.1.2.3. IllegalStateException thrown if session being accessed is invalid 5.1.3. retrieve objects from a session object 5.1.3.1. public Object HttpSession.getAttribute(String name) throws IllegalStateException -- returns the object bound under the specified name or null if there is no binding 5.1.3.2. public Enumeration HttpSession.getAttributeNames() throws IllegalStateException -- returns all bound attribute names as an enumeration of Strings (empty enum if no bindings) 5.1.3.3. public void HttpSession.removeAttribute(String name) throws IllegalStateException -removes binding or does nothing if binding does not exist 5.1.4. respond to the event when a particular object is added to a session 5.1.4.1. any object that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound to or unbound from a session. 5.1.4.2. public void valueBound(HttpSessionBindingEvent event) is called when the object is bound to a session 5.1.4.3. public void valueUnbound(HttpSessionBindingEvent event) is called when the object is unbound from a session, by being removed or replaced, or by having the session invalidated 5.1.5. respond to the event when a session is created or destroyed: see section 3.5 5.1.6. expunge a session object 5.1.6.1. public void HttpSession.invalidate() – causes the session to be immediately invalidated. All objects stored in the session are unbound. Call this method to implement a “logout”. 5.2. given a scenario, state whether a session object will be invalidated 5.2.1. ideally, a session would be invalidated as soon as the user closed his browser, browsed to a different site, or stepped away from his desk. Unfortunately, there’s no way for a server to detect any of these events. 5.2.2. session may expire automatically, after a set timeout of inactivity (tomcat default is 30 minutes) 5.2.3. timeout can be overridden in web.xml file by specifying <web-app>…<session-config><sessiontimeout>e.g. 60 Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 15 of 40
5.2.4. timeout can be overridden for a specific session by calling HttpSession.setMaxInactiveInterval(int secs) – negative value indicates session should never time out. 5.2.5. session may expire manually, when it is explicitly invalidated by a servlet by calling invalidate() 5.2.6. a server shutdown may or may not invalidate a session, depending on the capabilities of the server 5.2.7. when a session expires (or is invalidated), the HttpSession object and the data values it contains are removed from the system; if you need to retain information beyond a session lifespan, you should keep it in an external location (e.g. a database) 5.3. given that url-rewriting must be used for session management, identify the design requirement on sessionrelated html pages 5.3.1. For a servlet to support session tracking via URL rewriting, it has to rewrite every local URL before sending it to the client. 5.3.2. public String HttpServletResponse.encodeURL(String url) 5.3.3. public String HttpServletResponse.encodeRedirectURL(String url) 5.3.4. both methods encode the given url to include the session id and returns the new url, or, if encoding is not needed or is not supported, it leaves the url unchanged. The rules for when and how to encode are server-specific. 5.3.5. note that when using session tracking based on url rewriting that multiple browser windows can belong to different sessions or the same session, depending on how the windows were created and whether the link creating the windows was url rewritten. 5.4. Note: Using Cookies: 5.4.1.1. To send a cookie to a client: {Cookie cookie = new Cookie(“name”, “value”); res.addCookie(cookie);}. 5.4.1.2. To retrieve cookies: {Cookie[] cookies = req.getCookies();} 6. Designing and Developing Secure Web Applications 6.1. identify correct descriptions or statements about the security issues: 6.1.1. Authentication: Being able to verify the identities of the parties involved 6.1.2. Authorization: Limiting access to resources to a select set of users or programs 6.1.3. Integrity: Being able to verify that the content of the communication is not changed during transmission 6.1.4. Auditing: Keeping a record of resource access that was granted or denied might be useful for audit purposes later. To that end, auditing and logs serve the useful purposes of preventing a break-in or analyzing a break-in post mortem. 6.1.5. Malicious Code: 6.1.6. Web Site Attacks: 6.1.7. Confidentiality: Ensuring that only the parties involved can understand the communication 6.2. Identify deployment descriptor element names, and their structures, that declare the following 6.2.1. <web-app> <servlet> <servlet-name>secretSalary<servlet-name> <servlet-class>SalaryServer <security-constraint> indicates certain pages in a web app are to be accessed by users in a certain role (role-to-user mappings stored in server-specific format) <web-resource-collection> <web-resource-name>protectedResource /servlet/SalaryServer same wildcards allowed as for servlet mappings /servlet/secretSalary GET if no methods specified, then all methods are protected POST manager Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 16 of 40
ceo if no role-name, then not viewable by any user; if role-name = “*” then viewable by all roles <user-data-constraint> CONFIDENTIAL optional, indicates SSL security BASIC/DIGEST/FORM/CLIENT-CERT Default optional, only useful for BASIC authentication optional, only useful for FORM based authentication /loginpage.html /errorpage.html <security-role> manager not req’d; explicitly declaring the webapp’s roles supports tool-based manipulation of the file 6.3. For each of the following authentication types, identify the correct definition of its mechanism 6.3.1. BASIC 6.3.1.1. web server maintains a db of usernames and passwords, and identifies certain web resources as protected. When these are accessed, web server requests username and password; this information is sent back to the server, which checks it against its database; and either allows or denies access. 6.3.1.2. Disadvantage: provides no confidentiality, no integrity, and only the most basic authentication. 6.3.1.3. Disadvantage: Transmitted passwords are encoded using easily reversable Base64 encoding, unless additional SSL encryption employed. 6.3.1.4. Disadvantage: plus, passwords are often stored on server in clear text 6.3.1.5. Advantage: very easy to set up; useful for low-security environments, e.g. subscription-based online newspaper 6.3.2. DIGEST 6.3.2.1. variation to BASIC scheme; instead of transmitting password over network directly, digest of password used instead, produced by taking a hash of username, password, uri, http method, and a randomly generated nonce value provided by server. Server computes digest as well, and compares with user submitted digest. 6.3.2.2. Advantage: transactions are somewhat more secure than with basic authentication, since each digest is valid for only a single uri request and nonce value. 6.3.2.3. Disadvantage: server must still maintain a database of the original passwords 6.3.2.4. Disadvantage: digest authentication is not supported by very many browsers 6.3.3. FORM 6.3.3.1. the login page must include a form with a POST to the URL “j_security_check” with a username sent as j_username and a password j_password. 6.3.3.2. any time the server receives a request for a protected resource, the server checks if the user has already logged in, e.g. server might look for Principal object in HttpSession object. If Principal found, then roles are checked against security contraints; if Principal not authorized, then client redirected to 6.3.3.3. Advantage: allows users to enter your site through a well-designed, descriptive and friendly login page 6.3.3.4. Disadvantage: similar to BASIC, password is transmitted in clear text, unless SSL used Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 17 of 40
6.3.3.5. Disadvantage: similar to BASIC, no standard logout mechanism (calling session.invalidate() may work for FORM, but no guarantees), would need to close browser 6.3.3.6. Disadvantage: error page does not have access to any special information reporting why access was denied or even which page it should point the user at to try again 6.3.3.7. Disadvantage: similar to BASIC, relies on server to authenticate, so only captures username and password, not custom fields e.g. PIN #. 6.3.4. CLIENT-CERT 6.3.4.1. BASIC, even with SSL encryption, does not ensure strong client authentication since anyone could have guessed or gotten hold of client’s username and password 6.3.4.2. upon accessing a protected resource, the server requests the client’s certificate; the client then sends its signed certificate (many browsers require the client user enter a password before they will send the certificate), and the server verifies the certificate. If browser has no certificate, or if it is not authorized, then access is denied. 6.3.4.3. Advantage: the client will never see a login page, although the browser may prompt for a password to unlock their certificate before it is sent 6.3.4.4. Disadvantages: users must obtain and install signed certificates, servers must maintain a database of all accepted public keys, and servers must support SSL 3.0 in the first place. 7. Designing and Developing Thread-Safe Servlets 7.1. Identify which attribute scopes are thread-safe: 7.1.1. local variables: yes, thread-safe 7.1.2. instance variables: not thread-safe, since a single servlet instance may be handling multiple service requests at any given time 7.1.3. class variables: not thread-safe, since multiple servlets and/or service requests may try to access a class variable concurrently 7.1.4. request attributes: yes, thread-safe, since the request object is a local variable 7.1.5. session attributes: not thread-safe, since sessions are scoped at the web application level, hence the same session object can be accessed concurrently by multiple servlets and their service requests 7.1.6. context attributes: not thread-safe, since the same context object can be accessed concurrently by multiple servlets and their service requests 7.2. Identify correct statements about differences between multi-threaded and single-threaded servlet models 7.2.1. multi-thread model servlet: 7.2.1.1. one servlet instance per registered name 7.2.1.2. for each servlet request, the server spawns a separate thread which executes the servlet’s service() method 7.2.1.3. must synchronize access to instance variables 7.2.2. single-thread model servlet: 7.2.2.1. has a pool of servlet instances per registered name (depending on the server implementation, the pool size may be configurable or not, and may be as little as one.) 7.2.2.2. guaranteed by server “that no two threads will execute concurrently in the servlet’s service method” 7.2.2.3. considered thread-safe and isn’t required to synchronize access to instance variables 7.2.2.4. does not prevent synchronization problems that result from servlets accessing shared resources such as static variables or objects outside the scope of the servlet (e.g. ServletContext, HttpSession) 7.2.2.5. server might end up creating more instances than the system can handle, e.g. each instance might have its own db connection, hence in total there may be more db connections than the db server can handle. 7.3. Identify the interface used to declare that a servlet must use the single thread model 7.3.1. interface javax.servlet.SingleThreadModel { // this is an empty “tag” interface }
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 18 of 40
Section 8: The JSP Model 8.1 Write the opening and closing tags for the following JSP tag types: • Directive, • Declaration, • Scriptlet , • Expression a) Directive - <%@ Directive {attribute=”value”}* %> b) Declaration - <%! JavaDeclaration %> c) Scriptlet - <% JavaStatements %> d) Expression - <%= JavaExpression %> 8.2 Given a type of JSP tag, identify correct statements about its purpose or use a) Directive – controls translation and compilation phase. b) Declaration – declare a java variable or method. No output produced. Class level declarations. c) Scriptlet – valid java statements. No output produced unless out is used d) Expression – evaluation of expression to a String and then included in the output. 8.3 Given a JSP tag type, identify the equivalent XML-based tags. a) <%@ page …%> == <jsp:directive.page …/> b) <%! …%> == <jsp:declaration> … c) <% …%> == <jsp:scriptlet> … d) <%= …%> == <jsp:expression> … taglib directive doesn’t have XML equivalent, it is included in <jsp:root> element as a xmlns element. <%@taglib uri=http://my.com/my.tld prefix=”my” %> will become <jsp:root xmlns:my=http://my.com/my.tld> Template text should use <jsp:text> element. 8.4 Identify the page directive attribute, and its values, that: • Import a Java class into the JSP page <%@ page import=”java.util.Date” %> (Multiple declarations are separated by comma) • Declare that a JSP page exists within a session <%@ page session=”true”%> • Declare that a JSP page uses an error page <%@ page errorPage=”errorPage.jsp” %> • Declare that a JSP page is an error page <%@ page isErrorPage=”true” %> 8.5 Identify and put in sequence the following elements of the JSP page lifecycle: • Page translation • JSP page compilation • Load class • Create instance • Call jspInit • Call _jspService • Call jspDestroy The above order is already correct. Basically there are two phases, translation and execution. During the translation phase the container locates or creates the JSP page implementation class that corresponds to a given JSP page. This process is determined by the Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 19 of 40
semantics of the JSP page. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page. A tag library may optionally provide a validation method to validate that a JSP page is correctly using the library. A JSP container has flexibility in the details of the JSP page implementation class that can be used to address quality-of-service --most notably performance--issues. During the execution phase the JSP container delivers events to the JSP page implementation object. The container is responsible for instantiating request and response objects and invoking the appropriate JSP page implementation object. Upon completion of processing, the response object is received by the container for communication to the client. 8.6 Match correct descriptions about purpose, function, or use with any of the following implicit objects: • request • response • out • session • config • application • page • pageContext • exception implicit object request
Type
Purpose/Useful methods
Scope
Subclass of ServletRequest
request
response out session
Subclass of ServletResponse JspWriter HttpSession
config
ServletConfig
application
ServletContext
page pageContext
Object PageContext
exception
java.lang.Throwable
The request. getAttribute, setAttribute, getParameter, getParameterNames, getParameterValues The response Object for writing to the output stream. flush, getBufferSize created as long as <% page session=”false” %> is not used. Valid for Http protocol only. getAttribute, setAttribute Specific to a servlet instance. Same as Servlet.getServletConfig() getInitParameter, getInitParameterNames Available to all Servlets (application wide). Provides access to resources of the servlet engine (resources, attributes, context params, request dispatcher, server info, URL & MIME resources). this instance of the page (equivalent servlet instance ‘this’). provides a context to store references to objects used by the page, encapsulates implementation-dependent features, and provides convenience methods. created only if <%@ page isErrorPage=”true” %>
PageContext provides a number of facilities to the page/component author and page implementor including • a single API to manage the various scoped namespaces • a number of convenience API’s to access various public objects • a mechanism to obtain the JspWriter for output • a mechanism to manage session usage by the page • a mechanism to expose page directive attributes to the scripting environment • mechanisms to forward or include the current request to other active compo-nents in the application • a mechanism to handle errorpage exception processing The methods related to attributes are: setAttribute(), getAttribute(), removeAttribute() – deals page scope Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 20 of 40
page page session page application page page page
findAttribute(), - looks in all scopes int getAttributesScope() and getAttributeNamesInScope(int scope) 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 error handling: forward(relativeURl), include(relativeURl), and handlePageException(Exception/Throwable). 8.7 Distinguish correct and incorrect scriptlet code for: • A conditional statement; • An iteration statement a) Conditional Statement <% if (event.equals(“ENTER_RECORD”)) { %> <jsp:include page=”enterRecord.jsp” flush=true”/> <% } else if (event.equals (“NEW_RECORD”)) { %> <jsp:include page=”newRecord.jsp” flush=”true/> <% } else { %> <jsp:include page=”default.jsp” flush = true”/> <% } %> b) Iterative Statement <% Hashtable h = (Hashtable) session.getAttribute(“charges”); if (h != null) { %> <% Enumeration charges = h.keys(); While (charges.hasMoreElements()) { String proj = (String) charges.nextElement(); Charge ch = (Charge) h.get(proj); %> - name = <%= ch.getName() %> , project = <%= proj %> , hours = <%= ch.getHours() %> , date = <%= ch.getDate() %> <% } %>
<%}%> Section 9: Designing and Developing Reusable Web Components 9.1 Given a description of required functionality, identify the JSP directive or standard tag in the correct format with the correct attributes required to specify the inclusion of a Web component into the JSP page. Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 21 of 40
• Include Directive - Translation-time <%@ include file=”relativeURL” %> Content is parsed by JSP container. • Include Action - Request-time <jsp:include page=”relativeURL” flush=true|false /> <jsp:param name=”” value=””|<%= expression > > Content is not parsed; it is included in place. In case of dynamic resources the result from the processing is included. Section 10: 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 of the tag's functionality: • Declare the use of a JavaBean component within the page. • 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. • 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 the new value. <jsp:useBean> <jsp:useBean id=”connection”class=”com.myco.myapp.myBean” scope=”page” /> - create if bean doesn’t exist <jsp:useBean id=”connection” beanName=”com.myco.myapp.myBean.ser” /> - create from a serialized object <jsp:useBean id=”connection” type=”com.myco.myapp.myBean” /> - Bean should already exist <jsp:useBean id="name" scope="page|request|session|application" typeSpec /> typeSpec ::=
class=”className” | class=”className” type=”typeName” | type=”typeName” class=”className” | beanName=”beanName” type=”typeName” | type=”typeName” beanName=”beanName” | type=”typeName”
•First the container looks for the specified bean in the specified scope (default scope is page), if it is not there, one will be created. With beanName, you can specify a serialized file for instantiating the bean from. •class or beanName is required, type is optional. •If class and beanName are not specified (only type is specified), the bean will not be created, it should already exist in the specified scope. •The specified class should not be an abstract class or an interface and should have a public no-args constructor. If type is specified, the instantiated class is casted to the type. Instantiate method is used to create the bean. •jsp:useBean action element can have a non-empty body, e.g. a jsp:setProperty action; the body will be executed for newly instantiated beans only <jsp:useBean id="name" scope="page|request|session|application" typeSpec > body – usually this will be scriptlets or jsp:setProperty actions <jsp:getProperty> <jsp:getProperty name=”beanName” property=”propName” />
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 22 of 40
<jsp:setProperty> <jsp:setProperty name=”bean1” property=”*” /> -- all request parameters will be set in bean’s properties (with matching names) <jsp:setProperty name=”bean2” property=”user ” param=”username ” /> -- request parameter ‘username’ will be set to ‘user’ property of the bean <jsp:setProperty name=”bean2” property=”user ” /> -- request parameter ‘user’ will be set to ‘user’ property of the bean (since no param specified, it is assumed to have the same name as the property) <jsp:setProperty name=”bean2” property=”user ” value=”me” /> <jsp:setProperty name=”bean2” property=”user ” value=”<%=session.getAttribute(“user”) %>“ /> -- new value can be specified with an expression. If it’s an expression no conversion is performed, else standard conversion is performed. Note: value cannot be used in conjunction with param 10.2 Given JSP page attribute scopes: request, session, application, identify the equivalent servlet code. request - HTTPServletRequest session – HTTPServletRequest.getSession() : HTTPSession application – GenericServlet.getServletContext() or GenericServlet.getServletConfig().getServletContext() 10.3 Identify techniques that access a declared JavaBean component. A declared JavaBean can also be accessed using: (the name specified in the id attribute of <jsp:useBean>) Scriptlets Expressions Custom Tags Section 11: Designing and Developing JSPs Using Custom Tags 11.1 Identify properly formatted tag library declarations in the Web application deployment descriptor. taglib*,
<web-app> http://www.jspinsider.com/jspkit/javascript /WEB-INF/JavaScriptExampleTag.tld 11.2 Identify properly formatted taglib directives in a JSP page. <%@ taglib uri=”http://jakarta.apache.org/taglibs/datetime-1.0” prefix=”dt” %> - uri can be defined in web.xml or can be directly pointing to the TLD. - prefix is used in the jsp to reference the tag. ( local namespace) 11.3 Given a custom tag library, identify properly formatted custom tag usage in a JSP page. Uses include: • An empty custom tag - <msgBean:message/> • A custom tag with attributes - <msgBean:message attrName=”value” /> • A custom tag that surrounds other JSP code <msgBean:message> This is the title
• Nested custom tags Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 23 of 40
<msgBean:message> Section 12: Designing and Developing A Custom Tag Library 12.1 Identify the tag library descriptor element names that declare the following: • The name of the tag • The class of the tag handler • The type of content that the tag accepts • Any attributes of the tag username true <required>false String
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 - <required> • Whether or not the attribute's value can be dynamically specified - 12.3 Given a custom tag, identify the necessary value for the bodycontent TLD element for any of the following tag types: • Empty-tag - empty • Custom tag that surrounds other JSP code – JSP (default, even if there’s no body-content element) • Custom tag that surrounds content that is used only by the tag handler - tagdependent 12.4 Given a tag event method (doStartTag, doAfterBody, and doEndTag), identify the correct description of the methods trigger. doStart – Process the start tag for this instance doAfterBody – Process body (re)evaluation – repeat for iteration tag. doEndTag – Process the end tag for this instance. Used to clean up resources and add any closing tags to the output as necessary 12.5 Identify valid return values for the following methods: • doStartTag - Tag.EVAL_BODY_INCLUDE, BodyTag.EVAL_BODY_BUFFERED, Tag.SKIP_BODY Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 24 of 40
• • •
doAfterBody – IterationTag.EVAL_BODY_AGAIN, Tag.SKIP_BODY doEndTag – Tag.EVAL_PAGE, Tag.SKIP_PAGE PageContext.getOut - javax.servlet.jsp.JspWriter
12.6 Given a "BODY" or "PAGE" constant, identify a correct description of the constant's use in the following methods: • doStartTag • doAfterBody • doEndTag EVAL_BODY_AGAIN Request the reevaluation of some body. Returned from doAfterBody. For backward compatibility with JSP 1.1, the value is carefully selected to be the same as, now deprecated, BodyTag.EVAL_BODY_TAG. Defined in IterationTag. EVAL_BODY_TAG Deprecated now. Defined in BodyTag EVAL_BODY_BUFFERED Request the creation of new buffer, a BodyContent on which to evaluate the body of this tag. Returned from doStartTag when it implements BodyTag. This is an illegal return value for doStartTag when the class does not implement BodyTag. Defined in BodyTag. EVAL_BODY_INCLUDE Evaluate body into existing out stream. Valid return value for doStartTag. Defined in Tag. SKIP_BODY Skip body evaluation. Valid return value for doStartTag and doAfterBody. Defined in Tag. EVAL_PAGE Continue evaluating the page. Valid return value for doEndTag(). Defined in Tag. SKIP_PAGE Skip the rest of the page. Valid return value for doEndTag. Defined in Tag. EVAL_BODY_INCLUDE EVAL_BODY_BUFFERED EVAL_BODY_AGAIN SKIP_BODY EVAL_BODY_TAG EVAL_PAGE SKIP_PAGE
doStart All Body tag only All
doAfterBody
doEndTag
Iteration All deprecated All All
12.7 Identify the method in the custom tag handler that accesses: • A given JSP page's implicit variable • The JSP page's attributes A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the 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 error handling: forward(), include(), and handlePageException(). The methods related to attributes are: setAttribute(), getAttribute(), removeAttribute() – deals page scope Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 25 of 40
findAttribute(), - looks in all scopes int getAttributesScope() and getAttributeNamesInScope(int scope) Note: TagSupport implements IterationTag which extends Tag. BodyTagSupport implements BodyTag which extends IterationTag. getPreviousOut(), getBodyContent(), setBodyContent(), doInitBody() methods are defined in BodyTagSupport. 12.8 Identify methods that return an outer tag handler from within an inner tag handler. Tag Tag.getParent() Tag TagSupport.getParent() Tag TagSupport.findAncestorWithClass(Tag from, java.lang.Class class) (A static method) Section 13: Design Patterns 13.1 Given a scenario description with a list of issues, select the design pattern (Value Objects, MVC, Data Access Object, or Business Delegate) that would best solve those issues. 13.2 Match design patterns with statements describing potential benefits that accrue from the use of the pattern, for any of the following patterns: Value Objects , MVC , Data Access Object , Business Delegate Pattern Value Objects
MVC
Data Access Object
Business Delegate
Description/Benefit/Issues •Reduce network traffic by acting as a caching proxy of a remote object. •Total load on the remote object’s remote interface is decreased, because data represented by the Value Object are cached on the client by the Value Object instance. All accesses to the properties of the Value Objects are local, and so those accesses cause no remote method invocations. •Decreased latency can improve user response time. •Potential Liability - Stale data. Whenever a value object is backed by a volatile set of values (such as a stock's price and trading volume, for example) it should only be treated as a snapshot of those values. •Clarifies design by separating data modeling issues from data display and user interaction. •Allows the same data to be viewed in multiple ways and by multiple users. •Improves extensibility by simplifying impact analysis. •Improves maintainability by encapsulating application functions behind well-known APIs, and decreasing code replication (“copy-paste-and-hack”). •Enhances reusability by decoupling application functionality from presentation. •Makes applications easier to distribute, since MVC boundaries are natural distribution interface points. •Can be used to partition deployment and enable incremental updates. •Facilitates testability by forcing clear designation of responsibilities and functional consistency. •Enhances flexibility, because data model, user interaction, and data display can be made “pluggable”. •Greater deployment flexibility •Resource vendor independence •Resource implementation independence •Easier migration to CMP •Enhanced extensibility •Increased complexity because of a level of indirection •Reduced coupling, improved manageability. •Service exception translation •Simpler, uniform interface hiding the details. •Delegate may cache results – this may improve performance •Increased complexity because of a level of indirection Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 26 of 40
Front Component Façade Factory Singleton Template Method Bimodal Data Access Session Entity Façade
•Provides centralized dispatching of requests, e.g. via a controller servlet. •Enables centralized handling of security, navigation, and presentation formatting •Provides a layer between clients and subsystems of a complex system. •Shields clients from subsystem components, making the subsystems easier to use •Handles requests for object creation •A class which can have at most one instance •The key idea is that there is a basic algorithm we want to stay the same, but we want to let subclasses vary how they do the steps. The Template Method says to define the algorithm in the parent class, but implementations of the steps in the subclasses •Under certain conditions, allows designer to trade off data consistency for access efficiency. JDBC provides readonly, potentially dirty reads of lists of objects, bypassing the functionality, and the overhead, of Entity enterprise beans. At the same time, Entity enterprise beans can still be used for transactional access to enterprise data. Which mechanism to select depends on the requirements of the application operation •Being an instance of the Facade pattern, this pattern shares its applicability. In the context of J2EE application development, use the Session Facade pattern when you want to provide a simple interface to a complex subsystem of enterprise beans or when you want to reduce communication & dependencies b/w client objects and enterprise beans.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 27 of 40
Servlet API Interface / Class
Method
Description
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 28 of 40
init(ServletConfig) destroy() Servlet
service(ServletRequest, ServletResponse) ServletConfig getServletConfig() String getServletInfo String getInitParameter(String) Enumeration getInitParameterNames()
ServletConfig
ServletContext getServletContext() String getServletName()
String getInitParameter(String) Enumeration getInitParameterNames() Object getAttribute(String) setAttribute(String, Object) removeAttribute(String) Enumeration getAttributeNames() ServletContext
log(String) log(String, Throwable) ServletContext getContext(String uripath) String getRealPath(String path) java.net.URL getResource(String path)
Called by the servlet container to indicate to a servlet that the servlet is being placed into service. Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. Called by the servlet container to allow the servlet to respond to a request. Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. Returns information about the servlet, such as author, version, and copyright. Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters. Returns a reference to the ServletContext in which the caller is executing. Returns the name of this servlet instance. The name may be provided via server administration, assigned in the web application deployment descriptor, or for an unregistered (and thus unnamed) servlet instance it will be the servlet's class name. Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. Returns the servlet container attribute with the given name, or null if there is no attribute by that name. Binds an object to a given attribute name in this servlet context. Removes the attribute with the given name from the servlet context. Returns an Enumeration containing the attribute names available within this servlet context. Writes the specified message to a servlet log file, usually an event log. Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file. Returns a ServletContext object that corresponds to a specified URL on the server. The given path must be absolute (beginning with "/") and is interpreted based on the server's document root. Returns a String containing the real path for a given virtual path. Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 29 of 40
java.net.URL getResource(String path)
ServletContext
java.io.InputStream getResourceAsStream(String path) RequestDispatcher getRequestDispatcher(String path)
RequestDispatcher getNamedDispatcher(String name) Object getAttribute(String) setAttribute(String, Object) removeAttribute(String) Enumeration getAttributeNames()
String getParameter(String) String[] getParameterValues(String) ServletRequest
Enumeration getParameterNames() ServletInputStream getInputStream() BufferedReader getReader()
RequestDispatcher getRequestDispatcher(String path)
This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file. The resource content is returned directly, so be aware that requesting a .jsp page returns the JSP source code. Use a RequestDispatcher instead to include results of an execution. This method has a different purpose than java.lang.Class.getResource, which looks up resources based on a class loader. This method does not use class loaders. Returns the resource located at the named path as an InputStream object. Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher. Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. Stores an attribute in this request. Removes an attribute from this request. Returns an Enumeration containing the names of the attributes available to this request. This method returns an empty Enumeration if the request has no attributes available to it. Returns the value of a request parameter as a String, or null if the parameter does not exist. Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. Returns an Enumeration of String objects containing the names of the parameters contained in this request. Retrieves the body of the request as binary data using a ServletInputStream. Either this method or getReader() may be called to read the body, not both. Retrieves the body of the request as character data using a BufferedReader. The reader translates the character data according to the character encoding used on the body. Either this method or getInputStream() may be called to read the body, not both. 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 a request to the resource or to include the resource in a response. The resource can be dynamic or static.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 30 of 40
RequestDispatcher getRequestDispatcher(String path)
String getRemoteAddr() String getRemoteHost()
ServletRequest
String getServerName() int getServerPort() String getProtocol() String getScheme() boolean isSecure() String getContentType() int getContentLength() String getCharecterEncoding() setCharecterEncoding(String) ServletOutputStream getOutputStream()
PrintWriter getWriter()
ServletResponse setContentType(java.lang.String type)
setContentLength(int) boolean isCommitted()
The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher. The difference between this method and ServletContext’s method is that this method can take a relative path. Returns the Internet Protocol (IP) address of the client that sent the request. Returns the fully qualified name of the client that sent the request, or the IP address of the client if the name cannot be determined. Returns the host name of the server that received the request. Returns the port number on which this request was received. Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1. Returns the name of the scheme used to make this request, for example, http, https, or ftp. Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. Returns the MIME type of the body of the request, or null if the type is not known. Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. Returns the name of the character encoding used in the body of this request. Overrides the name of the character encoding used in the body of this request. Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both Returns a PrintWriter object that can send character text to the client. The character encoding used is the one specified in the charset= property of the setContentType method, which must be called before calling this method for the charset to take effect. Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream may be called to write the body, not both. Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html;charset=ISO-8859-4. If obtaining a PrintWriter, this method should be called first. Sets the length of the content body in the response. In HTTP servlets, this method sets the HTTP Content-Length header. Returns a boolean indicating if the response has been committed. A commited response has already had its status code and headers written.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 31 of 40
reset() int getBufferSize() setBufferSize(int) ServletResponse flushBuffer() resetBuffer() init() log(String) abstract class GenericServlet implements Servlet, ServletConfig, Serializable
log(String, Throwable) abstract service()
String getHeader(String)
Enumeration getHeaders(String)
Enumeration getHeaderNames() HttpServletRequest
int getIntHeader(String)
long getDateHeader(String)
Cookie getCookies() HttpSession getSession()
Clears any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an IllegalStateException. Returns the actual buffer size used for the response. If no buffering is used, this method returns 0. Sets the preferred buffer size for the body of the response. This method must be called before any response body content is written; if content has been written, this method throws an IllegalStateException. Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written. Clears the content of the underlying buffer in the response without clearing headers or status code. If the response has been committed, this method throws an IllegalStateException. A convenience method which can be overridden so that there's no need to call super.init(config). Writes the specified message to a servlet log file, prepended by the servlet's name. Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file, prepended by the servlet's name. Called by the servlet container to allow the servlet to respond to a request. This method is declared abstract so subclasses, such as HttpServlet, must override it. Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. The header name is case insensitive. You can use this method with any request header. Returns all the values of the specified request header as an Enumeration of String objects. If the request did not include any headers of the specified name, this method returns an empty Enumeration. The header name is case insensitive. You can use this method with any request header. Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration. Returns the value of the specified request header as an int. If the request does not have a header of the specified name, this method returns -1. If the header cannot be converted to an integer, this method throws a NumberFormatException. Returns the value of the specified request header as a long value that represents a Date object. Use this method with headers that contain dates, such as If-Modified-Since. If the request did not have a header of the specified name, this method returns -1. Returns an array containing all of the Cookie objects the client sent with this request, or null if no cookies sent. Returns the current session associated with this request, or if the request does not have a session, creates one.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 32 of 40
HttpSession getSession(boolean create)
String getRequestURI()
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. 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. requestURI = contextPath + servletPath + pathInfo
String getContextPath()
String getServletPath() String getPathInfo()
String getPathTranslated() String getQueryString() String getMethod() HttpServletRequest
String getAuthType()
String getRemoteUser() Principal getUserPrincipal()
boolean isUserInRole(String role)
String getRequestedSessionId()
boolean isRequestedSessionIdValid() boolean isRequestedSessionIdFromCookie() boolean isRequestedSessionIdFromURL()
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 "". Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. 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. This method returns null if there was no extra path information. Returns any extra path information after the servlet name but before the query string, and translates it to a real path. Returns the query string that is contained in the request URL after the path. Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Returns the name of the authentication scheme used to protect the servlet. All servlet containers support BASIC_AUTH, FORM_AUTH, and CLIENT_CERT_AUTH and may support DIGEST_AUTH. If the servlet is not authenticated null is returned. Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. Returns a java.security.Principal object containing the name of the current authenticated user. If the user has not been authenticated, the method returns null. Returns a boolean indicating whether the authenticated user is included in the specified logical "role". Roles and role membership can be defined using deployment descriptors. If the user has not been authenticated, the method returns false. Returns the session ID specified by the client. This may not be the same as the ID of the actual session in use. For example, if the request specified an old (expired) session ID and the server has started a new session, this method gets a new session with a new ID. If the request did not specify a session ID, this method returns null. Checks whether the requested session ID is still valid. Checks whether the requested session ID came in as a cookie. Checks whether the requested session ID came in as part of the request URL.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 33 of 40
addCookie(Cookie) addHeader(String name, String value) addIntHeader(String name, int value) addDateHeader(String name, long value) setHeader(String name, String value) setIntHeader(String name, int value) setDateHeader(String name, long value) setStatus(int sc)
sendError(int sc) sendError(int sc, java.lang.String msg)
HttpServletRespons e sendRedirect(java.lang.String location)
String encodeURL(java.lang.String url)
String encodeRedirectURL(String url)
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie. Add a response header with the given name and String value / integer value / date value respectively. These methods allow response headers to have multiple values. Set a response header with the given name and String value / integer value / date value respectively. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. 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 status codes SC_OK or SC_MOVED_TEMPORARILY). If there is an error, and the caller wishes to invoke an error-page defined in the web applicaion, the sendError method should be used instead. If this method is called after the response is committed, the call is ignored. Sends an error response to the client using the specified status clearing the buffer. The server defaults to creating the response to look like an HTML-formatted server error page, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter. If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to. Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root. If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to. Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 34 of 40
Object getAttribute(String) setAttribute(String, Object)
removeAttribute(String)
Enumeration getAttributeNames() HttpSession
String getId() long getCreationTime() long getLastAccessedTime() int getMaxInactiveInterval()
setMaxInactiveInterval(int) invalidate() isNew()
abstract class HttpServlet extends GenericServlet Eventhough this class is abstract it provides empty implementations of all methods. Typically servlets extending this class would override one of the doXXX methods.
public service(ServletRequest, ServletResponse) protected service(HttpServletRequest, HttpServletResponse) doGet(HttpServletRequest, HttpServletResponse) doPost(HttpServletRequest, HttpServletResponse) doPut(), doDelete(), doHead(), doTrace(), doOptions() long getLastModified()
Returns the object bound with the specified name in this session, or null if no object is bound under the name. Binds an object to a given attribute name in this session. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the new object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound. If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called. Removes the attribute with the given name from the session. After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueUnbound. Returns an Enumeration of String objects containing the names of all the objects bound to this session. Returns a string containing the unique identifier assigned to this session. Returns the time when this session was created Returns the last time the client sent a request associated with this session Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method. A negative time indicates the session should never timeout. Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout. Invalidates this session then unbinds any objects bound to it. Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request. Dispatches client requests to the protected service method. There's no need to override this method. Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. There's no need to override this method. Should be safe and idempotent (repeatable) Override to service GET requests. HEAD requests are also satisfied since doHead internally uses this method with a specialized response. Need not be safe or idempotent. Override to service POST requests. These methods are not common and service the corresponding requests. Returns the time the HttpServletRequest object was last modified
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 35 of 40
forward(ServletRequest, ServletResponse)
RequestDispatcher include(ServletRequest, ServletResponse)
SingleThreadModel
No methods
ServletContext Listener
contextInitialized(ServletContextEvent) contextDestroyed(ServletContextEvent)
ServletContext AttributeListener
HttpSession Listener
attributeAdded (ServletContextAttributeEvent) attributeRemoved (ServletContextAttributeEvent) attributeReplaced (ServletContextAttributeEvent) sessionCreated(HttpSessionEvent) sessionDestroyed(HttpSessionEvent)
HttpSession AttributeListener
HttpSession ActivationListener
attributeAdded (HttpSessionBindingEvent) attributeRemoved (HttpSessionBindingEvent) attributeReplaced (HttpSessionBindingEvent) sessionDidActivate(HttpSessionEvent) sessionWillPassivate(HttpSessionEvent)
HttpSession BindingListener
valueBound(HttpSessionBindingEvent) valueUnbound (HttpSessionBindingEvent)
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response. forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward. Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic serverside includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored. This is a ‘marker’ interface Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application. This listener interface can be implemented in order to get notifications of changes made to sessions within this web application.
Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener. 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 a result of a servlet programmer explicitly unbinding an attribute from a session, due to a session being invalidated, or die to a session timing out.
Deployment Descriptor DTD (web-app_2_3.dtd) Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 36 of 40
Legend: ? – Optional (0 or 1) * – Any number (0 - n) + – 1 or more (1 - n) No following character – Required (1) filter*, filter-mapping*, listener*, servlet*, load-on-startup?, run-as?, security-role-ref*)> servlet-mapping*, session-config?, mime-mapping*, welcome-file-list?, error-page*, taglib*, resource-env-ref*, resource-ref*, security-constraint*, auth-constraint?, user-data-constraint?)> NONE, INTEGRAL , or CONF IDENT IAL . login-config?, security-role*, env-entry*, ejb-ref*, ejb-local-ref*)>
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 37 of 40
Example 1
<web-app> A Simple Application <param-name>Webmaster <param-value>[email protected] <servlet> <servlet-name>catalog <servlet-class>com.mycorp.CatalogServlet <param-name>catalog <param-value>Spring <servlet-mapping> <servlet-name>catalog /catalog/* <session-config> <session-timeout>30 <mime-mapping> <extension>pdf <mime-type>application/pdf <welcome-file-list> <welcome-file>index.jsp <welcome-file>index.html <welcome-file>index.htm <error-page> <error-code>404 /404.html
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 38 of 40
Example 2
<web-app> A Secure Application <servlet> <servlet-name>catalog <servlet-class>com.mycorp.CatalogServlet <param-name>catalog <param-value>Spring <security-role-ref> MGR manager <servlet-mapping> <servlet-name>catalog /catalog/* <security-constraint> <web-resource-collection> <web-resource-name>SalesInfo /salesinfo/* GET POST manager <user-data-constraint> CONFIDENTIAL <security-role> manager
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 39 of 40
http://www.javaprogrammingworld.com One solution for all your certification needs.
Study Notes for Sun Certified Web Component Developer for J2EE Platform Page 40 of 40