Java - SCWCD

From Guides

Jump to: navigation, search

Contents

Introduction

This document is meant as a quick-ref for people wanting to do the 310-081 exam. I cannot be held responsible for you failing the exam by using this quick-ref. It is merely meant as a quick refresher.

I recommend you see the exam objectives on the sun's java site. Next to that I recommend you read the servlet api's and get a firm grasp on the most commonly used methods. Memorize them well!

The api's can be found here: Servlet API's

!!! NOTE: After passing the exam I don't have the willpower anymore to finish this document. I hope you will understand ;) !!!

URL's

URL's can be separated into several parts.

Example URL: http://localhost:8080/yourapp/ServletName/pathinfo?query=true&query2=false

Code:

System.out.println("URL:          " + request.getRequestURL() );
System.out.println("URI:          " + request.getRequestURI() );
System.out.println("Context Path: " + request.getContextPath() );
System.out.println("Servlet Path: " + request.getServletPath() );
System.out.println("Protocol:     " + request.getProtocol() );
System.out.println("Server     :  " + request.getServerName() );
System.out.println("Server Port:  " + request.getServerPort() );
System.out.println("Path Info   : " + request.getPathInfo() );
System.out.println("Query String: " + request.getQueryString() );

Output:

URL:          http://localhost:8080/yourapp/ServletName/pathinfo
URI:          /yourapp/ServletName
Context Path: /yourapp
Servlet Path: /ServletName
Protocol:     HTTP/1.1
Server     :  localhost
Server Port:  8080
Path Info   : /pathinfo
Query String: query=true&query2=false

Servlet Context

Adding params to web.xml xml-path: web-app:

<context-param>
	<description>A simple context parameter</description>
	<param-name>context_param</param-name>
	<param-value>Context Param Value</param-value>
</context-param>

Retrieving the value from java:

ServletContext sc = getServletContext(); //GenericServlet.getServletContext();
String value = sc.getInitParameter("context_param"); //Returns null value if not found

Iterating all values:

ServletContext sc = getServletcontext();
Enumeration e = sc.getInitParameterNames(); //Returns enumeration with 0 elements if there are no values


Attributes and Parameters

There is a distinct difference between attributes and parameters. Parameters are read only. Attributes however can be used to store or overwrite values.

Attribute Methods per scope
Request Scope Session Scope Context Scope
public void setAttribute(String name, Object value) If value is null the value is removed Same as request scope. Throws IllegalStateException if invoked when the session is invalid. Same as request scope.
public Object getAttribute(String name) Returns null if key is not found Same as request scope. Throws IllegalStateException if invoked when the session is invalid. Same as request scope.
public Enumeration getAttributeNames() Returns empty Enumeration if there are no values. Same as request scope. Throws IllegalStateException if invoked when the session is invalid. Some mandatory values are supplied. Therefore the Enumeration should not be empty.
public void removeAttribute(String name) Removes the named attribute. Same as request scope. Throws IllegalStateException if invoked when the session is invalid. Same as request scope.


Sessions

I recommend you read and learn the API calls you can make on this object: HttpSession

There are two methods to obtain a session object:

HttpSession session = HttpServletRequest.getSession();
session = HttpServletRequest.getSession(boolean createSession);

Distributable

To allow sessions to migrate from the same web application to another jvm you can use the <distributable/> tag in your web.xml file.

Session Death

A session can be ended in several ways.
  • Using web.xml
    <web-app>
        <session-config>
            <!-- Timeout in minutes, 0 or negative = never timeout -->
            <session-timeout>60</session-timeout>
        </session-config>
    </web-app>
    
  • HttpSession.invalidate();
  • Using HttpSession.setMaxInactiveInterval(int seconds);
    HttpSession.setMaxInactiveInterval(0); //Immediate expiration of session.
    HttpSession.setMaxInactiveInterval(-1); //Negative values should never expire
    

Session Management

There are two ways to use session management use either:
  • Cookies
  • URL Rewriting
