2、标准标签
标准标签比较多,主要功能为设置网页跳转、包含和JavaBean的处理等
有时也被称为动作Action
2、1 forward
意为将内容完全跳转到新的网页以替换当前的网页,注意此时的文件名称认为原来的文件名称,如index.jsp为:
<%@page c%>
<html>
<head>
</head>
<body>
<H1>欢迎来到JSP Web Site!</H1>
<HR>
<jsp:forward page="otherpage.jsp"/>
</body>
</html>
文件otherpage.jsp的内容为:
<table border="0" width="100%">
<tr>
<td bgcolor="#EEDDEE" width="100%">This is a other page!</td>
</tr>
</table>
显示的结果只有otherpage.jsp的内容,没有index.jsp的任何内容
注意:
跳转的网页既可以是jsp网页,也可以是一般的html网页,甚至是servlet,如下面的网页能够跳转到一个servlet中:
<%@page c%>
<html>
<head>
</head>
<body>
<jsp:forward page="/HTTPGetTime"/>
</body>
</html>
servlet为:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HTTPGetTime extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
PrintWriter output;
response.setContentType("text/html");
output=response.getWriter();
Date d=new Date();
output.println(d.toString());
output.close();
}
}
更加有效的方式还可以传送参数给servlet,其原因在于JSP和Servlet共享同一个请求对象。此时的网页为:
<%@page c%>
<html>
<head>
</head>
<body>
<jsp:forward page="/HTTPGetTime?number=000001"/>
</body>
</html>
带有处理参数的servlet为:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HTTPGetTime extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter output;
response.setContentType("text/html");
output = response.getWriter();
String str = request.getParameter("number");
output.println(str);
Date d = new Date();
output.println(d.toString());
output.close();
}
}
上述的跳转网页也可以使用下面的方式向servlet传递参数,如:
<%@page c%>
<html>
<head>
</head>
<body>
<jsp:forward page="/HTTPGetTime">
<jsp:param name="number" value="000002"/>
</jsp:forward>
</body>
</html>
当然这种传递参数的方式也可以向其他jsp网页传递参数,如发送参数的jsp网页为:
<%@page c%>
<html>
<head>
</head>
<body>
<jsp:forward page="otherpage.jsp">
<jsp:param name="sname" value="Tom"/>
<jsp:param name="snumber" value="000001"/>
</jsp:forward>
</body>
</html>
另一个接受参数的otherpage.jsp网页为:
<%
String s1=request.getParameter("sname");
String s2=request.getParameter("snumber");
out.println(s1+"<p>"+s2);
%>
注意:对于这种用法,也可以直接调用,如:
http://localhost:8088/myweb/otherpage.jsp?sname=Tom&snumber=00012
2、2 include
可以不仅包含静态页面,也可以包含动态页面,如:
<html>
<head>
</head>
<body>
<jsp:include page="header.jsp" flush="true"/>
<H1>JSP Web Site!</H1>
<HR>
<jsp:include page="foot.jsp" flush="true"/>
</body>
</html>
注意:flush="true"表示缓冲输出,否则默认情况下就会解释生成一句HTML就向客户端送一句
其中包含的header.jsp文件为:
<table border="0" width="100%">
<tr>
<td bgcolor="#EEDDEE" width="100%">This is a head!</td>
</tr>
</table>
包含的foot.jsp文件为:
<table border="0" width="100%">
<tr>
<td bgcolor="#DDEEDD" width="100%">
Current time is <%=(new java.util.Date()).toLocaleString()%>
</td>
</tr>
</table>
这个指令也可以传递参数,如:
<html>
<head>
</head>
<body>
<jsp:include page="header.jsp" flush="true"/>
<H1>JSP Web Site!</H1>
<HR>
<jsp:include page="foot.jsp?num=tom" flush="true"/>
</body>
</html>
此时的foot.jsp文件为:
<table border="0" width="100%">
<tr>
<td bgcolor="#DDEEDD" width="50%">
Current time is <%=(new java.util.Date()).toLocaleString()%>
</td>
<td bgcolor="#DDEEDD" width="50%">
<%=request.getParameter("num")%><P>
</td>
</tr>
</table>
也可以使用下面的参数传递方式,如:
<html>
<head>
</head>
<body>
<jsp:include page="header.jsp" flush="true" />
<H1>JSP Web Site!</H1>
<HR>
<jsp:include page="foot.jsp" flush="true">
<jsp:param name="num" value="tom" />
</jsp:include>
</body>
</html>
注意:@include和jsp:include存在区别,主要在于处理时间不一样,jsp:include在客户请求时才动态编译,而@include在编译JSP文件时就已经编译好
如index.jsp文件为:
<html>
<head>
</head>
<body>
<jsp:include page="otherpage.jsp" flush="true" />
<%@include file="otherpage.jsp" %>
<H1>JSP Web Site!</H1>
<%
int i = 0;
%>
</body>
</html>
otherpage.jsp文件为:
<%
int i=0;
%>
使用<%@include file="otherpage.jsp" %>会出错,编译引入产生重复变量定义
2、3 plugin
直接在网页中加入applet小程序,如:
<html>
<head>
</head>
<body>
<applet code="Exec.class" width="400" height="400"> </applet>
<jsp:plugin type="applet" code="Exec.class" codebase="."
width="400" height="400">
<jsp:fallback>
Plugin tag OBJECT or EMBED not supported by browser.
</jsp:fallback>
</jsp:plugin>
</body>
</html>
注意:
1)复制applet的class文件到网页的当前目录即可
2)更多的applet小程序可以在jsp-examples\plugin中找到,直接将目录applet全部拷贝至自己的目录即可
3 JSP环境配置
修改web.xml文件,可以给指定文件添加合适的页眉和页脚
<jsp-config>
<jsp-property-group>
<url-pattern>/*</url-pattern>
<include-prelude>/header.jsp</include-prelude>
<include-coda>/foot.jsp</include-coda>
</jsp-property-group>
</jsp-config>
此时所有的网页都会具有上述定义的页眉网页和页脚网页
注意:可能一位浏览器缓存的影响,不能及时看到,此时可以删除运行服务器,新建即可
4 JSTL
4、1 基本使用
例子1:
index.jsp文件:
<%@page c%>
<html>
<head>
<title>Select Your Portal</title>
</head>
<body>
<h1>Select your preferred portal:</h1>
<form action="showportal.jsp" method="get"><select
name="portchoice">
<option>news</option>
<option>weather</option>
<option>entertainment</option>
</select> <input type="submit" value="Select" /></form>
</body>
</html>
showportal.jsp文件:
<%@ page c%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<c:choose>
<c:when
test="<%=((String)request.getParameter("portchoice")).equals("news") %>">
<head>
<title>News Portal</title>
</head>
<body>
<h1>Welcome to the News Portal!</h1>
</body>
</c:when>
<c:when
test="<%=((String)request.getParameter("portchoice")).equals("weather") %>">
<head>
<title>Weather Portal</title>
</head>
<body>
<h1>You Get the Latest Weather!</h1>
</body>
</c:when>
<c:when
test="<%=((String)request.getParameter("portchoice")).equals("entertainment") %>">
<head>
<title>Entertainment Portal</title>
</head>
<body>
<h1>Entertainment News Just for You!</h1>
</body>
</c:when>
<c:otherwise>
<head>
<title>System Portal</title>
</head>
<body>
<h1>Application logic problem detected!</h1>
</body>
</c:otherwise>
</c:choose>
</html>
也可以写为EL的形式:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<c:choose>
<c:when test="${param.portchoice == 'news'}">
<head>
<title>News Portal</title>
</head>
<body>
<h1>Welcome to the News Portal!</h1>
</body>
</c:when>
<c:when test="${param.portchoice == 'weather'}">
<head>
<title>Weather Portal</title>
</head>
<body>
<h1>You Get the Latest Weather!</h1>
</body>
</c:when>
<c:when test="${param.portchoice == 'entertainment'}">
<head>
<title>Entertainment Portal</title>
</head>
<body>
<h1>Entertainment News Just for You!</h1>
</body>
</c:when>
<c:otherwise>
<head>
<title>System Portal</title>
</head>
<body>
<h1>Application logic problem detected!</h1>
</body>
</c:otherwise>
</c:choose>
</html>
此时仔细观察JSP的Servlet源代码即可发现EL的本质:
_jspx_th_c_when_0.setTest(((String)request.getParameter("portchoice")).equals("news") );
例子2:
index.jsp文件:
<%@page c%>
<html>
<head>
<title>Select Your Portal</title>
</head>
<body>
<table width="400">
<tr>
<td colspan="2" align="center"><b>Portal Selector</b></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td>
<form action="showportal.jsp" method="get">
<table>
<tr>
<td width="200">Portal Selection</td>
<td><select name="portchoice">
<option>news</option>
<option>weather</option>
<option>entertainment</option>
</select></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Select" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
showportal.jsp文件:
<%@ page c%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>System Portal-${param.portchoice}</title>
</head>
<body>
<c:choose>
<c:when test="${param.portchoice == 'news'}">
<jsp:include page="news.jsp" />
</c:when>
<c:when test="${param.portchoice == 'weather'}">
<jsp:include page="weather.jsp" />
</c:when>
<c:when test="${param.portchoice == 'entertainment'}">
<jsp:include page="entertain.jsp" />
</c:when>
<c:otherwise>
<h1>Application logic problem detected!</h1>
</c:otherwise>
</c:choose>
</body>
</html>
entertain.jsp文件:
<table width="600">
<tr>
<td>Entertainment News Just for You!</td>
</tr>
<tr>
<td><span> <jsp:useBean id="newsfeed"
class="data.NewsFeed" scope="request">
<jsp:setProperty name="newsfeed" property="topic"
value="entertainment" />
<jsp:getProperty name="newsfeed" property="value" />
</jsp:useBean> </span></td>
</tr>
</table>
weather.jsp文件:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table width="600">
<tr>
<td>You Get the Latest Weather!</td>
</tr>
<tr>
<td><jsp:useBean id="newsfeed" class="data.NewsFeed"
scope="request">
<jsp:setProperty name="newsfeed" property="topic" value="weather" />
</jsp:useBean>
<table>
<c:forEach items="${newsfeed.values}" var="row">
<tr>
<td width="200">${row.city}</td>
<td>${row.temp}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</table>
注意:
1)${newsfeed.values}也可以写为${newsfeed["values"]}
2)还可以使用诸如${newsfeed.values.上海}、${newsfeed.values["上海"]}等形式
news.jsp文件:
<table width="600">
<tr>
<td>Welcome to the News Portal!</td>
</tr>
<tr>
<td><span> <jsp:useBean id="newsfeed"
class="data.NewsFeed" scope="request">
<jsp:setProperty name="newsfeed" property="topic" value="news" />
<jsp:getProperty name="newsfeed" property="value" />
</jsp:useBean> </span></td>
</tr>
</table>
NewsFeed文件:
package data;
import java.util.ArrayList;
import java.util.HashMap;
public class NewsFeed extends Object implements java.io.Serializable {
private String topic;
private String value;
private ArrayList values;
public NewsFeed() {
}
public void setTopic(String topic) {
value = "";
values = null;
if (topic.equals("news")) {
value = "猪流感";
}
if (topic.equals("entertainment")) {
value = "刘老根";
}
if (topic.equals("weather")) {
values = new ArrayList();
HashMap tmap = new HashMap();
tmap.put("city", "曼谷");
tmap.put("temp", "30 C");
values.add(tmap);
tmap = new HashMap();
tmap.put("city", "莫斯科");
tmap.put("temp", "18 C");
values.add(tmap);
tmap = new HashMap();
tmap.put("city", "上海");
tmap.put("temp", "28 C");
values.add(tmap);
}
}
public String getValue() {
return this.value;
}
public ArrayList getValues() {
return this.values;
}
}
5 Expression Language
JSP网页中嵌入脚本的原因有:
1)为JSP执行提供流程控制
2)设置JSP网页的局部变量,并在以后访问
3)提供复杂的表达式(涉及Java类变量)的值
4)访问一个任意Java类变量的性质
5)调用JavaBean或者其他Java类变量的方法
使用JSTL可以有效处理前2个需求,而EL主要解决后3个需求
注意:EL并非和JSP紧密集成,而是可以应用于其他构造工具中,如JSF也可以使用EL
5、1 EL的基本使用
如直接嵌入在网页中:
<%@page c%>
<html>
<head>
</head>
<body>
<h1>Welcome! ${2+5}</h1>
</body>
</html>
或者作为标签的属性值:
<%@ page c%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
</head>
<body>
<c:if test="${100>1}">
<h1>100>1</h1>
</c:if>
</body>
</html>
更为复杂的变量处理形式:
<%@ page c%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
</head>
<body>
<c:set var="salary" value="2000" />
<c:if test="${pageScope.salary>1000}">
<h1>100>1</h1>
</c:if>
</body>
</html>
注意:即使此时没有定义变量,也不会报错
一个例子:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head>
<title>EL Expression Examples</title>
</head>
<body>
<h1>EL Expression Examples</h1>
<h2>Arithmetic Operators in Expressions</h2>
<c:set var="appleCount" value="${1 + 2 * 4 - 6 / 2}" />
<b>There are ${1 + 2 * 4 - 6 / 2} apples on the table.</b>
<br />
<b>There are <fmt:formatNumber pattern="00000"> ${1 + 2 * 4 - 6 / 2}</fmt:formatNumber>
apples on the table.</b>
<br />
<b>It feels like ${-4 - 8} degree today.</b>
<br />
<c:set var="myGrade" value="11" />
<br />
<b>The average grade is ${(myGrade == 10) ? "perfect" : "good"}. </b>
<br />
<b>There are ${23/54} remaining. </b>
<br />
<b>There are ${6 div 2} apples on the table.</b>
<br />
<b>There are ${2003 div 8} apples on the table.</b>
<br />
<b>There are ${2003 mod 8} apples on the table.</b>
<br />
<b>There are ${2003 % 8} apples on the table.</b>
<br />
<h2>Logical Operators</h2>
<c:set var="guess" value="12" />
<b>Your guess is ${guess}.</b>
<br />
<c:if test="${(guess >= 10) && (guess <= 20)}">
<b>You're in range!</b>
<br />
</c:if>
<c:if test="${(guess < 10) || (guess > 20)}">
<b>Try again!</b>
<br />
</c:if>
<c:set var="guess" value="1" />
<b>Your guess is ${guess}.</b>
<br />
<c:if test="${(guess >= 10) and (guess <= 20)}">
<b>You're in range!</b>
<br />
</c:if>
<c:if test="${(guess < 10) or (guess > 20)}">
<b>Try again!</b>
<br />
</c:if>
<h2>Comparison Operators</h2>
4 > '3' ${4 > '3'}
<br />
'4' > 3 ${'4' > 3}
<br />
'4' > '3' ${'4' > '3'}
<br />
4 >= 3 ${4 >= 3}
<br />
4 <= 3 ${4 < 3}
<br />
4 == '4' ${4 == 4}
<br />
<h2>empty Operator</h2>
empty "" ${empty ""}
<br />
empty "sometext" ${empty "sometext"}<br/> empty Junk ${empty Junk}
<br />
empty guess ${empty guess}
<br />
<h2>Boolean and Null Values</h2>
<c:set var="StrVar" value="true" />
<c:if test="${StrVar}">
equal!
</c:if>
<br />
null == null ${null == null}
<br />
"null" == null ${"null" == null}
<br />
</body>
</html>
注意:
<fmt:formatNumber pattern="#####"> ${1 + 2 * 4 - 6 / 2}</fmt:formatNumber>可以去除小数点
5、2 自定义函数的使用
在Web应用程序根目录下放置functions.tld文件,为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>
<shortname></shortname>
<info></info>
<function>
<description>Get an absolute value</description>
<name>abs</name>
<function-class>java.lang.Math</function-class>
<function-signature>int abs( int )</function-signature>
</function>
</taglib>
index.jsp文件为:
<%@page c%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="mt" uri="functions.tld"%>
<html>
<head>
</head>
<body>
<c:set var="num" value="-500"/>
The absolute value of ${num} is ${mt:abs(num)}
</body>
</html>
也可以自己定义相关类函数方法,如:
Time.java文件为:
package javabeans;
import java.text.SimpleDateFormat;
public class Time {
public static String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日HH点mm分ss秒");
String time = sdf.format(new java.util.Date());
return time;
}
}
注意,EL只能访问静态函数
functions.tld文件,为
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>
<shortname></shortname>
<info></info>
<function>
<description>Get current time</description>
<name>currentTime</name>
<function-class>javabeans.Time</function-class>
<function-signature>java.lang.String getTime( )</function-signature>
</function>
</taglib>
index.jsp文件为:
<%@page c%>
<%@ taglib prefix="mt" uri="functions.tld"%>
<html>
<head>
</head>
<body>
Now is ${mt:currentTime()}
</body>
</html>