Online Mind Mapping and Brainstorming

Create your own awesome maps

Online Mind Mapping and Brainstorming

Even on the go

with our free apps for iPhone, iPad and Android

Get Started

Already have an account? Log In

Head First Servlets and JSP by Mind Map: Head First Servlets and JSP
5.0 stars - 3 reviews range from 0 to 5

Head First Servlets and JSP

Chap 4. Request and Response


Runs multiples threads to process multiple requests to a single servlet

Create request and response objects

Servlet's life

1. Load class

2. Instantiate servlet (constructor runs)

3. init()

4. Service()

5. destroy()

Http Methods










No side effects


String param = request.getParameter("parameter"); request.getParameterValues("size")[0];

String client = request.getHeader("User-Agent"); request.getIntHeader("foo");

Cookie[] cookies = request.getCookies();

HttpSession session = request.getSession();

String method = request.getMethod();

ServletInputStream input = request.getInputSream();



PrintWriter writer = response.getWriter(); writer.println("some text and HTML");

ServletOutputStream out = response.getOutputStream(); out.write(aByteArray);

response.setHeader("foo", "bar"); response.setIntHeader("TheAnswer", 42);

response.addHeader("foo", "bar");




RequestDispatcher view = request.getRequestDispatcher("foo.jsp"); view.forward(request,response);


Methods, getAttribute(String), getContentLenght(), getinputStream(), getLocalPort(), getRemotePort(), getServerPort(), getParameter(String), getParameterValues(String), getParameterNames(), more..

father of, javax.servlet.http.HttpServletRequest, Methods, getContextPath(), getCookies(), getHeader(String), getIntHeader(String), getMethod(), getQueryString(), getSession(), more...


Methods, getBufferSize(), setContentType(), getOutputStream(), getWriter(), setContentLength(), more..

father of, javax.servlet.http.HttpServletResponse, Methods, addCookie(), addHeader(), encodeURL(), sendError(), setStatus(), sendRedirect(), more..

Chap 5. Attributes and Listeners

Context init Parameters

One per web app

<web-app>   <context-param>     <param-name>foo</..     <param-value>bar</...


Available to any servlet and JSP part of the web app

Servlet init Parameters

One per servlet

<servlet>   <servlet-name>     <init-param>       <param-name>foo</..       <param-value>bar</...


Available only to the servlet for which <init-param> was configured


getInitParameter(String) : String

getInitParameterNames() : String[]

getAttribute(String) : String

getAttributesName() : String[]

setAttributes(String, Object) : void

removeAttribute(String) : void

getRequestDispatcher(String) : RequestDispatcher


<listener>   <listener-class>     com.some.foor.Listener   </..

the AttributeEvent.getValue, holds the replaced or removed value

Types, javax.servlet.ServletContextListener : ServletContextEvent, contextInitialized, contextDestroyed, javax.servlet.ServletRequestListener : ServletRequestEvent, requestInitialized, requestDestroyed, javax.servlet.ServletContextAttributeListener : ServletContextAttributeEvent, attributeAdded, attributeRemoved, attributeReplaced, javax.servlet.ServletRequestAttributeListener : ServletRequestAttributeEvent, attributeAdded, attributeRemoved, attributeReplaced, javax.servlet.http.HttpSessionAttributeListener : HttpSessionBindingEvent, attributeAdded, attributeRemoved, attributeReplaced, javax.servlet.http.HttpSessionListener : HttpSessionEvent, sessionCreated, sessionDestroyed, javax.servlet.http.HttpSessionBindingListener : HttpSessionBindingEvent, valueBound, valueUnbound, javax.servlet.http.HttpSessionActivationListener : HttpSessionEvent, sessionDidActive, sessionWillPassivate


Attributes are not Thread safe

Types, Application/context, Session, Request

setAttribute(String name, Object value)

getAtrribute(String) : Object

removeAttribute(String) : void

getAttributeNames() : Enumeration


Types, Application/context init parameters, Request Paratemers, Servlet Iinit parameters

You CANNOT set Application and Servlet init parameters, they're set in the DD

getInitParameter(String) : String


Methods, forward(ServletRequest, ServletResponse), include(ServletRequest, ServletResponse)

RequestDispatcher view = request.getREquestDispatcher("result.jsp");