The preferred way is by using cookies. The standard name for session information on a J2EE web application is JSESSIONID.
To be able to know where a session id came from you have two options:
HttpServletRequest.isRequestedSessionIdFromCookie();
HttpServletRequest.isRequestedSessionIdFromURL();
These properties could return false for both occassions when:
  • U are using a SSL session
  • A session is new

URL Rewriting

To make your application more robust you should use the HttpServletResponse.encodeURL(); method. So that when cookies are disabled you can encode the URL to write the jsessionid to the URL. When redirecting you can use the HttpServletResponse.encodeRedirectURL();

Request Object

I recommend that you learn this API specification on this object by heart. Also try to remember which methods are inherited from any superclass. (ServletRequest class). HttpServletRequest

Response Object

I recommend that you learn this API specification on this object by heart. Also try to remember which methods are inherited from any superclass. (ServletResponse class). HttpServletResponse

Context Object

Multithreading

Thread Safety
Object/Variable Type Threadsafe? Comments
Request Object Yes All calls on this object are threadsafe
Response Object Yes All calls on this object are threadsafe
Session Attributes Officialy Not Threadsafe Officialy not threadsafe though for most common web applications thread safety can be assumed.

Q: Why is that? A: Because one client could have multiple requests running at the same session object.

Context Attributes No Context Attributes are created once and after that accessible from multiple threads
Local Variables Yes Declared within methods
Instance Variables No Might be accessed by other threads, Instance Variables are created when creating an instance of an object.
Class Variables No Might be accessed by other threads, Class Variables are created once (example: static variables).

RequestDispatcher

Obtaining a RequestDispatcher

ServletRequest.getRequestDispatcher(java.lang.String);
ServletContext.getRequestDispatcher(java.lang.String);
ServletContext.getNamedDispatcher(java.lang.String);
ServletRequest.getRequestDispatcher
The given String value represents the target which should be called. You can use a forward slash ("/") at the start of a string to refer to the context root. You could also use relative paths. Then the current path is used to find the requested path.
ServletContext.getRequestDispatcher
Only paths starting with a forward slash ("/") are allowed. Not starting the path with a forward slash will throw a runtime exception (IllegalArgumentException).
ServletContext.getNamedDispatcher
Uses the web.xml to locate the servlet with the given name. (<servlet-name>)
!!!When no valid RequestDispatcher is found for the given path a null value is returned.!!!

Forwarding

RequestDispatcher.forward();
When forwarding a request the normal flow of a servlet is stopped. Any data you've written to the response is lost. The response will come directly from the called page in the RequestDispatcher.
After the dispatcher returns the normal flow is returned, you cannot however write output to the outputstream of the response. It will be ignored.
Differences with using forward instead of ServletRequest.sendRedirect() is that the sendRedirect method will create a complete new request.
When trying to forward a response which has already been commited you will get an IllegalStateException to be thrown.

Including

RequestDispatcher.include();
Same as forward only now output written is retained.

Retrieving Original Attributes

Several request attributes are available in the forwarded request object to get info on the originally called servlet.
  • javax.servlet.forward.request_uri = getRequestURI()
  • javax.servlet.forward.context_path = getContextPath()
  • javax.servlet.forward.servlet_path = getServletPath()
  • javax.servlet.forward.path_info = getPathInfo()
  • javax.servlet.forward.query_string = getQueryString()

Filters

web.xml xml-path: web-app

<!-- Creating the filter -->
<filter>
        <filter-name>Your Filter</filter-name>
        <filter-class>YourFilter</filter-class>
</filter>

<!-- Which servlet needs filtering? -->
<filter-mapping>
        <filter-name>YourFilter</filter-name>
        <servlet-name>YourServlet</servlet-name>
</filter-mapping>

<!-- Which url needs filtering? -->
<filter-mapping>
        <filter-name>YourFilter</filter-name>
        <url-pattern>/</url-pattern>
</filter-mapping>

Listeners

There are several listeners (interfaces) available:

  • ServletRequestListener
  • ServletContextListener
  • SerlvetRequestAttributeListener
  • ServletContextAttributeListener

All these listeners need to be registered as listeners in the web.xml.

