Java EE

Use Guava Cache To Improve Performance

  • Posted on: 18 April 2015
  • By: Zhijun Chen

It is quite often that you might want to use cache a value when it is expensive to compute or retrieve, e.g. involves several hibernate queries and serialization.

Guava Cache is one of the options if you just need to cache the value in RAM instead of files.

In my case, I'm using CacheLoader as I've got key/value pairs. The following utility class shows how this can be done.

package uk.co.zhijun.manager.cache;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

/**
 * 
 */
public class StudentCache {

  private static Logger logger = LoggerFactory
      .getLogger(StudentCache.class);

  private LoadingCache<Long, Student> studentCache;
  private StudentManager studentManager;

  public StudentCache(int expirationTimeMinutes) {
    buildStudentCache(expirationTimeMinutes);
  }

  private void buildStudentCache(int expirationTimeMinutes) {
    studentCache = CacheBuilder.newBuilder()
        .expireAfterAccess(expirationTimeMinutes, TimeUnit.MINUTES)
        .removalListener(studentRemovalListener)
        .build(new CacheLoader<Long, Student>() {

          @Override
          public Student load(Long id) throws Exception {
            return studentManager.getStudentById(id);
          }
        });
  }

  public Student getStudent(Long id) throws ExecutionException {
      return studentCache.get(id);
  }

  public void invalidateStudentCache(Long id) {
    studentCache.invalidate(id);
  }

  private RemovalListener<Long, Student> studentRemovalListener = new RemovalListener<Long, Student>() {
    public void onRemoval(RemovalNotification<Long, Student> removal) {
      logger.info(
          "Refreshing student, studentId = {}, was evicted? {}",
          removal.getKey(), removal.wasEvicted());
    }
  };

  /* provided for spring setter injection */
  public void setStudentManager(StudentManager studentManager) {
    this.studentManager = studentManager;
  }
}

You can then register this class in the spring context and use it. The cache should be evicted everytime a change is going to affect the Student object.

...
<bean id="studentCache" class="uk.co.zhijun.manager.cache.StudentCache">
  <constructor-arg name="expirationTimeMinutes" value="10" />
  <property name="studentManager" ref="studentManager" />
</bean>
...

Solution for "InvalidPathException: Malformed input" in Tomcat

  • Posted on: 3 December 2014
  • By: Zhijun Chen

Today I came across the following Java Exception within Tomcat Web Application:

"java.nio.file.InvalidPathException: Malformed input or input contains unmappable characters."

This is due to file system not able to handle special characters in a file name, e.g. Tromsø.png
The solution to this issue is actually quite simple. Set the system language to be UTF8 using the following code:

export LANG = en_US.UTF8

Then restart Tomcat. Now Tomcat should pick up the system property and set the file.encode to be UTF8.

JSP Notes for OCEJWCD Exam

  • Posted on: 4 August 2013
  • By: Zhijun Chen

Here are the main notes for JSP part of Oracle Certified Expert, Java EE 6 Web Component Developer Exam.

Directive: <%@page attrList %>

  • import = “JAVA PACKAGE”
  • session = true | false
  • contentType = TYPE;[charset=CHARSET]
  • isELIgnored = true | false

Directive: <%@taglib attrList %>

  • uri = “URI”
  • tagdir = “the directory within the WAR of the library of tag files”
  • prefix = “prefix of the tag library”

Note: Translation error if BOTH of uri and tagdir are declared

Directive: <%@include file = “directory” %>

Declaration: <%! variable or method %>

Note: Content is put in global scope of translated JSP code, outside _jspService method

Scriptlet: <% content with semicolon %>

Expression: <%= expression without semicolon %>

Note: Content is put in _jspService method

Comments:

  • <!-- comment text here --> (Returned to client)
  • <%-- JSP comment here --> (Completely ignored)
  • <% /** Java comment here */ %> (Comment in translated file)

Implicit Objects:

  • request (Class implements javax.servlet.ServletRequest)
  • response (Class implements javax.servlet.ServletResponse)
  • pageContext (Class extends javax.servlet.jsp.PageContext)
  • session (Class implements javax.servlet.http.HttpSession)
  • application (Class implements javax.servlet.ServletContext)
  • out (Class extends javax.servlet.jsp.JspWriter)
  • config (Class implements javax.servlet.ServletConfig)
  • page (Class extends Object)
  • exception (Class java.lang.Throwable)

