face="CourIEr New">大家總是不喜歡看到<%和%>在JSP頁面上,其實我們可以使用比較優雅的XML方式來表達
1,隱含的注釋
JSP語法:<%-- 內容 --%>
XML語法:無
2,變量或函數的聲明
JSP語法:<%! declaration;[declaration;]+... %>
例如:
<%!
int i=0;
int a,b,c;
Color red=
new Color(255,0,0);
private static final String OK="ok";
public String getAnswer(){
return OK;
}
%>
XML語法:
<JSP:declaration>
declartion;[declaration;]+...
</JSP:declaration>
例如:
<JSP:declaration>
int i=0;
int a,b,c;
Color red=
new Color(255,0,0);
private static final String OK="ok";
public String getAnswer(){
return OK;
}
</JSP:declaration>
3,表達式
JSP語法:<%=expression%>
例如:
<%=Math.round(Math.random*100)%>
XML語法:
<JSP:expression>
expression
</JSP:expression>
例如:
<JSP:expression>
Math.round(Math.random*100)
</JSP:expression>
4,代碼片斷
JSP語法:<% your Java code %>
例如:
<%
String username=request.getParameter("username").trim();
String password=request.getParameter("passWord").trim();
%>
XML語法:
<JSP:scriptlet>
your Java code
</JSP:scriptlet>
例如:
<JSP:scriptlet>
String username=request.getParameter("username").trim();
String password=request.getParameter("passWord").trim();
</JSP:scriptlet>
5,指令:include
JSP語法:<%@include file="relativeURL"%>
例如:<%@include file="static_head.Html"%>
XML語法:<JSP:directive.include file="relativeURL"/>
例如:<JSP:directive.include file="static_head.Html"/>
6,指令:page
JSP語法:<%@page attribtes%>
例如:<%@page
import="Java.util.HashMap"%>
XML語法:<JSP:directive.page attribute/>
例如:<JSP:directive.page
import="Java.util.HashMap"/>
7,指令:taglib
JSP語法:<%@taglib uri="URIForLibrary" prefix="tagPrefix"%>
XML語法:無
對於JSP操作而言,本來就是XML格式。
下面使用XML表達方式書寫一個JSP頁面
example.JSP
<JSP:directive.page contentType="text/Html;charset=GBK" />
<JSP:directive.page
import="java.util.*,Java.text.*" />
<JSP:declartion>
public String getCustomDate(Date,date,String pattern){
SimpleDateFormat format=
new SimpleDateFormat();
format.applyPattern(pattern);
return format.format(date);
}
</JSP:declartion>
<JSP:scriptlet>
Date date=(Date)request.getAttribute("date");
String dateStr=getCustomDate(date,"yyyy-MM-dd,hh:mm:ss");
</JSP:scriptlet>
<div style="font-size:11pt">
顯示時間:<JSp:expression>dateStr</JSP:expression>
</div>