JSP Demo

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:&nbsp;</td>
				<td><input type="text" name="firstName"
					value='<jsp:getProperty name="customer" property="firstName"/>'>
				</td>
			</tr>
			<tr>
				<td align="right">Last Name:&nbsp;</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:&nbsp;</td>
				<td><input type="text" name="firstName"
					value='<jsp:getProperty name="customer" property="firstName"/>'>
				</td>
			</tr>
			<tr>
				<td align="right">Last Name:&nbsp;</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:&nbsp;</td>
				<td><input type="text" name="firstName"
					value='<jsp:getProperty name="customer" property="firstName"/>'>
				</td>
			</tr>
			<tr>
				<td align="right">Last Name:&nbsp;</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
http://localhost:8080/jsp/main.jsp

 http://localhost:8080/jsp/secondary.jsp

 

 

 Demo05 - Unified Expression Language

CustomerBean.java

package org.fool.simplejsp.bean;

public class CustomerBean
{
	private String firstName;
	private String lastName;

	public CustomerBean()
	{
	}

	public CustomerBean(String firstName, String lastName)
	{
		this.firstName = firstName;
		this.lastName = lastName;
	}

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

	@Override
	public String toString()
	{
		StringBuffer sb = new StringBuffer();
		sb.append(firstName);
		sb.append(" ");
		sb.append(lastName);

		return sb.toString();
	}
}

 InitServlet.java

package org.fool.simplejsp.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.fool.simplejsp.bean.CustomerBean;

@WebServlet("/initservlet")
public class InitServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		CustomerBean customer1 = new CustomerBean("JSP", "Servlet");
		CustomerBean customer2 = new CustomerBean("Struts", "WebWork");
		CustomerBean customer3 = new CustomerBean("Hibernate", "MyBatis");
		CustomerBean customer4 = new CustomerBean("Hadoop", "MongoDB");
		CustomerBean customer5 = new CustomerBean("Groovy", "Grails");

		HttpSession session = request.getSession();

		this.getServletContext().setAttribute("customer1", customer1);
		session.setAttribute("customer2", customer2);
		request.setAttribute("customer3", customer3);

		List<CustomerBean> customerList = new ArrayList<>();

		customerList.add(customer4);
		customerList.add(customer5);

		session.setAttribute("customerList", customerList);

		request.getRequestDispatcher("unifexprlangdemo.jsp").forward(request,
				response);
	}

}

 unifexprlangdemo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<jsp:useBean scope="page" id="customer6"
	class="org.fool.simplejsp.bean.CustomerBean" />

<jsp:setProperty name="customer6" property="firstName" value="Spring" />
<jsp:setProperty name="customer6" 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>Unified Expression Language Demo</title>
</head>
<body>
	Customer attached to the application Scope:
	${applicationScope.customer1}
	<br>
	<br> 
	Customer attached to the session scope:
	${sessionScope.customer2.firstName} ${sessionScope.customer2.lastName}
	<br>
	<br> 
	Customer attached to the request scope:
	${requestScope.customer3}
	<br>
	<br> 
	Customer attached to the page scope: 
	${pageScope.customer6}
	<br>
	<br> 
	List of customers attached to the session:<br> 
	${sessionScope.customerList[0]}
	<br> 
	${sessionScope.customerList[1].firstName}
	${sessionScope.customerList[1].lastName}
	<br>
	<br>
</body>
</html>

 result

http://localhost:8080/jsp/initservlet


 

 Demo06 - Core JSTL tag library


 



Page scope is always the default.

A number of JSTL tags contain a var attribute to define a variable in a scope specified by a scope attribute. In all cases, if no scope is specified, the page scope is used by default.

The following example shows a JSP using some of the most common JSTL core tags

coretagdemo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.util.ArrayList"%>
<%
	ArrayList<String> nameList = new ArrayList<String>(4);
	nameList.add("Spring");
	nameList.add("Struts");
	nameList.add("Hibernate");
	nameList.add("Hadoop");
	request.setAttribute("nameList", nameList);
%>
<!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>Core Tag Demo</title>
</head>
<body>
	<c:set var="name" scope="page" value="${param.name}"></c:set>

	<c:out value="Hello"></c:out>

	<c:choose>
		<c:when test="${!empty name}">
			<c:out value="${name}"></c:out>
		</c:when>
		<c:otherwise>
			<c:out value="Stranger"></c:out>
			<br>
			<c:out value="Need a name? Here are a few options:" />
			<br>
			<ul>
				<c:forEach var="nameOption" items="${requestScope.nameList}">
					<li><c:out value="${nameOption}"></c:out></li>
				</c:forEach>
			</ul>
		</c:otherwise>
	</c:choose>

	<c:remove var="name" scope="page" />
</body>
</html>
 result

http://localhost:8080/jsp/coretagdemo.jsp


 http://localhost:8080/jsp/coretagdemo.jsp?name=MongoDB


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值