View RSS Feed


Working with JSP and Servlet

Rating: 1 votes, 1.00 average.
by , 04-03-2012 at 12:44 PM (8243 Views)
Suppose you are familiar with some beginner concepts regarding Servlet and Java Server Pages (JSP), this article focuses on some techniques for making JSP and Servlet working together in a Java web application.

A brief overview of Servlet and JSP technologies

A Servlet is a Java class running on a web server to serve clientís requests. Servlets are commonly used to handle HTTP requests. They are created to address shortcomings of CGI scripting, and enhance functionality of web servers by taking advantages of the Java platform to deliver dynamic content to client. Home page of Servlet technology is at:

JavaServer Pages (JSP) is a technology that enables dynamic content authoring by mixing HTML code and Java code together in one page, using JSP Standard Tag Library (JSTL) and Expression Language (EL). A JSP page is eventually translated into a Servlet. Home page of JSP technology is at:

Expression Language (EL) is a special expression that is embedded in JSPs to simplify some common tasks without writing scriptlet (Java code in JSP). EL expression is identified by ${ }.

JSTL is a set of common and standard tags that allows developers to use HTML-like tags to accomplish some common tasks without writing scriplet.

Both Servlet and JSP are the two key technologies that make up the Java Enterprise Edition (Java EE).

API and libraries for Servlet and JSP

The current version of Servlet specification is 3.0, and for JSP is 2.0 (in the family of Java EE version 6). The online API documentation can be found at:

The binary library files (JAR files) usually come with a Java EE-supported server installation such as Tomcat or GlassFish. Those files usually have servlet-api, jsp-apiÖ or something like in their names and reside in lib directory under serverís root.

To have your code complied with Servlet/JSP API, you need to add the JAR files to the projectís classpath, depend on scenario:

  • Project within IDE: you need to configure server runtime for the project, the IDE then automatically add serverís library JAR files to projectís classpath.
  • Project without IDE: you need to manually copy the library JAR files from serverís lib directory to your projectís lib directory.

For JSTL 1.2 library, you need to download the JAR files from:; JSTL 1.1 can be downloaded from:

Submit form from a JSP to a Servlet

To submit formís data in a JSP page to a Servlet, simply set the action attribute of <form> tag to the servletís URL. The URL must match the URL mapping specified in web.xml file and is relative to applicationís root.

For example, for this servlet defined in web.xml file:

XML Code: Servlet mapping in web.xml
The JSP form should look like this:

XML Code: Code of HTML form
    <form action="submitForm" method="post">
        Full Name: <input type="text" name="fullName" />
        // other stuff
Remember the formís method is handled by appropriate doXXX() method of the servlet, such as doGet(), doPost(), Ö

Parsing request parameters in Servlet

The HttpServletRequest interface has some methods that help retrieving values of parameters sent along with an HTTP request:

  • getParameter(String name): returns String value of a parameter specified by the given name, or null if the parameter does not exist.
  • getParameterValues(String name): returns an array of Strings for an array parameter (many parameters which have a same name).

Both of the methods are working with GET/POST parameters.

Get value of a text field

XML Code: HTML code
Full Name: <input type="text" name="fullName" />
Java Code: Java code
String fullName = request.getParameter("fullName");
Get selected value of radio buttons

XML Code: HTML code
        Color Option:
        <input type="radio" name="colorOption" value="red"/>Red&nbsp;
        <input type="radio" name="colorOption"/>Green&nbsp;
        <input type="radio" name="colorOption" value="blue"/>Blue&nbsp;
Java Code: Java code
String colorOption = request.getParameter("colorOption");
The return value is the value of the selected option, or ďonĒ if the value property is not specified for the selected option. If there is no option is selected, a null value returned.

Get selected value of dropdown lists

XML Code: HTML code
        Size Selection:
        <select name="sizeSelection">
            <option value="small">Small</option>
            <option value="medium">Medium</option>
            <option value="large">Large</option>
            <option>X Large</option>
Java Code: Java code
String sizeSelection = request.getParameter("sizeSelection");
Return value of the selected option, if the value property is not specified for an option, return the text enclosed between tags <option> and </option>.

Get selected values of check boxes

XML Code: HTML code
        Image Option:
        <input type="checkbox" name="imageOption">Resize&nbsp;
        <input type="checkbox" name="imageOption" value="convert">Convert&nbsp;
        <input type="checkbox" name="imageOption" value="transparent">Transparent&nbsp;
Java Code: Java code
String[] imageOption = request.getParameterValues("imageOption");
Return an array of String values for the selected check boxes. The array will be null if there is no check box is selected.