javax.servlet.jsp.JspContext (Class)

  • Object findAttribute(String name) [all scopes]
  • Object getAttribute(String name) [page scope]
  • Object getAttribute(String name, int scope)
  • Enumeration getAttributeNamesInScope(int scope)
  • int getAttributesScope(String name)
  • void removeAttribute(String name) [all scopes]
  • void removeAttribute(String name, int scope)
  • void setAttribute(String name, Object value) [page scope]
  • void setAttribute(String name, Object value, int scope)
  • JspWriter getOut()
  • JspWriter pushBody(Writer writer)
  • JspWriter popBody()
  • ExpressionEvaluator getExpressionEvaluator()
  • VariableResolver getVariableResolver()

javax.servlet.jsp.PageContext (Class extends JspContext)

  • Exception getException()
  • Object getPage()
  • ServletRequest getRequest()
  • ServletResponse getResponse()
  • ServletConfig getServletConfig() [retrieve config implicit object]
  • ServletContext getServletContext() [retrieve application implicit object]
  • HttpSession getSession()
  • JspWriter getOut()
  • void forward(String relativeURL)
  • void include(String relativeURL)
  • void include(String relativeURL, boolean flush)
  • ErrorData getErrorData()
  • void handlePageException(Exception e)
  • void handlePageException(Throwable t) 

JSP documents (XML view)

  • Root element: <jsp:root xmlns:jsp = “http://java.sun.com/JSP/Page” version = “2.0”>, version is mandatory, should be 1.2 or 2.0, this element is optional in JSP 2.0.
  • Directive: <jsp:directive.page attrList>
  • Directive: <jsp:directive.include attrList>
  • There is no <jsp:directive.taglib />
  • Expression: <jsp:expression>content</jsp:expression>, need to use <jsp:text> and CDATA to insert scripting elements in attribute values, e.g.

<jsp:text><![CDATA[<img src = “]]></jsptext>

<jsp:expression>request.getAttribute(“image_source”)</jsp:expression>

<jsp:text><![CDATA[” />]]>

Can also use Expression Language.

Expression Language

  • Basic syntax: ${expression}
  • String concatenation is not supported
  • Data types: Boolean, Integer, Floating point, String, Object, Null
  • Implicit objects:
    • pageContext: the PageContext object for the current JSP
    • pageScope: Map of page attributes
    • requestScope: Map of request attributes
    • sessionScope: Map of session attributes
    • applicationScope: Map of application/context attributes
    • param: Map of request parameter names matched against a single String parameter value
    • paramValues: Map of request parameters
    • header:Map of request header names against a single String header value
    • headerValues: Map of request headers
    • initParam: Map of context initialisation parameters
    • cookie: Map of cookie
  • object.string_property or object[“string_property”] for String, collection[“number”] or object[number] for interger
  • Operators: (Ordered)
    • [], .
    • ()
    • -, not, !, empty
    • *, /, div, %, mod
    • +, -
    • <, lt, >, gt, <=, le, >=, ge
    • ==, eq, !=, ne
    • &&, and
    • ||, or
    • ? :
  • Every EL function has an asscociated public static method in a compiled Java class
  • The web container evaluates an attribute/variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String). For example, when evaluating the expression ${product}, the container will look for product in the page, request, session, and application scopes and will return its value.
  • Evaluation of scripting elements: <scripting-invalid>true</scripting-invalid> inside <jsp-property-group /> element
  • Evaluation of EL expressions
    • <el-ignored>true</el-ignored> in a <jsp-property-group/> element
    • isElIgnored = “true” in a page directive

<jsp:useBean id = “var_name” scope = “var_scope” attrList />

  • class = “class_name”
  • class = “class_name” type = “generalised_class”
  • beanName = “bean_class” type = “var_type”
  • type = “class_type”

Note: scope is default to page. The type attribute can be used without class, but unless an instance exists an exception will be thrown. The beanName attribute of useBean is only used with serialized beans.

<jsp:setProperty name = “var_name” property = “property_name” attrList />

  • property = “*” will iterate over all request parameters, update all matching ones
  • value = “val”
  • param = “req_param” will set value to the same as the request parameter

Note: When a setProperty tag is nested within a useBean tag it will not be executed if the bean already exists

<jsp:getProperty name = “var_name” property = “prop_name”>

<jsp:include attrList /> [body can contain <jsp:param />]

  • page = “url” (mandatory)
  • flush = “false” (optional)

<jsp:forward page = “rel_URL”> [body can contain <jsp:param />]

<jsp:param name = “name” value = “value” />

JSTL Core Library

  • <c:out value = “” escapeXml = true default = “” /> or <c:out>content</c:out>
    • value is mandatory
  • <c:catch var = “page_var_name”>nested actions</c:catch>
  • <c:remove var = “var_name” scope = “var_scope” />
    • var is mandatory
  • <c:set var = “var_name” scope = “var_scope” value = “var_value” /> or

