Integrate jScrollPane with GWT

  • Posted on: 21 May 2014
  • By: Zhijun Chen

jScrollPane is a cross-browser jQuery plugin which converts a browser's default scrollbars into an HTML structure which can be easily skinned with CSS. It is very helpful if you need a cross-browser style scrollbar.

If you build your web application using Google Web Toolkit (GWT), the easiest way to integrate jScrollPane is using JavaScript Native Interface (JSNI) feature of GWT. JSNI allows you to integrate JavaScript directly into your application's Java source code. The detail guide for JSNI in GWT can be found here.

Download jScrollPane and related files from here and include them inside your main page as follows:

  <link type="text/css" href="style/jquery.jscrollpane.css" rel="stylesheet" />
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src="script/jquery.mousewheel.js"></script>
  <script type="text/javascript" src="script/jquery.jscrollpane.min.js"></script>
  <script type="text/javascript">
    <!-- The following code will enable us to use jQuery as keyword instead of $ -->

Now that we are able to use jScrollPane, we can integrate it into GWT using the following JSNI code.

public native void initCustomScrollbar(String id) /*-{
    var settings = {
        autoReinitialise : true,
        horizontalDragMaxWidth : 0

    $wnd.jQuery('#' + id).jScrollPane(settings);

We need to set an id on GWT widget then call this method when it is needed (could be inside a GWT DeferredCommand):

FlowPanel scrollPanel = new FlowPanel();
// This method may be needed to put int a scheduler deferred command

Now you should be able to wrap all methods in jScrollPane through JSNI by access api as follows:

var api = $wnd.jQuery('#' + id).data('jsp');

Use CRest to consume RESTful Web Service for Android

  • Posted on: 20 April 2014
  • By: Zhijun Chen

There are several ways to consume RESTful web services from Android. One option would be using the builtin HttpClient library and parsing the response using an XML/Json parser library, e.g. Gson. After several hours research, I chose CRest Android version because of its simplicity. CRest is a lightweight JAX-RS compatible framework aiming to simplify the integration of external REST services into Java applications.

* Libraries required

The following libraries are required and should be put inside Android /libs folder. Maven dependencies are also available if you are using android maven plugin.

* RESTful Web Service Example and sample Response

Suppose we have a REST service GET call which simply returns the user with id:{id}?format=json. And the sample JSON response is given as follows.

  "id": 1,
  "first_name": "Zhijun",
  "last_name": "Chen",
  "name": "zhijun.chen"
* Java Model Objects

A Pojo is needed to map the JSON response into Java objects.


import org.codehaus.jackson.annotate.JsonProperty;

public class User {
	private Long id;
	private String firstName;
	private String lastName;
	private String name;
	public User() {
	public Long getId() {
		return id;

	public void setId(Long id) { = id;
	public String getFirstName() {
		return firstName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	public String getLastName() {
		return lastName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	public String getName() {
		return name;
	public void setName(String name) { = name;

Note: Any properties defined inside Java model but not in the JSON response should be annotated with @JsonIgnore

* Services Interfaces

Next we will create a service interface to consume the REST service.

import org.codegist.crest.annotate.Consumes;
import org.codegist.crest.annotate.EndPoint;
import org.codegist.crest.annotate.HeaderParam;
import org.codegist.crest.annotate.Path;
import org.codegist.crest.annotate.PathParam;


public interface UserService {
	@HeaderParam(value="Authorization", defaultValue="Basic {basic.auth.digest}")
	public User getUser(@PathParam("id") long id);

The @HeaderParam is needed when you need to add any http request header to the request, in this case it is an authentication token. @Consumes defines the type of response received from REST service. We will show how to pass in {basic.auth.digest} value.

* Android Integration

Now we have service interface ready, the final step would be integrated it into Android project. Android uses a seperate thread from main thread to execute http calls. And it is recommended to set CRest to use HttpClient to send requests. The following code gives an example.

private class FetchUserTask extends AsyncTask<Void, Void, User> {

			protected User doInBackground(Void... params) {
				String username = "username";
				String password = "password";
				String basicAuthDigest = Base64.encode(username + ":" + password);

				CRest crest = CRest.placeholder("basic.auth.digest", basicAuthDigest)
				UserService userService =;
				User user = userService.getUser(1);
				return user;

			protected void onPostExecute(User user) {
				// do something with the response

As you can see, the authentication code is passed in using placeholder.

Customize GNU Screen Terminal Title

  • Posted on: 6 April 2014
  • By: Zhijun Chen

GNU Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells.

To install Screen under Ubuntu, open a terminal and type in the following script.

sudo apt-get install screen

After installation, You can customize the terminal titles by creating a .screenrc file under your home directory and put the following code in the file.

termcapinfo xterm 'hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
termcapinfo xterm ti@:te@
shelltitle '$ |bash'

termcapinfo rxvt 'hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
termcapinfo rxvt ti@:te@

hardstatus on
hardstatus alwayslastline
hardstatus string "%{wk}%H%{Bk}|%{Mk}%?%-Lw%?%{km}[%n*%f %t]%?(%u)%?%{mk}%?%+Lw%? %=%{Bk}"

The effect of the code above will set the screen display as shown in the following picture.


Some useful keyboard combinations in Screen:

  • ctrl+a -> caps+a : Name the current terminal
  • ctrl+a -> number of window x : Switch to window x, e.g. ctrl+a 1
  • ctrl+a -> ctrl+a : Go back to the previous screen
  • ctrl+a -> [ : Enter copy mode, then you can scroll up and down in the current window, press q to exit
  • ctrl+a -> caps+s : Split display vertically
  • ctrl+a -> | : Split display horizontally
  • ctrl+a -> tab : Jump to next display region
  • ctrl+a -> caps+x : Remove current region
  • ctrl+a -> caps+q : Remove all regions but the current one

Hibernate Many To Many Annotation Mapping

  • Posted on: 29 March 2014
  • By: Zhijun Chen

In this blog I will use a simple 'Student' and 'Exam' example to demonstrate how to implement Hibernate Many to Many relationship mapping using annotations. 

* Database structure and schema

The database relationship is shown in the following diagram.

The corresponding mysql schema is shown as follows:

 CREATE TABLE `student` (
    `first_name` VARCHAR(50) NULL DEFAULT NULL,
    `last_name` VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)

    `name` VARCHAR(50) NOT NULL,
    `start_time` TIMESTAMP NOT NULL,
    PRIMARY KEY (`id`)

CREATE TABLE `student_exam` (
    `student_id` INT(11) NOT NULL,
    `exam_id` INT(11) NOT NULL,
    PRIMARY KEY (`student_id`, `exam_id`),
    KEY student_exam_student_key (student_id),
    KEY student_exam_exam_key (exam_id),
    CONSTRAINT student_exam_student_key FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT student_exam_exam_key FOREIGN KEY (`exam_id`) REFERENCES `exam` (`exam_id`) ON DELETE CASCADE ON UPDATE CASCADE
* Hibernate Model Classes

Two entity classes, Student and Exam, will be created to map database tables with annotations.


import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
public class Student {
    private Long id;
    private String firstName;
    private String lastname;
    private Set<Exam> exams = new HashSet<Exam>();
    public Student() {
    public void setId(Long id) {
 = id;

    public Long getId() {
          return id;

    public void setFirstName(String firstName) {
          this.firstName = firstName;

    public String getFirstName() {
          return firstName; 

   public void setLastName(String lastName) {
          this.lastName = lastName;
    public String getLastName() {
          return lastName; 

    public void setExams(Set<Exam> exams) {
          this.exams = exams;

    @ManyToMany(cascade = {CascadeType.ALL})
    public Set<Exam> getExams() {
          return exams;


import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
public class Exam {
    private Long id;
    private String name;
    private Date startTime;
    private Set<Student> students = new HashSet<Student>();
    public Exam() {

    public void setId(Long id) {
 = id;

    public Long getId() {
          return id;

    public void setName(String name) {
 = name;

    public String getName() {
          return name; 

    public void setStartTime(Date startTime) {
          this.startTime = startTime;

    public Date getStartTime() {
          return startTime;

    public void setStudents(Set<Student> students) {
          this.students = students;
    public Set<Student> getStudents() {
          return students;

@ManyToMany - is used to create many-to-many relationship between Student and Exam entites. The association can be unidirectional or bidirectional (in this case). The Student entity is the owning side.

@JoinTable - is used to define the join table for many-to-many relationship.

@JoinColumn - is used to define the join columns.

* Hibernate configuration file

 We need to put these two classes in hibernate.cfg.xml file.

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <mapping class="" />
        <mapping class="" />

Selenium WebDriver Parallel Testing with Selenium Grid 2, Jenkins and TestNG

  • Posted on: 17 November 2013
  • By: Zhijun Chen

Recently I've been working on setting up Webdriver parallel testing on a web app. The following guide will give you a brief walkthrough of the steps and technologies.

* WebDriver (Selenium 2.0)

WebDriver is the primary new feature in Selenium 2.0. It aims to better support dynamic web pages where elements of a page may change without the page itself being reloaded. Full documentation of Webdriver can be found here. A useful design pattern in Webdriver is Page Objects, which documentation can be found here. A Page Object simply models web page areas as objects within the test code. Suppose you have a simple login page as shown in the following code.

    <div>Username: </div>
    <div><input type="text" id="username" /></div>
    <div>Password: </div>
    <div><input type="password" id="password" /></div>
    <div><input type="button" id="login_button" value="Login" /></div>

and you would like to model the elements on that page as Java objects.

/* import statements*/

