Working with JSP and Servlet
by , 04-03-2012 at 11:44 AM (3917 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: http://www.oracle.com/technetwork/ja...let/index.html
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: http://www.oracle.com/technetwork/ja...sp-138231.html
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: http://docs.oracle.com/javaee/6/api/
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: http://jstl.java.net/download.html; JSTL 1.1 can be downloaded from: http://jakarta.apache.org/taglibs/do...doc/intro.html
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:
The JSP form should look like this:XML Code: Servlet mapping in web.xml<servlet> <display-name>FormServlet</display-name> <servlet-name>FormServlet</servlet-name> <servlet-class>com.hainasoft.web.FormServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FormServlet</servlet-name> <url-pattern>/submitForm</url-pattern> </servlet-mapping>
Remember the form’s method is handled by appropriate doXXX() method of the servlet, such as doGet(), doPost(), …XML Code: Code of HTML form<form action="submitForm" method="post"> Full Name: <input type="text" name="fullName" /> // other stuff </form>
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 codeFull Name: <input type="text" name="fullName" />Get selected value of radio buttonsJava Code: Java codeString fullName = request.getParameter("fullName");
XML Code: HTML codeColor Option: <input type="radio" name="colorOption" value="red"/>Red <input type="radio" name="colorOption"/>Green <input type="radio" name="colorOption" value="blue"/>Blue 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.Java Code: Java codeString colorOption = request.getParameter("colorOption");
Get selected value of dropdown lists
XML Code: HTML codeSize Selection: <select name="sizeSelection"> <option value="small">Small</option> <option value="medium">Medium</option> <option value="large">Large</option> <option>X Large</option> </select>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>.Java Code: Java codeString sizeSelection = request.getParameter("sizeSelection");
Get selected values of check boxes
XML Code: HTML codeImage Option: <input type="checkbox" name="imageOption">Resize <input type="checkbox" name="imageOption" value="convert">Convert <input type="checkbox" name="imageOption" value="transparent">Transparent Return an array of String values for the selected check boxes. The array will be null if there is no check box is selected.Java Code: Java codeString[] imageOption = request.getParameterValues("imageOption");
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 codeFile 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/>Get binary data (upload data)Java Code: Java codeString[] fileNames = request.getParameterValues("fileName");
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 streamInputStream ins = request.getInputStream(); int read = 0; byte[] buffer = new byte[4096]; while ((read = ins.read(buffer)) != -1) { // do something with the bytes read } ins.close();
Send response from servlet
To send HTML output to client, use the PrintWriter object which is associated with the response:
Note that the content type should be set explicitly, so that the client can handle the response appropriately.Java Code: Output HTML to clientresponse.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<b>Thank you</b>"); out.println("<body>"); out.println("</html>");
To send binary data to the client, use the ObjectOutputStream object which is associated with the response:
Java Code: Output byte data to clientOutputStream outStream = response.getOutputStream(); byte[] dataBytes = new byte[1024]; // set data for byte array outStream.write(dataBytes);
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:
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: Forward to a JSP page from within serlvetrequest.getRequestDispatcher("result.jsp").forward(request, response);
Then, the JSP page can access the passed object using scriptlet code or EL:Java Code:request.setAttribute("message", "Thank you");
Include JSP’s response in ServletXML Code:<h2><%=request.getAttribute("message") %></h2> <h3>${requestScope.message}</h3>
It’s possible to include response of a JSP page into the servlet’s 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.Java Code:request.getRequestDispatcher("include.jsp").include(request, response);
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:
So the rule of design is, divide the pages into smaller and re-usable components as much as possible.XML Code: A JSP page that includes other JSP pages<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>A JSP page that re-uses other JSP pages</title> </head> <body> <jsp:include page="header.jsp" /> <jsp:include page="menu.jsp" /> <h1>Unique content of this page goes here...</h1> <jsp:include page="footer.jsp" /> </body> </html>
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:
Using EL is much simpler:XML Code:<h2><%=request.getAttribute("message") %></h2>
So the rule is, take advantages of the EL in JSP as much as possible, and avoid writing scriplet.XML Code:<h3>${requestScope.message}</h3>
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:
And following are other directives for those who don’t want to remember the details:XML Code:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
XML Code:<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="xml" uri="http://java.sun.com/jsp/jstl/xml" %> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/functions" %>
Conclusion
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.










Email Blog Entry
License4J 4.0
Today, 12:23 AM in Java Software