<c:set var = “var_name” scope = “var_scope”>var_value</c:set>

    • var is mandatory
    • value is mandatory when body is empty
  • <c:set target = “obj_target” property = “prop_name” value = “value” /> or

<c:set target = “obj_target” property = “prop_name”>value</c:set> [the same as <jsp:setProperty />]

    • target and property are mandatory, value is mandatory if body is empty
    • obj_target must be a real-time expression, either EL or scripting element.
  • <c:if test = “test_cond” var = “var_name” scope = “var_scope” /> or

<c:if test = “test_cond” var = “var_name” scope = “var_scope”>output</c:if>

    • test is mandatory, var is mandatory if the body is empty
  • <c:choose>

<c:when test = “cond_1”>

       …

</c:when>

<c:otherwise>

       …

</c:otherwise>

       </c:choose>

  • <c:forEach begin = “index1” end = “index2” step = “step_length”>

body_content

</c:forEach>

  • <c:forEach items = “collection_obj”>

       body_content

</c:forEach> [var, begin, end, step can be added as optional attributes]

Special attribute: varStatus [object of type javax.servlet.jsp.jstl.core.TagLoopStatus] and has the following methods:

    • Object getCurrent()
    • int getIndex()
    • int getCount()
    • boolean isFirst()
    • boolean isLast()
    • Integer getBegin()
    • Integer getEnd()
    • Integer getStep()
  • <c:forTokens items = “token_string” delims = “separator_sequence”>

Body content

       </c:forTokens>

       [var, begin, end, step, varStatus can be added as optional attributes]

  • <c:url value = “url_expression” context = “context_url” var = “var_name” scope = “var_scope” /> [body can contain <c:param />]
    • value is mandatory
  • <c:import url = “resource_url” context = “app_context” varReader = “reader_obj”> [body can contain <c:param />]
    • url is mandatory
  • <c:redirect url = “redirect_url” context = “app_context” /> [body can contain <c:param />]
    • url is mandatory
  • <c:param name = “param_name” value = “param_value” /> or

<c:param name = “param_name”>param_value</c:param>

javax.servlet.jsp.tagext.Tag (Interface extends JspTag)

  • void setParent(Tag tag)
  • void setPageContext(PageContext pageContext)
  • Tag getParent()
  • void release()
  • int doStartTag() [return either EVAL_BODY_INCLUDE or SKIP_BODY]
  • int doEndTag() [return either EVAL_PAGE or SKIP_PAGE]

javax.servlet.jsp.tagext.IterationTag (Interface extends Tag)

  • int doAfterBody() [return either SKIP_BODY or EVAL_BODY_AGAIN]

javax.servlet.jsp.tagext.TagSupport (Class implements IterationTag)

  • doStartTag() returns SKIP_BODY
  • doAfterBody() returns SKIP_BODY
  • doEngTag() returns EVAL_PAGE
  • static Tag findAncestorWithClass(Tag from, Class clazz)

javax.servlet.jsp.tagext.BodyTag (Interface extends IterationTag)

  • void setBodyContent(BodyContent content)
  • void doInitBody()

Note: Both of these two methods will only be invoked when the doStartTag method returns EVAL_BODY_BUFFERED.

javax.servlet.jsp.tagext.BodyContent (Class extends JspWriter)

  • void clearBody()
  • void flush()
  • JspWriter getEnclosingWriter()
  • Reader getReader()
  • String getString()
  • void writeOut(Writer writer)

javax.servlet.jsp.tagext.BodyTagSupport (Class extends TagSupport implements BodyTag)

  • doStartTag() returns EVAL_BODY_BUFFERED
  • doAfterBody() returns SKIP_BODY
  • doEndTag() returns EVAL_PAGE

javax.servlet.jsp.tagext.SimpleTag (Interface extends JspTag)

  • void setJspContext(JspContext context)
  • void setParent(JspTag parent)
  • JspTag getParent()
  • void setJspBody(JspFragment fragment)
  • void doTag() 

javax.servlet.jsp.tagext.SimpleTagSupport (Class implements SimpleTag)

  • protected JspContext getJspContext()
  • protected JspFragment getJspBody()
  • static JspTag findAncestorWithClass(Tag from, Class clazz)

javax.servlet.jsp.tagext.JspFragment (Class)

  • JspContext getJspContext()
  • void invoke(Writer writer)

SimpleTags are never pooled, Class tags are pooled so instance variables need to be reset either inside doStartTag() or doEndTag()