public class LoginPage {
    private By usernameLocator;
    private By passwordLocator;
    private By loginButtonLocator;
    private final WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    private void initLocators() {
       usernameLocator ="username");
       passwordLocator ="password");
       loginButtonLocator ="login_button");
    public LoginPage setUsername(String username) {
        WebElement usernameEl = driver.findElement(usernameLocator);
        return this;
    public LoginPage setPassword(String password) {
        WebElement passwordEl = driver.findElement(passwordLocator);
        return this;
    public HomePage clickLoginButton() {
        // Return a new page object representing the destination
        return new HomaPage(driver);

The page object class should only be responsible for elements on the page. All assertions should be made inside the tests. A simple login test can then be written as follows.

public void testLogin() {
   LoginPage loginPage = new LoginPage(driver);
   // some assertions here, e.g. Home page title

To improve stability of selenium tests, it is necessary to add WebDriverWait when using WebDriver.findElement method. You also need to make sure that the element is scrolled into view before you interact with it. This can be done through JavascriptExecutor in WebDriver.

((JavascriptExecutor) driver).executeScript("arguments[0]".scrollIntoView(true), element);

It's also helpful to catch StaleElementReferenceException and re-initialize the element.

* Selenium Grid 2

Selenium Grid facilitates Selenium tests by allowing users to:

  • scale by distributing tests on several machines
  • manager multiple environments from a central point, making it easy to run the tests against a vast combination of browsers/operation systems.
  • implement custom hooks to leverage virtual infrastructure for instance.

The following diagram shows the idea of Selenium Grid 2.


Here are the steps to set up the grid:

  • Download Selenium Grid standalone server from here.
  • Start Selenium Grid Server using the following command, by default the server will run on port 4444, you can have a look at the grid console on http://localhost:4444/grid/console
java -jar selenium-server-standalone-$version.jar -role hub
  • Register nodes using the following command. Note: For chrome you need to download ChromeDriver, and for IE you need to download IEDriverServer.
java -jar selenium-server-standalone-$version.jar$chromedriver_location$iedriver_location -role node -hub http://localhost:4444/grid/register

More information can be found here

After setting up the grid, you can now use RemoteWebDriver instead in your Selenium code as follows.

DesiredCapabilities capabilities = new DesiredCapabilities();
// disable native event
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);

When running Selenium tests under multiple browsers in the same machine, there will be browser focus issues. This will lead to test failures. Setting native vent to false will help in this case.

Alternatively, there are some decent Selenium cloud testing platforms available. One of them is Sauce Labs. They allow you to run Selenium tests on the cloud, and test on all possible browser/OS combinations, without having to install them on a local machine. Free plan is also available.

* TestNG

Integrating TestNG into Selenium tests is pretty straightforward. The main advantages of TestNG are parallel tests execution and the use of parameters. Most of the assertions and annotations are quite similar to JUnit. Information can be found here. One way to implement parallel testing in Selenium is to set browser and system as parameters as shown in the following code.

<!DOCTYPE suite SYSTEM "" >
<suite name="TestSuite" parallel="tests" thread-count="5"
  <test name="mac-chrome">
    <parameter name="browser" value="chrome" />
    <parameter name="platform" value="mac" />
      <class name="" />
  <test name="windows-chrome">
    <parameter name="browser" value="chrome" />
    <parameter name="platform" value="windows" />
      <class name="" />

The attribute parallel="tests" allows us to run same tests at the same time but using different parameters. The browser and platform can now pass in to the capability method as follows.

@Parameters({"browser", "platform"})
public DesiredCapabilities getCapabilities(String browser, String platform) {
   // code to initialize capabilities
* Jenkins

Two useful plugins can be used inside Jenkins to publish Selenium tests report.

It's very easy to set up, you just need to pass in the testng-results.xml file as the input. For Performance plugin, you can even pass in different result xml files generated under different browsers and systems.

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


  • <!-- 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 = “” version = “2.0”>, version is mandatory, should be 1.2 or 2.0, this element is optional in JSP 2.0.
  • Directive: < 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: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:forEach begin = “index1” end = “index2” step = “step_length”>



  • <c:forEach items = “collection_obj”>


</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


       [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 *.




























       <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>













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

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



















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










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

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





























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












       <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

























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)
  • getResource(String path)
  • 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)


       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



       String name,

       String value,

       String description = “”




       int fileSizeThreshold = 0,

long maxFileSize = -1L,

long maxRequestSize = -1L,

String location = “”




       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



       value = “”


Note: value is the description of the listener



       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.]



       String description = “”,

       Class beanInterface = Object.class,

       String name = “”,

       String beanName = “”,

       String mappedName = “”,

       String lookup = “”




       String name = “”,

       String unitName = “”


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



       String name = “”,

       String unitName = “”


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



       HttpConstraint value,

       HttpMethodConstraint[] httpMethodConstraints = {};




       String value, // required: the HTTP method name

       String[] rolesAllowed = {},

ServletSecurity.TransportGuarantee transportGuarantee = NONE | CONFIDENCIAL,

ServletSecurity.EmptyRoleSemantic emptyRoleSemantic = PERMIT | DENY;




       String[] rolesAllowed = {},

ServletSecurity.TransportGuarantee transportGuarantee = NONE | CONFIDENCIAL,

ServletSecurity.EmptyRoleSemantic emptyRoleSemantic = PERMIT | DENY;


CSS3 Properties To Make Site Look Prettier

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

Here are three useful CSS3 properties for prettifying websites. All of these properties will be supported by major browers like Chrome, Firefox.

* border-radius property

It used to be very diffcult to create round corners since we always needed to use multiple images and divs.
Now with border-radius property, you can easily create round-corners with pure CSS.


border-radius: 10px; 

or specify every corner as follows:

border-top-left-radius: 10px;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;


* box-shadow property

The box-shadow property attaches one or more drop-shadows to the box to make it look more 3D like.


box-shadow: 2px 3px 5px 2px #bbb;


* CSS3 background gradient property

With CSS3, you can now achieve background gradient effect by setting background property instead of using images.

Syntax (Linear Gradient from top to bottom):

/* fallback */

/* Safari 4-5, Chrome 1-9 */
background: -webkit-gradient(linear, 0%, 0%, 0% 100%, from(#7CDD0D), to(#272727))

/* Safari 5.1, Chrome 10+ */
background: -webkit-linear-gradient(top, #272727, #7CDD0D)

/* Firefox 3.6+ */
background: -moz-linear-gradient(top, #272727, #7CDD0D)

/* IE 10 */
background: -ms-linear-gradient(top, #272727, #7CDD0D)

/* Opera */
background: -o-linear-gradient(top, #272727, #7CDD0D)