Monday, June 15, 2009

SCWCD notes

After about 4-week part time study, I managed to pass the SCWCD(Sun certified web component developer) exam. I would not say the exam was difficult, but you do need to study the material thoroughly in order to pass it. My main reference is Head First Servlets and JSP book, the book is written with a goal of passing SCWCD exam and it has been appreciated by a number of successful candidates. I would strongly suggest this book for anyone who intends to take the SCWCD exam.

After reading the book, I tried the exam at the end of the book and a few other mock exams on the internet, the quality and difficualty of the exams varies but I found the one comes with the book reflects the real exam well, only a fraction more difficault.

During the period of my study, I made a note of all the key points in the book and some catchy stuff in the mock exam. Now it's the time for me to share this note with you guys, I hope it will help with your preparation:

The servlet lifecycle is simple; there’s only one main state—initialized. If the servlet isn’t initialized, then it’s either being initialized (running its constructor or init()method), being destroyed (running its destroy() method), or it simply does not exist.

The Container calls init() on the servlet instance after the servlet instance is created.

You might hear people say things like, “Each instance of the servlet...” but that’s just wrong. There aren’t multiple instances of any servlet class.

The Container runs multiple threads to process multiple requests to a single servlet. the servletservlet

getRemotePort() means “get the client’s port

println() to a PrintWriter
write() to an ServletOutputStream
response. getOutputStream()
response. getWriter()

The sub-element is the ONLY required sub-element of the element.

Only Request attributes and local variables are thread-safe!

Don’t forget that the encodeURL() method is something you call on your HttpServletResponse

In the DD, using the element, only minutes can be specified, using HttpSession’s setMaxInactiveInterval() only seconds can be specified.

Three different JSP element types:

  • Scriptlet: <% %>
  • Directive: <%@ %>
  • Expression: <%= %> e.g. <%= Counter.getCount() %> Expressions become the argument to an out.print(). - No semicolon
  • Declaration: <%! %>
<% = 42*20 %> is WRONG! The arithmetic is fine, but there’s a space between the % and the =. It can’t be <% =, it must be <%= . If there’s a conflict between the setting in the DD and , the isELIgnored page directive always wins!

You can only disable scripting language through the DD.

Template Text - Plain old HTML.

You can override jspInit(), jspDestroy(). But you cannot override _jspService()!!!!

${person.name}
If the expression has a variable followed by a dot, the left-hand variable MUST be a Map or a bean.
The thing to the right of the dot MUST be a Map key or a bean property.

There is NO "=" in EL, only "=="

EL is null-friendly. It handles unknown or null values so that the page still displays, even if it can’t find an attribute/property/key with the name in the expression. In arithmetic, EL treats the null value as “zero”. In logical expressions, EL treats the null value as “false”.

For custom tags, default value is "false".

Using the getParent() method,a Classic tag can access Classic tag parents, and a Simple tag can access either a Classic or Simple parent.

A user can’t be authorized until he’s been authenticated.

NO is the opposite of an EMPTY !

The existence of an empty element overrides all other elements that refer to that resource, precluding access.

This web.xml file MUST be in WEB-INF

RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
view.forward(request, response);

If you don’t put method=“POST” into your form, the default is an HTTP GET request.
Every request to a servlet runs in a separate thread! There is only one instance of any particular servlet class.

getServletContext().getInitParameter(“foo”);
getServletConfig().getInitParameter(“foo”);
is used for servlet init parameters, not context init parameters. You find ONLY inside a element.

ServletContext.getInitParameterNames() or ServletContext.getInitParameter(String)

The servlet to which a request is forwarded may access the original query string by calling getAttribute(“javax.servlet.forward.query_string”) on the ServletRequest.

Depending on the class whose method creates a RequestDispatcher, the path to the resource to be forwarded to will change.

If your servlet uses an Redirect(RequestDispatcher.forward), it can never send its own response.

if you don’t explicitly encode your URLs, and the client won’t accept cookies, you don’t get to use sessions. If you do encode your URLs, the Container will first attempt to use cookies for session management, and fall back to URL rewriting only if the cookie approach fails.

You do NOT configure session binding listeners in the DD.

HttpSessionListener and HttpSessionActivationListener must be registered in the DD, since they’re related to the session itself, rather than an individual attribute placed in the session.
SSL has a built-in mechanism that a servlet container could use to obtain data used to define a session.

If there’s a conflict between the setting in the DD and the isELIgnored page directive attribute, the directive always wins!

JSPs turn into plain old servlets, so they have access to the plain old ServletConfig and ServletContext objects... and it’s just a little early in the lifecycle to be talking about requests and responses.

exceptin and application are valid JSP implicit variables.

You can only disable scripting via the DD by using the element.

Automatic String-to-primitive conversion does NOT work if you use scripting!! It fails even if an expression is INSIDE the tag.