javax.servlet.jsp.tagext.DynamicAttributes (Interface)

  • void setDynamicAttribute(String ns, String name, Object value)

javax.servlet.jsp.tagext.TagAdapter (Class implements Tag)

  • Tag getParent()
  • JspTag getAdaptee()

Tag files

<%@ tag attrList %> or <jsp:directive.tag attrList /> [replace page directive in tag files]

  • display-name
  • body-content: [empty, scriptless, tagdependent]
  • dynamic-attributes
  • small-icon
  • large-icon
  • description
  • example
  • language
  • import
  • pageEncoding
  • isELIgnored = true | false

Note: body-content = “JSP” is not permitted for a SimpleTag or a tag file.

<%@ attribute attrList %> or <jsp:directive.attribute attrList /> [used to specify the name and runtime type of all attributes declared by an action]

  • name
  • required = true | false
  • fragment = true | false
  • rtexprvalue = true | false
  • type = “full qualified class name”
  • description 

<%@ variable attrList %> or <jsp:directive.variable attrList />

  • name-given = “output_name”
  • name-from-attribute = “action_attribute_name”
  • alias = “local_name”
  • variable-class
  • declare = true | false
  • scope [AT_BEGIN, AT_END or NESTED(default)]
  • description 

Tag files implicit objects: request, response, jspContext, session, application, out, config

<jsp:doBody attrList />

  • varReader
  • var
  • scope

Note: var xor varReader

<jsp:invoke fragment = “attribute_name” />

  • varReader
  • var
  • scope

Note: var xor varReader

Structure for Deployment Descriptor (web.xml)

  • Posted on: 4 August 2013
  • By: Zhijun Chen

Deployment Descriptor

* - Optional(0 or more)        ? – Optional(0 or 1)              + - 1 or more         1 – Required(exactly 1)

Note: All elements under web app are marked as *.

<web-app>

<description>*</description>

<display-name>*</display-name>

<icon>

       <small-icon>*</small-icon>

       <large-icon>*</large-icon>

</icon>

<distributable>*</distributable>

<context-param>

       <description>*</description>

       <param-name>1</param-name>

       <param-value>1</param-value>

</context-param>

<filter>

       <description>*</description>

       <display-name>*</display-name>

       <icon>*</icon>

       <filter-name>1</filter-name>

       <filter-class>1</filter-class>

       <init-param>*

              <description>*</description>

              <param-name>1</param-name>

              <param-value>1</param-value>

       </init-param>

</filter>

<filter-mapping>

       <filter-name>1</filter-name>

       <url-pattern>1, xor to servlet-name</url-pattern>

       <servlet-name>1, xor to url-pattern</servlet-name>

       <dispatcher>0 to 4, FORWARD, INCLUDE, REQUEST, ERROR</dispatcher>

</filter-mapping>

<listener>

       <description>*</description>

<display-name>*</display-name>

<icon>*</icon>

<listener-class>1</listener-class>

</listener>

<servlet>

       <description>*</description>

       <display-name>*</display-name>

       <icon>*</icon>

       <servlet-name>1</servlet-name>

       <servlet-class>1, xor to jsp-file</servlet-class>

       <jsp-file>1, xor to servlet-class</jsp-file>

       <init-param>*

              <description>*</description>

              <param-name>1</param-name>

              <param-value>1</param-value>

       </init-param>

       <load-on-startup>?</load-on-startup>

       <run-as>?</run-as>

       <security-role-ref>*

              <description>*</description>

              <role-name>1</role-name>

              <role-link>?</role-link>

</security-role-ref>

</servlet>

<servlet-mapping>

       <servlet-name>1</servlet-name>

       <url-pattern>1</url-pattern>

</servlet-mapping>

<session-config>

       <session-timeout>?, in minutes</session-timeout>

</session-config>

<mime-mapping>

       <extension>1</extension>

       <mime-type>1</mime-type>

</mime-mapping>

<welcome-file-list>

       <welcome-file>+</welcome-file>

</welcome-file-list>

<error-page>

       <error-code>1, xor to exception-type</error-code>

       <exception-type>1, xor to error-code</exception-type>

       <location>1</location>

</error-page>

<jsp-config>

       <description>*</description>

       <display-name>*</display-name>

       <icon>*</icon>

       <taglib>*

       <taglib-uri>1</taglib-uri>

       <taglib-location>1</taglib-location>

</taglib>