RequestDispatcher view = getServletContext().getRequestDispatcher("/result.jsp);

a flush often lead to an illegalStateException

getAttribute("javax.servlet.forward.query_string"); obtain the query string for the original access

if your servlet use an RD, it can never send its own response.

Chap 6. Session Managment

URL rewriting

Adds the session ID to the end of all URLs in the HTML that you write to the response

Is used to pass over the session ID when cookies are not supported but you need to explicitily encode all of the URLs you write

There's no way to get automatic URL rewriting with your static pages, so if you depend on sessions, you must use dynamically-generated pages


You get this obj using req,getSession, you not use new HttpSession().

getAttribute(String) : Object

getCreationTime() : long

getId() : String

getLastAcessedTime() : long

getMaxInactiveInterval(): int

getServletContext() : ServletContext


isNew(): boolean


setAttribute(String, Object)




getSession(boolean create new session if not exist)


SSL has a built-in mechanism to define a session

URL rewriting

Cookies, the cookie name must be JSESSIONID

Ways a session die

Times out, <web-app> <session-config> <session-timeout>15</..., session.setMaxInactiveInterval(15*60);


App goes down


javax.servlet.http.HttpServletRequest.getCookies(); javax.servlet.http.HttpServletResponse.addCookie(cookie); The cookie conatin the sessionID and so..

Cookie(String name, String value)

getDomain() : String

getMaxAge(): int

getName(): String

getPath() : String

getSecure(): boolean

getValue(): String





Session Listeners

HttpSessionListener : HttpSessionEvent, sessionCreated, sessionDestroyed

HttpSessionActivationListener: HttpSessionEvent, sessionDidActive, sessionWillPassivate

HttpSessionBindingListener : HttpSessionBindingEvent, valueBound, valueUnbound

HttpSessionAttributeListener : HttpSessionBindingEvent, attributeAdded, attributeRemoved, attributeReplaced

Chap 7. Using JSP


Is translated into a java, then compiled into a class and loaded as a servlet

Import, <%@ page import="foo.*" %>, <%@ page import="foo.*,java.util.*" %>

Elements, <% %>, <%@ %>, <%= %>, <%! %>

Template text is just a fucking text =/

implicit objects, JspWriter : out, HttpServletRequest : request, HttpServletResponse : response, HttpSession: session, ServletContext : application, SerlvetConfig : config, Throwable : exception, PageContext : pageContext, Object : page

javax.servlet.jsp.JspPage, jspInit(), Access to, ServletConfig, ServletContext, jspDestroy(), javax.servlet.jsp.HttpJspPage, _jspService()

Attributes, In a Servlet, Application: getServletContext().setAttribute("foo", obj);, Request: request.setAttribute("foo", obj);, Session: request.getSession().setAttribute("foo", obj);, Page: does not apply, In a JSP, Application : application.setAttribute("foo", obj), Request: request.setAttribute("foo", obj), Session : session.setAttribute("foo", obj), Page: pageContext.setAttribute("foo", obj)

pageContext, Constants, APPLICATION_SCOPE, PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, Methods to get any implicit object, getRequest(), getServletConfigs(), getServletContext(), getSession(), Inherited Methods from JspContext, getAttribute(String name), getAttribute(String name, int scope), getAttributeNameInScope(int scope), findAttribute(String name)

Directives, page, Attributes, import, isThreadSafe, contetType, isELIgnored, isErrorPage, errorPage, Attributes outside of the examn, language, extends, session, buffer, autoFlush, info, pageEncoding, taglib, include

Disable, scripting, <jsp-config> <jsp-property-group> <url-pattern>*.jsp <scriptin-invalid> true ...., EL, <jsp-config> <jsp-property-group> <url-patter>*.jsp.. <el-ignored> true, <% page isElIgnored="true">

Actions, Standar action : <jsp:include page="Foo.jsp"/>, Other action: <c:set var="rate" value="32" />

Chap 8. Scriptless JSP


El expressions are always with curly braces, and prefixed with a dollar($) sign ${expression}

The first named variable in the expression is either an implicit object or an attribute in one of the four scopes (page, request, session or application)

The dot operator lets you access values by using a Map key or a bean property name. whatever comes to the right of the dot operator must follow normal Java naming rules

You can NEVER put anything to the right of the dot that wouldn't be legal as a Java identifire

The [] operator let you access arrays and lists, when retrive the entire list only the first element is displayed, initParam.list is the same as initParam.list[0]

If what's inside the brackets is not in quotes, the container evaluates it. if it's in quotes, and it's not an index into an array or list, the container sees it as the literal name of a property or key

All but one of the EL implicit objects are Maps (PageContext)

the implicit object request is represented by requestScope implicit object on EL

You can use TLD to call java methods

Alrays inside of [] should have "" if it's not a number

If the dot operator is used to access a bean property but the prperty doesn't exist, then a runtime exception is thrown


<jsp:useBean>, Defines a variable that holds a reference to either an existing bean attribute or, if the bean doesn't already exist, create a new bean, MUST have an "id" attribute which declares the variable name, the "scope" attribute default is page, The "class" attribute is optional, and it declares the class type that will be used if a new bean is created. The type must be public, non-abstract and have no-args constructor, The "type" attribute must be a type to which the bean can be cast, if you have "type" attribute but not have a "class" the bean must already exist, This tag can have body, and anything in the body runs ONLY if a new bean is created, <jsp:setProperty>, must have a name attribute and a "property" attribute (can be a wildcard), if it doesn't contain a property attribute the container will set the property value only if there's a request parameter with a name that matches the property name, if the request parameter is different from the property name, can use "param" attribute, The values can be String or primitives, and the tag takes care to do the conversion automagically


mechanisms, <%@ include FILE="header.html" %>, does the include at translation time, only once, <jsp:include PAGE="header.html" />, does the include at at runtime, every time!, can customize an included file by setting a request parameter using <jsp:param>, If the param name used already has a value as a request parameter, the new value will overwrite the previous one, it's NOT possible to import the contents of any binary file into a JSP page

is position-sensitive directive

be sure to strip out the opening and closing tags.

Cannot change the response status code or set headers

Taglib declaration

<taglib> ... <function> <name>Some</.. <function-class>com.some.package.class</.. <function-signature>java.lang.String param (java.lang.String)</.. </... </...


like RequestDispatcher forwards the request to another resouce from the same web app

the response buffer is cleared first!, so anything written to the response before the forward will be thrown away

if you commit the response before the forwad (calling out.flush()), the forward won't happen, and the rest of the original page won't be processed

attribute Page

Chap 9. Using JSTL

JSP Standard Tag Library

Core Tags

<c:out />, Attributes, value, escapeXml attribute is optional, true as default, default attribute is optional, the body of the c:out tag also works as default attribute

<c:forEach>, Attributes, var, items, varSatus, is a new variable that holds an instance of javax.servlet.jsp.jstl.core.LoopTagStatus, has a count property at least, can nest tags

<c:if>, Attributes, test, doesn't have an else

<c:choose>, <c:when>, test, <c:otherwise>

<c:set>, Variables, var, scope, default page, value, the body also works as value, Beans or Maps, target, property, value, the body also works as value

<c:remove>, attributes, var, scope, is optinoal if not exist remove from ALL

<c:import>, Attribute, url, value, var, add the contet from the value of url attribute to the current page, at request time (runtime) like jsp:include but it's more flexible, can reach outside of the web app, Body, <c:param>, Attributes, name, value

<c:catch>, attirubte, var





Manually, <%@ page isError="true">, ${pageContext.exception}, <%@ page errorPage="errorPage.jsp">

DD, <error-page> <exception-types>java.lang.Throwable</.. <location>/errorPage.jsp</... ..., <error-page> <exception-type>java.lang.ArithmeticException</... <location>/arimeticError.jsp</... ..., <error-page> <error-code>404</... <location>/notFoundError.jsp<... ....


Tag library descriptor

declaration, <?xml ...> <taglib xmlns...> <tlib-verion>1.2</tlib-verion> //mandatory <short-name>Random</short-name>//mandatory <function> //to be called on EL <name>rollIt</name> <function-class>foo.DiceRoller</function-class> <function-signature>int rollDice()</function-signature> </function> <uri>randomThings</uri> //unique! <tag> <description>randome advice</description>//optional <name>advice</name>//Required <tag-class>foo.AdvisorTagHandler</tag-class>//required <body-contet>empty</body-contet>//required <attribute> <name>user</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>, rtexprvalue, default is false, evaluate, EL expressions, Scripting expression, <jsp:attribute>, body-contet, values, empty, <mine:advice user="${userName}" />, <mine:advice user="${userName}" > </mine:advice>, <mine:advice > <jsp:attribute name="user">${userName}</...> </mine:advice>, scriptless, tagdependent, JSP, uri, doesn't have to be a location, <taglib> <taglib-uri>randomThings</.. <taglib-location>/WEB-INF/tag.tld</.. </...

class, extends SimpleTagSupport, override void doTag(), all setters needed

usage, <%@ taglib prefix="calis" uri="randomThings" %> <mine:advice user="${username}">

The TLD file can be placed in any subdirectory of WEB-INF

Chap 10. Custom tag Development

Tag handlers

Classic, Extend TagSupport -> IterationTag -> Tag -> JspTag, Life, 1. Load class, 2. Instantiate class (no-args constructor runs), 3. Call the SetPageContext(PageContext), 4. if the tag is nested setParent(Tag), 5. if the tag has attributes, call attributes setters, 6. doStartTag(), returns, SKIP_BODY, default, EVAL_BODY_INCLUDE, 7. if the tag is NOT declared to have an empty body, AND tag is NOT invoked with an empty body, AND the doStartTag() return EVAL_BODY_INCLUDE the body is evaluated, 8. if the body is evauated doAfterBody(), returns, SKIP_BODY, default, EVAL_BODY_AGAIN, 9. doEndTag(), returns, SKIP_PAGE, EVAL_PAGE, default, pageContext.getOutput().println, pageContext.implicitObjects

Classic BodyTag, extend BodyTagSupport (implement bodyTag -> iterationTag-> Tag-> JspTag ), Life, 1. Load class, 2. Instantiate class (no-args constructor runs), 3. Call the SetPageContext(PageContext), 4. if the tag is nested setParent(Tag), 5. if the tag has attributes, call attributes setters, 6. doStartTag(), returns, SKIP_BODY, EVAL_BODY_INCLUDE, EVAL_BODY_BUFFERED, default, 7. setBodyContet() if Eval_body_buffered was returned, 8. doInitBody(), 9. if the tag is NOT declared to have an empty body, AND tag is NOT invoked with an empty body, AND the doStartTag() return EVAL_BODY_INCLUDE the body is evaluated, 10. if the body is evauated doAfterBody(), returns, SKIP_BODY, default, EVAL_BODY_AGAIN, 11. doEndTag(), returns, SKIP_PAGE, EVAL_PAGE, default

Simple, Extend SimpleTagSupport --> SimpleTag --> JspTag, To deploy it, must crate a TLD that describes the tag using the same <tag> element, to use it with body, make sure the TLD <tag> for this tag does not declare <body-contet>empty. then call getJspBody().invoke(null) to cause the body to be processed, Life, 1. Load class, 2. Instantiate class (no-args constructor runs), 3. Call setJspContext(jspContext), 4. If the tag is nested, call the setParent(JspTag), 5. If the tag has attributes, call attribute setters, 6. if the tag is NOT decalred to have a <body-contet>empty.... and the tag has a body, call setJspBody(JspFragment), 7. doTag(), can set attribute used by the body of the tag, calling getJspContext().setAttribute() followed by getJspBody().invoke(), You can iterate over the body invoking the body (getJspBody.invoke()) in a loop, the getJspBody() return a JspFragment, methods, invoke(, getJspContet(), Throw a SkipPageException if you want the current page to stop processing, if the page that invoked the ta was included from another page, the including page keeps going even though the included page stops processin from the moment the exception is thrown, getJspContext().getOutput().println, getJspContext().implicitobjects


directives and actions to apply the name can be tag or tagx it MUST be inside of WEB-INF/tag lib

Apply only to tags, tag, taglib, jsp:doBdoy

directives but page

NOT Scripting


DynamicAttributes Interface

method, setDynamicAttribute(String uri, String name, object, value)

<tag> <attribute>... <dynamic-attribute>true</dynamic-attribute> ...

<%@ tag body-contet="empty" dynamic-attribute="tagAttrs">


extend from JspContext, mehtods, getAttributes(name), getAttribute(name, int scope), getAttributeNamesInScope(int scope), findAttribute(name)

methods, getRequest(), getServletConfig(), getServletCnontext(), getSession()

Scopes, Application, Page, Request, Session

Chap 11. Web App Deployment

Directory Structure

Webapps, NameofTheApp, *.jsp *html, WEB-INF, web.xml, *.tld, tags, *.tag, lib, *.jar, META-INF, TLDs, *.tld, package, *.class, classes, package, *.class

War, Webapps, NameofTheApp, *.jsp *html, WEB-INF, web.xml, *.tld, tags, *.tag, lib, *.jar, META-INF, TLDs, *.tld, package, *.class, classes, package, *.class, META-INF, MANIFEST.MF


<servlet> <servlet-name>Beer</servlet-name> <servlet-class>com.example.BeerSelect</servlet-class> </servlet> <servlet-mapping> <servlet-name>Beer</... <url-pattern>/Beer/</.. ...

Rules, one Match, 1. exact Match, 2. directory match, 3 extension match, multiples match, choose the longest mapp

Welcome file

<welcome-file-list> <welcome-file>index.html</... <welcome-file>default.jsp</.. </...


<servlet> <servlet-name>... <servlet-class>... <load-on-startup> number </.. ...

JSP Document (XML-based dcument)

the <% are only for reference they are not valid into a jsp docuemnt (xml-based)

Directives (except taglib), <%@ page import="java.util.*" %>, < import="java.util.*"/>

Declaration, <%! int y=3; %>, <jsp:declaration> int y = 3; </jsp:declaration>

Scriptlet, <%list.add("foo"); %>, <jsp:scriptlet> list.add("foo"); </jsp:scriptlet>

text, Simple text, <jsp:text> Simple text </jsp:text>

scripting expression, <%= %>, <jsp:expression> </jsp:expression>


local, <ejb-local-ref> <ejb-ref-name>ejb/Customer</.. <ejb-ref-type>Entity</.. <local-home>org.some.CustomerHome</... <local>org.some.Customer</... ......

remote, <ejb-ref> <ejb-ref-name>ejb</... <ejb-ref-type>Entitiy</... <home>org.some.CustomerHome</.. <remote>org.some.Customer</.. ...


is a way to get deploy-time constants into a j2ee app

<env-entry> <env-entry-name>rates/discountRate</.... <env-entry-type>java.lang.Integer</.. <env-entry-value>10</... ....


<mime-mapping> <extension>mpg</... <mime-type>video/mpeg</... .......

Chap 12. Web App Security

Realm: place where authentication information is stored


Step 1. Defining roles, tomcat-user.xml, <tomcat-users> <role rolename="Admin"/> <role rolename="Member"/> <role rolename="Guest"/> <user username="Guti" password="secret" roles="Admin, Member, Guest"/> <user username="Ted" password="Tedsecret" roles="Guest"/> ..........., DD, <security-role><role-name>Admin</role-name></security-role> <security-role><role-name>Member</role-name></security-role> <security-role><role-name>Guest</role-name></security-role>, <login-config> <auth-method>BASIC</... </...

Sept 2. Defining resource/method constrains, DD, <web-app> .... <web-resource-collection>, <web-resource-collection>, <web-resource-name>UpdateRecipes</.., <url-pattern>/Beer/AddRecipe/*</... <url-pattern>/Beer/ReviewRecipe/*</..., <http-method>GET</... <http-method>POST</...., </web-resource-collection>, <auth-constraint> <role-name>Admin</.. <role-name>Member</.. </...., <user-data-constraint> <transport-guarantee>CONFIDENTIAL</... </..., values, NONE, default, INTEGRAL, CONFIDENTIAL, </security-constraint> </web-app>

Multiples <security-constraint>

1. when combinig individual role names, all of the roles names listed will be allowed

2. A rle name of "*" combines with anything else to allow acces to everybody

3. An empty <auth-constraint> tag combines with anything else to allow access to nobody, empty tag is always final word, nobody allowed

4. if one <securty-constraint> has no <auth-constraint>, combines with anything else to allow access to everybody

Authentication types




FORM, <login-config> <auth-method>FORM</.. <form-login-config> <form-login-page>/loginPage.html</.. <form-error-page>/loginError.html</.. </.... </...., action= j_security_check j_username j_password





Chap 13. Wrappers and Filters


Methods, init(FilterConfig config), doFilter(ServletRequest, ServletResponse, FilterChain), destroy()

Filters have no idea who's going to call them or who's next in line

Declaring (DD)

<filter> <filter-name>BeerRequest</.. <filter-class>com.example.SomeFilter</.. <init-param> <param-name>logFile</.. <param-value>Log.txt</... </init... ...

<filter-mapping> <filter-name>BeerRequest</.. <url-pattern>*.do</... ...

<filter-mapping> <filter-name>BeerRequest</.. <servlet-name>AdviceServlet</... ...

<dispatcher>, REQUEST, default, INCLUDE, FORWARD, ERROR


wraps one kind of an object with an "enhanced" implementations (add new capabilities)

not necessary needs to override methods

Order rule

1. All matching Url patterns

2. Servlet-name

Chap 14. Patterns and Struts

Business Delegate

Use the business delegate pattern to shield your web tier controllers from the fact that some of your app's model components are remote.

Features, Acts as a proxy, implementing the remote service's interface, initiates communications with a remote service, handles communication details and exceptions, receives request from a controller component, translates the request and forwards it to the business services, translate the response and returns it to the controller component, by handling the details of remote component lookup and communications, allows controllers to be more cohesive

Principales, based on, hiding complexity, coding to interfaces, loose copuling, separation of concerns, minimizes the impact on the web tier when changes occur on the buisiness tier, Reduces coupling between tiers, Adds a layer to the app, which incrases complexity, Methods calls to the Buisness Delegate should be a coarse-grained to reduce network traffic

Service Locator

Use the service locator pattern to perform registry lookups so you can simplify all of the other components that have to do JNDI lookups

Features, Obtains InitialContext objects, Performs registry lookups, Handles communication details and exceptions, Can improve perfomance by caching previously obtained references, Works with a variety of registries such as: JNDI, RMI, UDDI, and COSS naming

Principales, based on, hiding complexity, separation of concerns, minimize the impact on the web tier when remote components change locations or containers, Reduce coupling between tiers

Transfer Object

minimize network traffic by providing a local representation of a fine-grained remote component

functions, provides a local representation of a remote entity, minimize network traffic, can follow java bean conventions so that it can be easily accessed by other objects, implemented as a serializable objects so that it can move across the network, typically easily accessible by view components

principales, based on reducing network traffic, minimize the performance impact on the web tier when remote components data is accessed with fine-grained calls, Reduces coupling between tiers, a drawback is that components accessing the Transfer Object can receive out-of-data data, because transfer object's data is really representing sate that's stored somewhere elese., Making updatable transfer objects concurency-safe is typcally complex

Intercepting Filter

modify the requests being sent to servlets, or to modify responses being sent to users

functions, can intercept and/or modify request before they reach the servlet, can intercept and/or modify the response before they are returned to the client, Filters are deployed declaratively using the DD, Filters are modular so that they can be exceuted in chains, Filters have lifecycles managed by the container, Filter must implemente Container callback methods

principales, based on, cohesion, lose coupling, increasing declarative control, delcarative control allow filters to be easily implemented on either a temporary or permanent basis, declarative control allows the sequence of invocation to be easily updated

Model View, Controller

create a logical structre that separates the code into three basic tye fo compoennts, in you application, this increase the cohesiveness of each component and allows for greater reusability, especially with model components

features, views can change independtly from controllres and model, model components hide interal details, from the view and controllers, if the model adheres to a stric contract,then these components can be reused in other app, separation fo model code from controller code allows for easier migration to using remote buisness components

principales, based on, separation of concerns, loose coupling, increase cohesion in inividual components, increase the overall complexity of the application, minimize the impact of changes in other tiers of the application

Fron controller

Use the fron controller pattern to gather common, often redundant, request processing code into a single component, this allows the application controller to be more cohesive and less complex

features, centralize a web app's initial request handling tasks in a single component, using the fron controller with other patterns can provide loose coupling by making presentation tier dispatching declarative, a drawback of front controller is that is' very barebons compared to strus

principales, based on, hiding complexity, separation of concerns, loose coupling, increases cohesin in application controller components, decreases the overall complexity of the application, increases the maintainability of the inferastructure code