Music is: ${musicMap[Ambient]}
Find an attribute named “Ambient”. Use the VALUE of that attribute as the key into the Map, or return null.

You can’t do ${foo.1}

Use requestScope to get request ATTRIBUTES, not request PROPERTIES.
${requestScope.person.name}

For request properties, you need to go through pageContext.
${pageContext.request.method}

The EL initParam is NOT for params configured using ! But it is for context params

mainEmail
likewecare@wickedlysmart.com

email is: ${ initParam.mainEmail}

The include directive happens at translation time <%@ include fi le=”Header.jsp”%>
happens at runtime

${header.User-Agent} is equivalent to ${header[“User-Agent”]} WRONG! - because of the dash in User-Agent. Only header[“User-Agent”] will work.
${cookies.foo} is WRONG because the variable is “cookie”.

Null values are rendered as blank text

This flavor of (with its two variations—with and without a body) works for only two things: bean properties and Map values. That’s it. You can’t use it to add things to lists or arrays.

You can never have BOTH the “var” and “target” attributes in a .

If there’s no in tags attribute configuration, the default value is false.

The tag is the ONLY thing you can put between the opening and closing tags of a tag with a of empty! It’s just an alternate way to put the attributes in, but tags don’t count as “body content”.

Four places the Container looks for TLDs
  • Directly inside WEB-INF
  • Directly inside a sub-directory of WEB-INF
  • Inside the META-INF directory inside a JAR file that’s inside WEB-INF/lib
  • Inside a sub-directory of META-INF inside a JAR file that’s inside WEB-INF/lib
Where the Container looks for Tag Files:
  • Directly inside WEB-INF/tags
  • Inside a sub-directory of WEB-INF/tags
  • Inside the META-INF/tags directory inside a JAR file that’s inside WEB-INF/lib
  • Inside a sub-directory of META-INF/tags inside a JAR file that’s inside WEB-INF/lib
${sessionScope.customer.address.city = param.city} is WRONG because EL does not permit assignment.

Scripting elements, remember, are scriptlets (<% ... %>), scriptlet expressions (<%= ... %>), and declarations (<%! ... %>).

Tag File bodies are never allowed to have scripting!


If the tag file is deployed in a JAR, there MUST be a TLD for the tag file.

The setParent() method is called only when the tag is invoked from WITHIN another tag. Since this tag was not nested, setParent() is NOT called.

SkipPageException stops only the page that directly invoked the tag

If the page that invokes the tag was included from some other page, only the page that invokes the tag stops processing! The original page that did the include keeps going after the SkipPageException.

Tag Files implement tag functionality using a page, while tag handlers implement tag functionality using a Java tag handler class.

When you implement BodyTag (by extending BodyTagSupport), you get two more lifecyclesetBodyContent() and doInitBody(). You also get one new return value for doStartTag(), EVAL_BODY_BUFFERED.

Using the getParent() method, a Classic tag can access Classic tag parents, and a Simple tag can access either a Classic or Simple parent.

pageContext variable is only available to Classic tags.

findAncestorWithClass requires two parameters: A Tag and a Class.

doAfterBody() is only called when doStartTag() returns EVAL_BODY_INCLUDE.

the fragment is invoked by the doTag implementation, NOT before the doTag is called.

pageContext.getAttribute(String) only checks the page scope.

a Simple tag may include a Complex tag in the body as long as that tag contains no scripting code.
simple tags cannot have a body that includes a JSP expression tag.

The “classes” directory must NOT be under “lib”, it must be under “WEB-INF”.

Nothing under META-INF or WEB-INF is directly accessible.

The must NOT be a primitive!

You can configure a mapping between an extension and a mime type in the DD.Don’t include the “.” in the extension!

DD elements are used to declare initialization parameters for a specific servlet.
Constraints are not at the RESOURCE level. Constraints are at the HTTP REQUEST level.
1 When combining individual role names, all of the role names listed will be allowed.
2 A role name of “ * “ combines with anything else to allow access to everybody.
3 An empty tag combines with anything else to allow access to nobody! In other words, an empty is always the fi nal word[[BR]] 4 If one of the

elements has no element, it combines with anything else to allow access to everybody.

IMPORTANT: The Container’s rules for ordering filters: When more than one filter is mapped to a given resource, the Container uses the following rules: 1) ALL filters with matching URL patterns are located first. This is NOT the same as the URL mapping rules the Container uses to choose the “winner” when a client makes a request for a resource, because ALL filters that match will be placed in the chain!! Filters with matching URL patterns are placed in the chain in the order in which they are declared in the DD. 2) Once all filters with matching URLs are placed in the chain, the Container does the same thing with filters that have a matching in the DD.

Request/Response wrappers implement the Decorator pattern.