<jsp-property-group>*

       <description>*</description>

       <display-name>*</display-name>

       <icon>*</icon>

       <url-pattern>+</url-pattern>

       <el-ignored>?</el-ignored>

       <page-encoding>?</page-coding>

       <scripting-invalid>?</scripting-invalid>

       <is-xml>?</is-xml>

       <include-prelude>*</include-prelude>

       <include-coda>*</include-coda>

</jsp-property-group>

</jsp-config>

<security-constraint>

       <display-name>*</display-name>

       <web-resource-collection>+

              <web-resource-name>1</web-resource-name>

              <url-pattern>+</url-pattern>

              <http-method>*, GET, POST, PUT, DELETE, etc.</http-method>

       </web-resource-collection>

       <auth-constraint>?

              <role-name>*</role-name>

       </auth-constraint>

<user-data-constraint>

       <transport-guarantee>

NONE, INTEGRAL, CONFIDENTIAL

</transport-gurantee>

</user-data-constraint>

</security-constraint>

<login-config>

       <auth-method>?, BASIC, DIGEST, CLIENT-CERT, FORM</auth-method>

       <realm-name>?, not required for CLIENT-CERT, FORM</realm-name>

       <form-login-config> only for FORM auth-method

              <form-login-page>1</form-login-page>

              <form-error-page>1</form-error-page>

       </form-login-config>

</login-config>

<security-role>

       <role-name>1</role-name>

</security-role>

<env-entry></env-entry>

<ejb-ref>

       <ejb-ref-name></ejb-ref-name>

       <ejb-ref-type></ejb-ref-type>

       <ejb-ref-home></ejb-ref-home>

       <ejb-ref-remote></ejb-ref-remote>

</ejb-ref>

<ejb-local-ref></ejb-local-ref>

<service-ref></service-ref>

<resource-ref>

       <description>*</description>

       <res-ref-name></res-ref-name>

       <res-type></res-type>

       <res-auth></res-auth>

</resource-ref>

<resource-env-ref></resource-env-ref>

</web-app>

Servlet Notes for OCEJWCD 6 Exam

  • Posted on: 4 August 2013
  • By: Zhijun Chen

Here are the main notes for Servlet part of Oracle Certified Expert, Java EE 6 Web Component Developer Exam.

javax.servlet.Servlet (Interface)

  • void init(ServletConfig)
  • void init()
  • void destroy()
  • void service(ServletRequest, ServletResponse)

 javax.servlet.GenericServlet (Class implements Servlet)

  • ServletConfig getServletConfig()
  • ServletContext getServletContext() [== getServletConfig().getServletContext()]
  • String getInitParameter(String name) [== getServletConfig().getInitParameter(String name)]
  • Enumeration getInitParameterNames() [== getServletConfig().getInitParameterNames()]
  • String getServletName() [== getServletConfig().getServletName()]

javax.servlet,http.HttpServlet (Class extends GenericServlet)

  • protected void service(HttpServletRequest, HttpServletResponse)
  • protected void doXxx(HttpServletRequest, HttpServletResponse) throws ServletException, IOException (doPost, doGet, doHead, doPut, doDelete, doTrace, doOptions)

javax.servlet.ServletContext (Interface)

  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • void removeAttribute(String name)
  • void setAttribute(String name, Object value)
  • String getServletContextName()
  • String getRealPath(String path)
  • Set getResourcePaths(Sting path)
  • ServletContext getContext(String appUrl)
  • java.net.URL getResource(String path)
  • java.io.Inputstream getResourceAsStream(String path)
  • String getMimeType(String path)
  • RequestDispatcher getRequestDispatcher(String path)
  • RequestDispatcher getNamedDispatcher(String name)
  • String getInitParameter(String name)
  • Enumeration getInitParameterNames()
  • ServletRegistration.Dynamic addServlet(String name, String servletClass)
  • FilterRegistration.Dynamic addFilter(String name, String filterClass)
  • ServletRegistration.Dynamic addServlet(String name, Class<? extends Servlet> servletClass)
  • FilterRegistration.Dynamic addFilter(String name, Class<? extends Filter> filterClass)
  • <T extends Servlet> T createServlet(Class<T> servletClass)
  • <T extends Filter> T createFilter(Class<T> filterClass)
  • ServletRegistration.Dynamic addServlet(String name, Servlet s)
  • FilterRegistration.Dynamic addFilter(String name, Filter filter)
  • void addListener(Class<? extends java.util.EventListener> listenerImplementationClass)
  • void addListener(String listenerImplementationClassName)
  • FilterRegistration getFilterRegistration(String filterName)
  • Map<String, ? extends FilterRegistration> getFilterRegistrations()
  • ServletRegistration getServletRegistration(String servletName)
  • Map<String, ? extends ServletRegistration> getServletRegistrations()
  • boolean setInitParameters(String name, String value)
  • void declareRoles(String… roleNames)
  • JspConfigDescriptor getJspConfigDescriptor()
  • SessionCookieConfig getSessionCookieConfig()
  • Set<SessionTrackingMode> getDefaultSessionTrackingModes()
  • Set<SessionTrackingMode> getEffectiveSessionTrackingModes()
  • void setSessionTrackingModes(Set<SessionTrackingMode> modes)
  • int getEffectiveMajorVersion()
  • int getEffectiveMinorVersion()
  • int getMajorVersion()
  • int getMinorVersion()
  • String getServerInfo()