Example, xml-path: web-app

<listener>
    <listener-class>your.listener.YourListenerClass</listener-class>
</listener>

ServletRequestListener

This class will respond to the life and death of requests.
Uses a ServletRequestEvent object which you can use to get the ServletContext or ServletRequest object.
Has two methods available:
public void requestInitialized(ServletRequestEvent event);
public void requestDestroyed(ServletRequestEvent event);

ServletContextListener

This class will respond to the life and death of the application context.
It uses a ServletContextEvent which you can use to retrieve the ServletContext object from.
It has two methods:
public void contextInitialized(ServletContextEvent event);
public void contextDestroyed(ServletContextEvent event);

ServletRequestAttributeListener

This class listens to the changes of attributes attached to a request object.
Uses ServletRequestAttributeEvent objects which extend the ServletRequestEvent to be able to retrieve the ServletContext or ServletRequest objects.
Methods:
public void attributeAdded(ServletRequestAttributeEvent srae);
srae.getValue(); //Returns Object that was added with setAttribute(); call.

public void attributeRemoved(ServletRequestAttributeEvent srae);
srae.getValue(); //Returns Object that was removed with setAttribute(); call.

public void attributeReplaced(ServletRequestAttributeEvent srae);
String name = srae.getName();
srae.getValue(); //Returns old value that was replaced.
srae.getServletRequest().getAttribute(name); //Returns new value;

ServletContextAttributeListener

This class listens to the changes of attributes attached to the application context.
Basically the same as the ServletRequestAttributeListener only now there is listened to the application context.

Session Listeners

This is one has several other listeners under it so it is import to memorize this one well.
HttpSessionListener
Methods:
public void sessionCreated(HttpSessionEvent event);
public void sessionDestroyed(HttpSessionEvent event);
HttpSessionAttributeListener
Methods:
public void attributeAdded(HttpSessionBindingEvent event);
public void attributeRemoved(HttpSessionBindingEvent event);
public void attributeReplaced(HttpSessionBindingEvent event);
HttpSessionBindingListener
This Listener is called when you have an object which implements the interface HttpSessionBindingListener and this object is bound or unbound to a Session.
Note: There is no need to add these to the deployment descriptor (web.xml)
Note2: These calls are made before any HttpSessionAttributeListener methods.
Methods:
public void valueBound(HttpSessionBindingEvent event);
public void valueUnbound(HttpSessionBindingEvent event);
HttpSessionActivationListener
This Listener is called when you have an object which is notified when a session gets distributed. (From one JVM to another for example)
Note: There is no need to add these to the deployment descriptor (web.xml)
Methods:
public void sessionDidActivate(HttpSessionEvent event);
public void sessionWillPassivate(HttpSessionEvent event);

Security

Security Constraint

Example, (xml-path: web-app):
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Admin Panel</web-resource-name>
        <url-pattern>/admin</url-pattern>
        <!-- Which http methods? PUT, DELETE, GET, POST, ETC -->
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>administrator</role-name>
    </auth-constraint>
</security-constraint>
User Data Constraint
you could also add a user data constraint to ensure proper handling of user data.
Example, (xml-path: web-app/security-constraint):
<user-data-constraint>
    <!-- Possible Values: NONE, INTEGRAL (uses checksums), CONFIDENTIAL (uses encryption) -->
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>

Login Config

Example, (xml-path: web-app):
<login-config>
    <!-- BASIC, DIGEST, FORM, CLIENT-CERT -->
    <auth-method>FORM</auth-method>
    <!-- This piece only needed when using FORM authentication -->
    <form-login-config>
        <form-login-page>/login.html</form-login-page>
        <form-error-page>/error.html</form-error-page>
    </form-login-config>
</login-config>
And a working form for the FORM authentication:
<html>
    <head>
        <title>Login Form</title>
    </head>
    <body>
        <form action="j_security_check" method="POST">
            <br/>Name: <input type="text" name="j_username"/>
            <br/>Password: <input type="password" name="j_password"/>
            <br/><input type="submit" value="Log In"/>
        </form>
    </body>