SimpleTag extends JspTag. ClassicTag extends Tag.

getRequestDispatcher() method of ServletContext interface expect a URL starts with "/" i.e. absolute url.

Servlet attribute can be set in these scopse: request, session, and context

HttpSessionBindingEvent can access the ServletContext via getSession().getServletContext()

ServletRequest.getRequestDispatcher can take a relative URL.
ServletContext.getRequestDispatcher cannot

Use of the methods in the HttpSessionActivationListener does not require configuration in the deployment descriptor
The HttpSessionBindingListener does not need to be configured in the deployment descriptor.

BASIC authentication is easy to set up but the forms are ugly and there is no encryption security

Digest security is not considered strong and Digest in not supported by all browsers. DIGEST authentication is defined within the HTTP protocol, though it is not widely used as it is not supported by all browsers.

Form authentication allows better looking login forms than BASIC, but still has no security. To use FORM authentication the form is required trigger an action called j_security_check and the userid and password must have the names j_username and j_pssword. FORM authentication is defined within the J2EE spec

Client Cert authentication has good security, but it is complex to implement and maintain
<% @include file=”menu.jsp” %>

The include directive happens at translation time and the include standard action happens at runtime

JSP comments are the equivalent of Java comments in that they are discarded by the parsing process and do not appear in the text that is sent to the browser.
The jspInit method is called by the container once and only once for a servlet instance.
JSP implicit objects:
methods—
  • request,
  • response,
  • out,
  • session,
  • config, an instance of javax.servlet.ServletConfig
  • application, an instance of javax.servlet.ServletContext.
  • page, The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method.
  • pageContext, and
  • exception.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations.

The following words are reserved and cannot be used as a prefix for a taglib jsp:, jspx:, java:, javax:, servlet:, sun:, and sunw

The
  • -request getRequest
  • -response getResponse
  • -out getOut
  • -session getSession
  • -config getServletConfig
  • -application getServletContext
  • -page getPage
  • -exception getException
Because the getParent and findAncestorWithClass methods have a return type of jspTag you generally need to cast the returned value back to the type of the custom tag you have implemented.

You need to memorize the method return values for the classic tag methods
  • -The doStart method: SKIP_BODY or EVAL_BODY_INCLDE
  • -The doAfterBody method: IterationTag.EVAL_BODY_AGAIN or Tag.SKIP_BODY
  • -The doEndTag method: SKIP_PAGE or EVAL_PAGE
The BodyTagSupport class adds the getBodyContent and doInitBody methods and the EVAL_BODY_INCLUDE constant.

jspTag Tag getParent()
jspTag Tag findAncestorWithClass(Tag from, java.lang.Class klass)
getParent and findAncestoryWith class are available to both simple and classic tags
The findAncestorWithClass method allows an arbitrary ancestor to be retrieved rather than just the enclosing parent.

Simple tags cannot have scriptlet code (JSP) within the body. Because of this the tag of the TLD can only have values of empty or scriptless.
public void setDynamicAttribute(String uri, String localName, Object value){}

Using a tag file that is not wrapped in a jar is very convenient because it needs no Tag Library

Descriptor File (tld). However when wrapped in a jar (Java archive) tag files require a tld.

However when wrapped in a jar (Java archive) tag files require a tld. A tag file is similar but not identical to a regular tld. Instead of matching tags to handlers it matches the names of tag files to their paths, and so it uses the new element instead of the element of a standard taglib tld.

  • The implicit objects available in JSP pages are: request, response, pageContext, session, application, out, config, page, exception (in error pages only).
  • The implicit objects available in EL pages are: pageContext, pageScope, requestScope, sessionScope, applicationScope, param, paramValues, header, headerValues, cookie, initParam.
  • The implicit objects available in Tag file are: request, response, out, session, application,config,jspContext

This is similar, but not identical to the implicit objects available to standard JSP pages. JSP pages have a page object, pageContext object and can have an exception object.

a war file must contain a directory called META-INF

Unlike the TagSupport class the SimpleTagSupport class does not have its own pageContext field. The getJspContext can be used to get the the page context passed in by the container via setJspContext.

The jspInit() method may be overriden within a JSP page

If scripting is disabled in the deployment descriptor a compilation error will be generated if you try to compile a page with scripting elements

The taglib directive can use either the tagdir or the uri attribute to locate the tld file

A resource that is included using the RequestDispatcher.include method will share attributes of the originating resource.

The beanName attribute of useBean is only used with serialized beans

The body of a call to a tagfile cannot contain scripting. Thus by default a tag file body is scriptless.

The scope of an attribute can be HttpSession,ServletRequest,or ServletContext.

FORM based authentication is a Java (JSP/Servlet) specific technology. Not defined in HTTP specification.

If your servlet uses an RD, it can never send its own response The page attribute of the