Note: SessionTrackingMode includes COOKIE, URL, SSL.

javax.servlet.Registration (Inteface)

  • String getClassName()
  • String getName()
  • String getInitParameter(String name)
  • Map<String, String> getInitParameters()
  • boolean setInitParameter(String name, String value)
  • Set<String> setInitParameters(Map<String, String> initParams)

javax.servlet.Registration.Dynamic (Interface extends Registration)

  • void setAsyncSupported(boolean isAsyncSupported)

javax.servlet.ServletRegistration (Interface extends Registration)

  • Set<String> addMapping(String… urlPatterns)
  • Collection<String> getMappings()
  • String getRunAsRole()

javax.servlet.FilterRegistration (Interface extends Registration)

  • void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String… servletNames)
  • void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String… urlPatterns)
  • Collection<String> getServletNameMappings()
  • Collection<String> getUrlPatternMappings()

javax.servlet.FilterRegistration.Dynamic (Interface extends FilterRegistration and Registration.Dynamic) [No additional methods]

javax.servlet.ServletRegistration.Dynamic (Interface extends ServletRegistration and Registration.Dynamic)

  • void setLoadOnStartup(int loadOnStartup)
  • void setRunAsRole(String roleName)
  • void setMultipartConfig(MultipartConfigElement multipartConfig)
  • Set<String> setServletSecurity(ServletSecurityElement constraint)

javax.servlet.ServletConfig (Interface)

  • String getServletName()
  • ServletContext getServletContext()
  • String getInitParameter(String name)
  • Enumeration getInitParameterNames()

javax.servlet.ServletContextListener (Interface)

  • void contextInitialized(ServletContextEvent event)
  • void contextDestroyed(ServletContextEvent event)

javax.servlet.ServletContextEvent (Class)

  • ServletContext getServletContext()

javax.servlet.ServletContextAttributeListener (Interface)

  • void attributeAdded(ServletContextAttributeEvent event)
  • void attributeRemoved(ServletContextAttributeEvent event)
  • void attributeReplaced(ServletContextAttributeEvent event)

javax.servlet.ServletContextAttributeEvent (Class extends ServletContextEvent)

  • ServletContext getServletContext()
  • String getName()
  • Object getValue()

javax.servlet.ServletRequest (Interface)

  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • void removeAttribute(String name)
  • void setAttribute(String name, Object value)
  • String[] getParameterValues(String name)
  • String getParameter(String name)
  • Enumeration getParameterNames()
  • Map getParameterMap()
  • ServletInputStream getInputStream()
  • Reader getReader()
  • RequestDispatcher getRequestDispatcher(String path)
  • boolean isAsyncSupported()
  • boolean isAsyncStarted()
  • AsyncContext startAsync(ServletRequest, ServletResponse)
  • AsyncContext startAsync()
  • AsyncContext getAsyncContext()

javax.servlet.http.HttpServletRequest (Interface extends ServletRequest)

  • Enumeration getHeaders(String name)
  • String getHeader(String name)
  • int getIntHeader(String name)
  • long getDateHeader(String name)
  • String getAuthType()
  • String getRemoteUser()
  • Principal getUserPrincipal()
  • boolean isUserInRole(String role)
  • Cookie[] getCookies()
  • String getRequestedSessionId()
  • HttpSession getSession()
  • HttpSession getSession(boolean create)
  • boolean isRequestedSessionIdFromCookie()
  • boolean isRequestedSessionIdFromURL()
  • boolean isRequestedSessionIdValid()
  • Collection<Part> getParts()
  • Part getPart(String name)

javax.servlet.http.Part (Interface)[a part or form item that was received within a multipart/form-data POST request]

  • String getName()
  • long getSize()
  • String getContentType()
  • String getHeader(String name)
  • Collection<String> getHeaders(String name)
  • Collection<String> getHeaderNames()
  • InputStream getInputStream()
  • void write(String path)
  • void delete()