</html>

JSP

JSP Elements

Expressions
Expressions will output java code directly to the page. No semicolon is needed.
<%= java.util.Date() %>
Scriptlets
Scriptlets allow you to incorporate a block of java code.
<%
  int i = 0;
  i = 3;
  if( i > 3 ){
    doSomething();
  }
%>
Declarations
Declarations will allow you to create code that should be placed outside the compiled _jspService(); method in your jsp. If you for example want to create a function you can use a declaration.
<%!
  private int getRandomNumber(){
    return (int) Math.random();
  }
%>

JSP Directives

Note: Directives are only translated once: During the initial translation of the jsp page.

Page Directive
Import
You can include a page by using the following marking anywhere in your jsp:
<%@ page import="java.util*,java.lang.*" %>
Session
Determine if a session object is available
<%@ page session="true" %>
Content Type
You can define the MIME type of the jsp with this variable.
<%@ page contentType="image/gif" %>
Ignore EL
You can ignore the Expression Language by using this parameter.
<%@ page isELIgnored="true" %>
There are several other possibilities which I will list in short here:
language, extends, buffer, autoFlush, isThreadSafe, info, errorPage and isErrorPage
Include Directive
File
This one can be used to include another file in the current jsp page.
<%@ include file="another/file.html" %>
Taglib Directive
Used to import a tag library. Required attributes: prefix and uri.
<%@ taglib prefix="yourtags" uri="http://www.yourtags.com/taglibs/yourtags" %>

Implicit Objects

Several basic objects are available to you in a JSP page.
These are them:
  • request (javax.servlet.http.HttpServletRequest)
  • response (javax.servlet.http.HttpServletResponse)
  • out (javax.servlet.jsp.JspWriter)
  • session (javax.servlet.http.HttpSession)
  • config (javax.servlet.ServletConfig)
  • application (javax.servlet.ServletContext)
  • page (java.lang.Object)
  • pageContext (javax.servlet.jsp.PageContext)
  • exception (java.lang.Throwable)

JSTL

Possible tags:

  • <c:out>
    <c:out value=${user.name} escapeXml="true">Default value if value evaluates to null</c:out>
    
  • <c:set>
    <c:set value="${example.value}" var="yourVar"/>
    
    <c:set value="newValue" target="${your.bean.target}" property="propertyName" scope="session"/>
    
  • <c:remove>
    <c:remove var="yourVar" scope="session"/>
    
  • <c:catch>
    <c:catch var="exceptionVar"/>
    
  • <c:if>
    <c:if test="${object.property.evaluatesToTrue}">
        ... do this
    </c:if>
    
    <c:if test="3 gt 2">
        ... do this
    </c:if>
    
    <c:if test="true" var="putResultInThisVarForLaterUse" scope="session">
        ... do this
    </c:if>
    
  • <c:choose>
  • <c:when>
  • <c:otherwise>
    <c:choose>
        <c:when test="3">
            ... do this
        </c:when>
        <c:otherwise>
            ... do this
        </c:otherwise>
    </c:choose>
    
  • <c:forEach>
    <c:forEach var="temp" items="${listOfVars}">
        <c:out value="${temp.value}"/>
    </c:forEach>
    
    <c:forEach begin="0" end="5" step="1">
        <c:out value="simpleValue"/>
    </c:forEach>
    
  • <c:forTokens>
    <c:forTokens items="${stringWithDelimiters}" delims="," var="temp">
        <c:out value="${temp.value}">
    </c:forTokens>
    
  • <c:import>
    <c:import url="http://external.url/index.html" var="importedPage" scope="page"/>
    <c:out value="${importedPage}"/>
    
  • <c:url>
    <c:url value="/jsp/page.jsp" context="/context" var="temp"/>
    <a href="${temp}">Link</a>
    
  • <c:redirect>
    <c:redirect url="http://redirected.url/index.html"/>
    
  • <c:param>
    <!-- Use in conjunction with import, url or redirect -->
    <c:param name="nameOfProperty" value="valueOfProperty"/>
    
Personal tools
Google Ads