Sei sulla pagina 1di 12

Header values in a HTTP message are used to specify general

information about the message like Cache-Control, Date etc. or


the data specific information like Content-Encoding, Length etc.
HttpServletRequest provides the following methods for
retrieving headers:
long getDateHeader(String name)
Returns the value of the specified request header as
a long value that represents a Date object.
String getHeader(String name)
Returns the value of the specified request header as
a String.
Enumeration getHeaderNames()
Returns an enumeration of all the header names this
request contains.
Enumeration getHeaders(String name)
Returns all the values of the specified request header
as an Enumeration of String objects.
int getIntHeader(String name)
Returns the value of the specified request header as
an int. If there is no header by this name, then it
returns "-1" and if the value cannot be converted to
an int then it throws a NumberFormatException.

ServletContext provides the following methods to access


resources:
URL getResource(String path)
Returns a URL to the resource that is mapped to a specified
path.
InputStream getResourceAsStream(String path)
Returns the resource located at the named path as an
InputStream object.
The path must begin with a "/" and is interpreted as relative to
the current context root.
init() throws ServletException
service() and doXXX() throw ServletException and IOException
destroy() DOES NOT throw any exception.

String[] getParameterValues(String name)


Returns an array of String objects containing all of the values
the given request parameter has, or null if the parameter does
not exist.

String getParameter(String name)


Returns the value of a request parameter as a String, or null if
the parameter does not exist. If the parameter has multiple
values, the first value is returned.

Map getParameterMap()
Returns a java.util.Map of the parameters (mapped to String[]
of values) of this request.

Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names
of the parameters contained in this request.

Signature of all the doXxx() methods are same. They are


protected, return void, and throw IOException and
ServletException

ServletContext (for application scope), HttpSession (for session


scope) and ServletRequest(for request scope) have the following
three methods to get and set attribute:

Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes
available.
res.isCommitted() to check whether the response is committed or
not. And then call res.sendError() if the response is not
committed

A servlet can add a cookie only to the HttpServletResponse


object (not to a request).
HttpServletResponse has only one method to add a cookie:
void addCookie(Cookie cookie)

ServletInputStream (for binary file) or the Reader (for text


file) from the request.

###########################

Only one instance of the filter class is instantiated per <filter>


declaration in web.xml

the caller resource cannot generate any output after the call to
forward().

An error handler servlet should have access to 4 attributes:


javax.servlet.error.status_code , javax.servlet.error.exception,
javax.servlet.error.servlet_name, and
javax.servlet.error.request_uri.
So, if you are forwarding the request to an error handling servlet
manualy using RequestDispatcher, you should set the above
attributes in the request before forwarding the request to the
servlet.

You should do JNDI lookups to acquire resources such as a JMS


queue in servlet's init() method.
in the case of forward(), the caller is not allowed to write
anything to the response after forwarding the request.

The filter class must implement 3 methods.


init(FilterConfig), doFilter(ServletRequest, ServletResponse,
FilterChain), and destroy() . These methods are declared in
javax.servlet.Filter interface.

if you write to the response after calling sendError() then the


data is ignored and no exception is thrown

ServletContextEvent object. It has only one method-


getServetContext()

Catch the exception, wrap it into ServletException and define


the 'business exception to error-page' mapping in web.xml

The method HttpServletRequest.getHeader() returns a String


containing the complete value of the header in the String.
The method HttpServletRequest.getHeaders() returns an
Enumeration in which each comma separated value can be
retrieved using Enumeration.nextElement().

The following is the sequence of things that happen when you


invalidate a session:
1. Container calls sessionDestroyed() on all HttpSessionListeners
configured in web.xml (in the order they are declared in web.xml).
Notice that although the method name is sessionDestroyed, the
session is not destroyed yet . It is about to be destroyed.
2. The container destroys the session.
3. The container calls valueUnbound() on all the session attributes
that implement HttpSessionBindingListner interface.

contextpath, requestpath (or servlet path), and pathinfo, all start


with a /.
Request URL = protocol://host:port + contextpath + requestpath
+ pathinfo
Request Path is the path that maps to the <url-pattern> of the
<servlet-mapping>.

doXXX methods cannot throw exceptions other than:


. runtime exceptions or errors
. ServletExceptions or subclasses thereof
. IOExceptions or subclasses thereof

a url-pattern always starts with a / except when it is an


extension mapping
You cannot start an extension mapping with a /.
extension mapping is considered ONLY if there is no path
matching

<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>false</el-ignored>
</jsp-property-group>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>false</scripting-invalid>
</jsp-property-group>
</jsp-config>

A web application may access any resource in the WAR files or in


any of the jar files in the lib directory using getResource
A web application cannot override the web container
implementation classes
###########################
The valueBound() method is called BEFORE the object becomes
accessible through HttpSession.getAttribute()

The valueUnbound() method is called AFTER the object is


removed from the HttpSession

When the sendError() method is called, the response is assumed


to be committed.
As per the API of the sendError() method, if you write to the
response after calling sendError() then the data is ignored and no
exception is thrown
A new javax.servlet.ServletRequestListener has been added in
the API for this purpose. It is configured in web.xml.

regarding the getResource() method of ServletContext


If a jsp file is retrieved, the jsp code contained will be returned
as it is.

If you want to print the stack trace of the exception in the


resulting HTML page, you must catch the exception and print the
stack trace using the Throwable.printStackTrace(PrintWriter
pw) method.

ServletException provides the getRootCause() method that


returns the wrapped exception. It's return type is Throwable, so
you have to cast it to appropriate business exception type.

void sendError(int sc)