javax.servlet.ServletResponse (Interface)

  • ServletOutputStream getOutputStream()
  • PrintWriter getWriter()
  • void flushBuffer()
  • int getBufferSize()
  • boolean isCommitted()
  • void reset()
  • void resetBuffer()
  • void setBufferSize(int size)
  • void setCharacterEncoding(String enc)
  • String getCharacterEncoding()
  • void setContentType(String type)
  • String getContentType()
  • void setLocale(Locale locale)
  • Locale getLocale()
  • void setContentLength(int size)

javax.servlet.http.HttpServletResponse (Interface extends ServletResponse)

  • void addHeader(String name, String value)
  • void setHeader(String name, String value)
  • boolean containsHeader(String name)
  • void addIntHeader(String name, int value)
  • void setIntHeader(String name, int value)
  • void addDateHeader(String name, int value)
  • void setDateHeader(String name, int value)
  • void setStatus(int status)
  • void sendError(int code)
  • void sendError(int code, String message)
  • void sendRedirect(String path)
  • String encodeURL(String url)
  • String encodeRedirectURL(String url)
  • void addCookie(Cookie cookie)

javax.servlet.ServletRequestListener (Interface)

  • void requestInitialized(ServletRequestEvent event)
  • void requestDestroyed(ServletRequestEvent event)

javax.servlet.ServletRequestEvent (Class)

  • ServletContext getServletContext()
  • ServletRequest getServletRequest()

javax.servlet.ServletRequestAttributeListener (Interface)

  • void attributeAdded(ServletRequestAttributeEvent event)
  • void attributeRemoved(ServletRequestAttributeEvent event)
  • void attributeReplaced(ServletRequestAttributeEvent event)

javax.servlet.ServletRequestAttributeEvent (Class extends ServletRequestEvent)

  • String getName()
  • Object getValue()

javax.servlet.RequestDispatcher (Interface)

  • void forward(ServletRequest req, ServletResponse resp)
  • void include(ServletRequest req, ServletResponse resp)

javax.servlet.ServletRequestWrapper (Class implements ServletRequest)

  • public ServletRequestWrapper(ServletRequest encapsulatedReq)
  • ServletRequest getRequest()
  • void setRequest(ServletRequest encapsulatedReq)

javax.servlet.http.HttpServletRequestWrapper (Class extends ServletRequestWrapper implements HttpServletRequest)

public HttpServletRequestWrapper(HttpServletRequest wrappedReq)

 

javax.servlet.ServletResponseWrapper (Class implements ServletResponse)

  • public ServletResponseWrapper(ServletResponse encapsulatedResp)
  • ServletResponse getResponse()
  • void setResponse(ServletResponse encapsulatedResp)

javax.servlet.http.HttpServletResponseWrapper (Class extends ServletResponseWrapper implements HttpServletResponse)

  • public HttpServletResponseWrapper(HttpServletResponse wrappedResp)

javax.servlet.Filter (Interface)

  • void init(FilterConfig)
  • void destroy()
  • void doFilter(ServletRequest, ServletResponse, FilterChain)

javax.servlet.FilterChain (Interface)

  • void doFilter(ServletRequest, ServletResponse)

javax.servlet.FilterConfig (Interface)

  • ServletContext getServletContext()
  • String getInitParameter(String name)
  • Enumeration getInitParameterNames()
  • String getFilterName()

javax.servlet.AsyncContext (Interface)

  • ServletRequest getRequest()
  • ServletResponse getResponse()
  • boolean hasOriginalRequestAndResponse()
  • void setTimeout(long milliseconds) [<=0 to disable]
  • long getTimeout()
  • void start(Runnable task)
  • void dispatch(String path)
  • void dispatch(ServletContext context, String path)
  • void dispatch()
  • void complete()
  • <T extends AyncListener> T createListener(Class<T> clazz)
  • void addListener(AsyncListener l)
  • void addListener(AsyncLisnter l, ServletRequest request, ServletResponse response)

javax.servlet.AsyncListener (Interface)

  • void onStartAsync(AsyncEvent event)
  • void onComplete(AsyncEvent event)
  • void onTimout(AsyncEvent event)
  • void onError(AsyncEvent event)

javax.servlet.AsyncEvent (Class)

  • AsyncContext getAsyncContext()
  • Throwable getThrowable()
  • SerlvetRequest getSuppliedRequest()
  • ServletResponse getSuppliedResponse()

javax.servlet.http.HttpSession (Interface)

  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • void setAttribute(String name, Object value)
  • void removeAttribute(String name)
  • long getCreationTime()
  • String getId()
  • long getLastAccessedTime()
  • int getMaxInactiveInterval()
  • void invalidate()
  • boolean isNew()
  • void setMaxInactiveInterval(int timeoutSeconds) [0 times out at the end of req-res cycle, <0 never time out]
  • ServletContext getServletContext()

