In the early days, servlets were the only API available to develop server-side web applications in Java. Servlets had a number of advantages over CGI scripts, which were (and to some extent, still are) prevalent in those days. Some of the advantages of servlets over CGI scripts included increased performance and enhanced security.
However, servlets also had one major disadvantage. As the HTML code to be rendered in the browser needed to be embedded in Java code, most servlet code was very hard to maintain. To overcome this limitation, Java Server Pages (JSP) technology was created. JSPs use a combination of static HTML content and dynamic content to generate web pages. As the static content is separate from the dynamic content, JSP pages are a lot easier to maintain than servlets that generate HTML output.
1.Maven Dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.simplejsp</groupId> <artifactId>jsp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.0</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
2.Project Directory
3.Demo
demo01 - first.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Date"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Server Date And Time</title> </head> <body> <p>Server date and time: <% out.print(new Date()); %> </body> </html>
result
http://localhost:8080/jsp/first.jsp
Demo02 - JSP implicit objects
JSP implicit objects are objects that can be used in a JSP without having to be declared or initialized. They are actually declared and initialized behind the scenes by the application server when the JSP is deployed.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JSP</display-name> <servlet> <servlet-name>ImplicitObjectsJsp</servlet-name> <jsp-file>/implicitobjects.jsp</jsp-file> <init-param> <param-name>webxmlparam</param-name> <param-value>This is set in the web.xml file</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ImplicitObjectsJsp</servlet-name> <url-pattern>/implicitobjects.jsp</url-pattern> </servlet-mapping> </web-app>
implicitobjects.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Enumeration"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Implicit Objects Demo</title> </head> <body> <p>This page uses JSP Implicit objects to attach objects to the request, session, and application scopes.<br /> It also retrieves some initialization parameters sent in the web.xml configuration file.<br /> The third thing it does is get the buffer size from the implicit response object.<br /> </p> <p> <% application.setAttribute("applicationAttribute", new String( "This string is accessible accross sessions.")); session.setAttribute("sessionAttribute", new String( "This string is accessible accross requests")); request.setAttribute("requestAttribute", new String( "This string is accessible in a single request")); Enumeration<String> initParameterNames = config.getInitParameterNames(); out.println("Initialization parameters obtained from the implicit <br>"); out.println("config object:<br><br>"); while (initParameterNames.hasMoreElements()) { String parameterName = initParameterNames.nextElement(); out.print(parameterName + " = "); out.print(config.getInitParameter(parameterName)); out.print("<br>"); } out.println("<br/>"); out.println("Implicit object <b>page</b> is of type " + page.getClass().getName() + "<br><br>"); out.println("Buffer size is: " + response.getBufferSize() + " bytes"); %> </p> <p><a href="implicitobjects2.jsp">Click here to continue.</a></p> </body> </html>
implicitobjects2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Enumeration"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Sanity Check</title> </head> <body> <p> This page makes sure we can retrieve the application, session and request attributes set in the previous page. <br /> </p> <p> applicationAttribute value is: <%=application.getAttribute("applicationAttribute")%> <br> sessionAttribute value is: <%=session.getAttribute("sessionAttribute")%> <br> requestAttribute value is: <%=request.getAttribute("requestAttribute")%> <br> </p> <p> The following attributes were found at the application scope:<br><br> <% @SuppressWarnings("static-access") Enumeration<String> applicationAttributeNames = pageContext .getAttributeNamesInScope(pageContext.APPLICATION_SCOPE); while (applicationAttributeNames.hasMoreElements()) { out.println(applicationAttributeNames.nextElement() + "<br/>"); } %> </p> <p><a href="buggy.jsp">This hyperlink points to a JSP that will throw an exception.</a></p> </body> </html>
buggy.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Buggy JSP</title> </head> <body> <p> This text will never be seen in the browser since the exception will be thrown before the page renders. <% Object o = null; out.println(o.toString()); // NullPointerException thrown here. %> </p> </body> </html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <%@ page import="java.io.StringWriter"%> <%@ page import="java.io.PrintWriter"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>There was an error in the application</title> </head> <body> <h2>Exception caught</h2> <p>Stack trace for the exception is:<br /> <% StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); out.write(stringWriter.toString()); %> </p> </body> </html>
result
http://localhost:8080/jsp/implicitobjects.jsp
Clicking on the hyperlink at the bottom of the page takes us to implicitobjects2.jsp:
Notice how the value for the request attribute shows up as null. The reason for this is that when we clicked on the hyperlink on the previous page, a new HTTP request was created, therefore any attributes attached to the previous request were lost. If we had forwarded the request to this JSP, we would have seen the expected value on the browser window.
Finally, clicking on the hyperlink at the bottom of the page takes us to the buggy JSP, which does not render. Instead, control is transferred to error.jsp:
Nothing surprising is displayed here; we see the exception's stack trace as expected.
Demo03 - JSPs and JavaBeans
It is very easy to set and retrieve JavaBean properties with JSPs. A JavaBean is a type of Java class. In order for a class to qualify as a JavaBean, it must possess the following attributes:
• It must have a public constructor taking no arguments.
• Its variables must be accessed via getter and setter methods.
• It must implement java.io.Serializable.
• Although not a strict requirement, it's good coding practice to make all of JavaBean's member variables private.
CustomerBean.java
package org.fool.simplejsp.bean; public class CustomerBean { private String firstName; private String lastName; public CustomerBean() { } 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; } }
beanproperties1.jsp
<jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="firstName" value="Spring" /> <jsp:setProperty name="customer" property="lastName" value="MVC" />
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="firstName" value="Spring" /> <jsp:setProperty name="customer" property="lastName" value="MVC" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JavaBean Properties</title> </head> <body> <form> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td align="right">First Name: </td> <td><input type="text" name="firstName" value='<jsp:getProperty name="customer" property="firstName"/>'> </td> </tr> <tr> <td align="right">Last Name: </td> <td><input type="text" name="lastName" value='<jsp:getProperty name="customer" property="lastName"/>'> </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>
result
http://localhost:8080/jsp/beanproperties1.jsp
beanproperties2.jsp
<jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="firstName" param="fNm" /> <jsp:setProperty name="customer" property="lastName" param="lNm" />
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="firstName" param="fNm" /> <jsp:setProperty name="customer" property="lastName" param="lNm" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JavaBean Properties</title> </head> <body> <form> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td align="right">First Name: </td> <td><input type="text" name="firstName" value='<jsp:getProperty name="customer" property="firstName"/>'> </td> </tr> <tr> <td align="right">Last Name: </td> <td><input type="text" name="lastName" value='<jsp:getProperty name="customer" property="lastName"/>'> </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>
result
http://localhost:8080/jsp/beanproperties2.jsp?fNm=Spring&lNm=MVC
beanproperties3.jsp
<jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="*" />
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <jsp:useBean id="customer" class="org.fool.simplejsp.bean.CustomerBean" scope="page"></jsp:useBean> <jsp:setProperty name="customer" property="*" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JavaBean Properties</title> </head> <body> <form> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td align="right">First Name: </td> <td><input type="text" name="firstName" value='<jsp:getProperty name="customer" property="firstName"/>'> </td> </tr> <tr> <td align="right">Last Name: </td> <td><input type="text" name="lastName" value='<jsp:getProperty name="customer" property="lastName"/>'> </td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>
result
http://localhost:8080/jsp/beanproperties3.jsp?firstName=Spring&lastName=MVC
Demo04 - Reusing JSP content
When using JSPs to develop a web application, it is possible to define each of these areas in a single JSP, then include this JSP as a part of other JSPs. For example, we could have a JSP that renders the site's navigation menu, then have every other JSP include the navigation menu JSP to render the navigation menu. If the navigation menu needs to change, the change needs to be done only once. JSPs including the navigation menu JSP don't need to be changed.
There are two ways by which a JSP can be included in another JSP. It can be done via the <jsp:include> tag or via the include directive.
main.jsp
<%@ include file="navigation.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%!String pageName = "Main";%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Main Page</title> </head> <body> <table cellpadding="0" cellspacing="0" border="1" width="100%" height="100%"> <tr> <td width="100"><%@ include file="navigation.jsp"%> </td> <td>This is the main page.</td> </tr> </table> </body> </html>secondary.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%!String pageName = "Secondary";%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Secondary Page</title> </head> <body> <table cellpadding="0" cellspacing="0" border="1" width="100%" height="100%"> <tr> <td width="100"><%@ include file="navigation.jsp"%> </td> <td>This is the secondary page.</td> </tr> </table> </body> </html>navigation.jsp
<b>Application Menu</b> <ul> <li><a href="main.jsp">Main</a></li> <li><a href="secondary.jsp">Secondary</a></li> </ul> Current page: <%=pageName%>result