Get values of an array of fields

If there are multiple fields have a same name, the return value will be an array.

XML Code: HTML code
        File Name 1: <input type="text" name="fileName" /><br/>
        File Name 2: <input type="text" name="fileName" /><br/>
        File Name 3: <input type="text" name="fileName" /><br/>
Java Code: Java code
String[] fileNames = request.getParameterValues("fileName");
Get binary data (upload data)

For special case, you can use the ObjectInputStream object which is associated with the request to read binary data:

Java Code: Read bytes data from request's input stream
        InputStream ins = request.getInputStream();
        int read = 0;
        byte[] buffer = new byte[4096];
        while ((read = != -1) {
            // do something with the bytes read

Send response from servlet

To send HTML output to client, use the PrintWriter object which is associated with the response:

Java Code: Output HTML to client
        PrintWriter out = response.getWriter();
        out.println("<b>Thank you</b>");
Note that the content type should be set explicitly, so that the client can handle the response appropriately.

To send binary data to the client, use the ObjectOutputStream object which is associated with the response:

Java Code: Output byte data to client
        OutputStream outStream = response.getOutputStream();
        byte[] dataBytes = new byte[1024];
        // set data for byte array

Dispatching from a Servlet to a JSP page

Itís common to dispatch from a Servlet to a JSP page for rendering response, after the servlet has completed processing. For example, the following line of code will dispatch the response to a JSP page called result.jsp:

Java Code: Forward to a JSP page from within serlvet
request.getRequestDispatcher("result.jsp").forward(request, response);
This eliminates bored writings of HTML code within the servlet. Also, the request and response objects are also forwarded to the destination JSP page. To send data to the target JSP page, set attributes of the request as following:

Java Code:
request.setAttribute("message", "Thank you");
Then, the JSP page can access the passed object using scriptlet code or EL:

XML Code:
<h2><%=request.getAttribute("message") %></h2>

Include JSPís response in Servlet

Itís possible to include response of a JSP page into the servletís response:

Java Code:
request.getRequestDispatcher("include.jsp").include(request, response);
This way the JSPís response code can be mixed with the HTML code outputted by the servlet, and the JSP page can still access the request and response objects of the servlet.

Include JSP pages

A JSP page can be re-used in other JSP pages by using including mechanism. This can be done via the <jsp:include /> standard action. Letís consider a very popular scenario: a web application contains many pages which have the same layout structure (header, menu, content, footerÖ), so itís advisable to re-use header, menu, content, footerÖ across pages, for example:

XML Code: A JSP page that includes other JSP pages
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A JSP page that re-uses other JSP pages</title>
<jsp:include page="header.jsp" />
<jsp:include page="menu.jsp" />
<h1>Unique content of this page goes here...</h1>
<jsp:include page="footer.jsp" />
So the rule of design is, divide the pages into smaller and re-usable components as much as possible.

Using EL

Expression Language (EL) is a quick and easy way to accomplish common tasks in a JSP page without writing Java code (scriptlet) in JSP. For example, instead of writing this lengthy scriptlet:

XML Code:
<h2><%=request.getAttribute("message") %></h2>
Using EL is much simpler:

XML Code:
So the rule is, take advantages of the EL in JSP as much as possible, and avoid writing scriplet.

Working with JSTL

In addition to EL, JSTL can be used for more complex tasks without writing scriplet. JSTL is HTML friendly (using tags like HTML) and can be mixed with EL code. The common custom tag libraries provided by JSTL are: core, XML, internationalization, SQL and functions.
Remember to include appropriate taglib directives for JSTL at the top of JSP pages where JSTL is used. For example, this line indicates that the JSP page will use the core custom tags:

XML Code:
<%@ taglib prefix="c" uri="" %>
And following are other directives for those who donít want to remember the details:

XML Code:
<%@ taglib prefix="fmt" uri="" %>

<%@ taglib prefix="xml" uri="" %>

<%@ taglib prefix="sql" uri="" %>

<%@ taglib prefix="f" uri="" %>


Servlet and JSP are the two mainstream technologies that power the Java EE family, so understand those technologies and how to use them properly is very important. Though this article cannot cover all aspects of servlet and JSP, it has pointed out some common techniques which need to be considered when working with servlet and JSP.

Submit "Working with JSP and Servlet" to Facebook Submit "Working with JSP and Servlet" to Digg Submit "Working with JSP and Servlet" to Submit "Working with JSP and Servlet" to StumbleUpon Submit "Working with JSP and Servlet" to Google

Tags: jsp, servlet Add / Edit Tags
Servlet , JSP