javax.servlet.http.HttpSessionListener (Interface)

  • void sessionCreated(HttpSessionEvent event)
  • void sessionDestroyed(HttpSessionEvent event)

javax.servlet.http.HttpSessionEvent (Class)

  • HttpSession getSession()

javax.servlet.http.HttpSessionActivationListener (Interface)

  • void sessionDidActivate(HttpSessionEvent event)
  • void sessionWillPassivate(HttpSessionEvent event)

javax.servlet.http.HttpSessionAttributeListener (Interface)

  • void attributeAdded(HttpSessionBindingEvent event)
  • void attributeRemoved(HttpSessionBindingEvent event)
  • void attributeReplaced(HttpSessionBindingEvent event)

javax.servlet.http.HttpSessionBindingEvent (Class extends HttpSessionEvent)

  • String getName()
  • Object getValue()

javax.servlet.http.HttpSessionBindingListener (Interface) [Implemented by classes bound into sessions as attributes]

  • void valueBound(HttpSessionBindingEvent event)
  • void valueUnbound(HttpSessionBindingEvent event)

javax.servlet.annotation.@WebServlet(

       boolean asyncSupported = false,

       String description = “”,

       String displayName = “”,

       String largeIcon = “”,

       String smallIcon = “”,

       int loadOnStartup = -1,

       String name = “”,

       String[] urlPatterns = {},

       String[] value = {},

       @WebInitParam[] initParams = {}

)

Note: value is the default element if no others are supplied, the same role as urlPatterns. (value XOR urlPatterns). If name is omitted, full qualified class name will apply

 

javax.servlet.annotation.@WebInitParam(

       String name,

       String value,

       String description = “”

)

 

javax.servlet.annotation.@MultiPartConfig(

       int fileSizeThreshold = 0,

long maxFileSize = -1L,

long maxRequestSize = -1L,

String location = “”

)

 

javax.servlet.annotation.@WebFilter(

       boolean asyncSupported = false,

       String description = “”,

String displayName = “”,

       String largeIcon = “”,

       String smallIcon = “”,

       String filterName = “”,

       String[] urlPatterns = {},

       String[] value = {},

       @WebInitParam[] initParams = {},

       String[] servletNames = {},

       DispatcherType[] dispatcherTypes = {DispatcherType.REQUEST}

)

Note: DispatcherType includes ASYNC, ERROR, FORWARD, INCLUDE, REQUEST

 

javax.servlet.annotation.@WebListener(

       value = “”

)

Note: value is the description of the listener

 

javax.annotation.@Resource(

       String description = “”,

       String name = “”,

       String mappedName = “”,

       Class type = Object.class,

       Resource.AuthenticationType authentication = CONTAINER,

       boolean shareable = true

)

Note: name is the JNDI name of the resource, appended to java:comp/env/; AuthenticationType includes CONTAINER, APPLICATION

 

javax.annotation.@PreDestroy, javax.annotation.@PostConstruct [used to annotate methods which run before an injection is removed or after a resource is injected.]

 

javax.ejb.@EJB(

       String description = “”,

       Class beanInterface = Object.class,

       String name = “”,

       String beanName = “”,

       String mappedName = “”,

       String lookup = “”

)

 

javax.persistence.@PersistenceUnit(

       String name = “”,

       String unitName = “”

)

Note: Expresses a dependency on an EntityManagerFactory and its associated persistence unit.

 

javax.persistence.@PersistenceContext(

       String name = “”,

       String unitName = “”

)

Note: Expresses a dependency on a container-managed EntityManager and its associated persistence context.

 

javax.servlet.annotation.@ServletSecurity(

       HttpConstraint value,

       HttpMethodConstraint[] httpMethodConstraints = {};

)

 

javax.servlet.annotation.@HttpMethodConstraint(

       String value, // required: the HTTP method name

       String[] rolesAllowed = {},

ServletSecurity.TransportGuarantee transportGuarantee = NONE | CONFIDENCIAL,

ServletSecurity.EmptyRoleSemantic emptyRoleSemantic = PERMIT | DENY;

)

 

javax.servlet.annotation.@HttpConstraint(

       String[] rolesAllowed = {},

ServletSecurity.TransportGuarantee transportGuarantee = NONE | CONFIDENCIAL,

ServletSecurity.EmptyRoleSemantic emptyRoleSemantic = PERMIT | DENY;

)