Sends an error response to the client using the specified
status code and clearing the buffer.
void sendError(int sc, String msg)
Sends an error response to the client using the specified status
code and descriptive message.

void setStatus(int sc)


Sets the status code for this response.

void setStatus(int sc, String sm)


Deprecated.

A call to forward() clears the output buffer before the target


resource is invoked
The execution control returns to the resource that has called the
RequestDispatcher.forward() method after the callee resource
finishes processing

include() allows but forward() doesn't include() allows but


forward() doesn't allow the caller resource to generate any
amount of output because if any output is sent to the client,
forward() throws an IllegalStateException.

GenericServlet class and ServletContext interface, provide


methods log(String msg) and log(String, Throwable) that write
the information to a log file. Only difference is that the
GenericServlet version also prepends the servlet name to the
message.

###########################

<security-role-ref>
<role-name>boss</role-name> <!-- used by the servlet -->
<role-link>manager</role-link> <!-- actual role defined else
where as a <security-role> element in the web.xml -->
</security-role-ref>

public java.security.Principal getUserPrincipal()


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

declarative security model does not apply in case of include and


forward actions. Thus, an unprotected resource can have a call to
a protected resource without having the user to log in.

###########################

you are dynamically including page b.jsp in a.jsp (<jsp:include


page='b.jsp' /> ). Now, a page scoped bean in a.jsp will not be
accessible in b.jsp when the request is transfered to b.jsp. While
a request scoped bean in a.jsp will be accessible in b.jsp too.
Note, page scoped bean will be acessible in b.jsp if it is a static
include ( <%@include file='b.jsp' /> ) in a.jsp because b.jsp
becomes a part of the translation unit.

the useBean tag is inside a block, the variable sb will be declared


inside the block and thus will not be accessible outside it. So the
line <%=sb%> will give:
Undefined variable: sb

The only requirement for a class to be used as a bean in a JSP


page is that the class should have a public no-args constructor
otherwise java.lang.InstantiationException.
<jsp:setProperty name="user" property="*" /> This sets all the
parameters of the request in user bean. Of course, parameter
names in the request must match property names of the bean.

If the Bean is not already instantiated then the container looks


for class or beanName attribute to instantiate an object and then
if type is present, it casts the object to the type.

Only and at least one of these four combinations must be there in


a useBaen tag:
a. class
b. type
c. class and type
d. beanName and type
The following element sets a property from a value
<jsp:setProperty name="results" property="subjectX"
value="<%=i+1%>"/>

###########################

The following prefix values are reserved and hence cant be used
in taglib prefixes:
jsp, jspx, java, javax, sun, servlet, and sunw.

A feature of the 'out' tag is that it performs XML character-


entity encoding for <, >, &, ", and ' automatically (by default). This
means that a < will be automatically encoded to &lt; and a > will be
encoded to &gt; and so on. In this case, however, we do not want
this feature because we want to write <h1> and </h1> in the
output. Therefore, we need to supress this feature by specifying
escapeXml='false'.

<%=dept.getName()%> is invalid here:


<c:forEach var="dept" items="${departments}">
<c:out value="${dept.name}"/><br><%=dept.getName()%>
</c:forEach>

<c:forEach var="i" begin="10" end="30" step="5"


varStatus="status">
<c:if test="${status.first}">
begin:<c:out value="${status.begin}"/> end:<c:out
value="${status.end}"/> step:<c:out value="${status.step}"/>
</c:if>
</c:forEach>

If you include the var attribute, the text is not included


automatically. It is included only where you use the variable. For
example:
<c:import url="/test2.jsp" var='text' scope='request' /> <-
test2.jsp will NOT be included here.
...lot of other code
<c:out value='${text}' /> <- test2.jsp will be included here.

Since the body content of the tag is tagdependent, the body of


the tag will not be processed by the JSP engine. It must be
processed by the tag itself.

You cannot embed one tag inside another tag's attribute list.
(Although you can nest one tag inside another).

###########################
To use scriptlets in a tag's body, its body-content must be JSP.
Now, the body of a Simple Tag is translated into a JSP fragment
and since JSP fragments do not support scriptlets, the <body-
content> of a SimpleTag cannot be JSP. A TLD is invalid if it
specifies JSP as the value for <body-content> for a tag whose
handler implements the SimpleTag interface.

Only the following directives are valid for tag files:


taglib, include, tag, attribute, variable.

If we extend BodyTagSupport, then we use


BodyTagSupport.getPreviousOut() to get the enclosing JspWriter

###########################

"Workflow" and "dispatch requests to the appropriate JSP pages"


are typical uses of Front Controller pattern. It is also called as
Front Component.

The <distributable/> is an empty element. It's presence itself


signifies that the application may be distribtued.

tagext package is a part of javax.servlet.jsp package and not of


javax.servlet.http package.

The default implementation of HttpServlet class's doHead()


method calls the doGet() method.

"Accept" header contains strings like "image/gif", which cannot


be parsed into a data.
###########################

request scoped beans are stored in ServletRequest.

javax.servlet.jsp.JspPage Extends javax.servlet.Servlet and


declares jspInit() and jspDestroy().

javax.servlet.jsp.HttpJspPage This interface extends JspPage


and adds _jspService() method.

If the <scripting-invalid> is specified as true, then a jsp file must


not contain any scripting elements otherwise the file is not even
translated to the corresponding servlet.

If header has multiple values, only the first value is contained in


‘header’ implicit object.

javax.servlet.Servlet <- javax.servlet.jsp.JspPage <-


javax.servlet.jsp.HttpJspPage <- MyJSP

Any page directive except import can only occur only once

Potrebbero piacerti anche