1、简单的使用
1、1 一个最为简单的JSP文件
不论手工来做,还是使用IDE只需建立下面文件并放入Web应用程序目录下即可,如:
<html>
<head>
</head>
<body>
<%
out.print("Hello!");
%>
</body>
</html>
http://localhost:8088/myweb/index.jsp
修改后无需重启Tomcat即可刷新看到新的结果
上述做法的真正代码是servlet代码,在编译执行JSP网页后,可以发现在<Tomcat>/work目录下存在新的java文件,里面就是一个servlet,名称为JSP文件名称加上“_jsp”后缀,它继承org.apache.jasper.runtime.HttpJspBase,而此类继承javax.servlet.http.HttpServlet。所以,里面有个_jspService方法,即包含JSP网页代码
1、2 JSP程序的部署配置
JSP程序也可以象servlet那样在web.xml中进行路径配置,如:
<servlet>
<servlet-name>exec</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>exec</servlet-name>
<url-pattern>/exec</url-pattern>
</servlet-mapping>
相应的jsp网页请求可以为:http://localhost:8088/myweb/exec
1、3 几个练习
时间显示之一:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<%=new java.util.Date()%>
</body>
</html>
时间显示之二:
<html>
<head>
<meta http-equiv = "refresh" c />
<title>A Simple JSP Example</title>
<style type = "text/css">
.big { font-family: helvetica, arial, sans-serif;
font-weight: bold;
font-size: 2em; }
</style>
</head>
<body>
<p class = "big">Simple JSP Example</p>
<table style = "border: 6px outset;">
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
<%= new java.util.Date() %>
</p>
</td>
</tr>
</table>
</body>
</html>
时间显示之三:
<%@page import="java.util.GregorianCalendar"%>
<%@page import="java.util.Date"%>
<%@page c%>
<html>
<head>
</head>
<body>
<h1>
<%
final int YEAR = 2050;
GregorianCalendar target = new GregorianCalendar();
target.set(target.YEAR, YEAR);
target.set(target.MONTH, 1);
target.set(target.DATE, 1);
target.set(target.AM_PM, 0);
target.set(target.HOUR, 0);
target.set(target.MINUTE, 0);
target.set(target.SECOND, 0);
Date Dtarget = (Date) target.getTime();
Date Dcurrent = new Date();
int i = Dtarget.compareTo(Dcurrent);
if (i == 1) {
long secs = Dtarget.getTime() - Dcurrent.getTime();
long days = (long) secs / (long) (1000 * 60 * 60 * 24);
//毫秒与天的换算
out.print("距离" + YEAR + "年还有" + days + "天!");
}
%>
</h1>
</body>
</html>
显示不同字体之一:
<%@page language="java"%>
<html>
<head></head>
<body>
<%
String str = "Welcome!";
int font_size = 0;
for (int i = 0; i < str.length(); i++) {
out.print("<font size=");
out.print(++font_size);
out.print(">");
out.print(str.substring(i, i + 1));
out.print("</font>");
}
%>
</body>
</html>
显示不同字体之二:
<%@page language="java"%>
<html>
<head>
</head>
<body>
<%
String str = "Welcome!";
int font_size = 0;
for (int i = 0; i < str.length(); i++) {
%>
<font size=<%=++font_size%>> <%=str.charAt(i)%></font>
<%
}
%>
</body>
</html>
1、4 输出星号三角形
<%@page language="java" c%>
<html>
<head>
</head>
<body style="font-family:宋体;font-size:28pt">
<%
final int lineCount = 3;
for (int c = 0; c < lineCount; c++) {
for (int d = 0; d < lineCount - 1 - c; d++)
out.print(" ");
for (int d = 0; d < (c + 1) * 2 - 1; d++)
out.print("*");
out.print("<br>");
}
%>
</body>
</html>
[此贴子已经被作者于2010-12-12 18:13:20编辑过]