进一步强化掌握 JSP 页面使用 Tag 文件,即向 Tag 文件传递对象, Tag 文件负责处理数据。
(1) Tag 文件 calendar . tag 负责显示日历。
(2)编写 JSP 页面 useCalendar . jsp ,要求 useCalendar . jsp 使用 Tag 标记使用 calendar . tag ,并将日期的年份和月份传递给 calendar . tag 。
(3)在 Tomcat 服务器的 webapps 目录下(比如, D :\ apache - tomcat -9.0.26\ webapps )新建一个名字是ch3_ practice _ two 的 Web 服务目录。把 useCalendar . jsp 文件保存到ch3_ practice _ two 目录中。在ch3_ practice _ two 目录下再建立目录结构:\ WEB - INF \ tags \practice2,将 calendar . tag 保存在practice2目录中。
(4)用浏览器访问 JSP 页面 useCalendar . jsp 。
useCalendar.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib tagdir = "/WEB-INF/tags" prefix = "getCalendar" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body bgcolor="#CCCFFF">
<getCalendar:calendar year = "2025" month = "2"/> <%-- 使用tag标记 --%>
</body>
</html>
calendar.tag:
<%@ tag language="java" pageEncoding="utf-8"%>
<%@ tag import="java.time.LocalDate"%>
<%@ tag import="java.time.DayOfWeek"%>
<%@ attribute name ="year" required="true" type="java.lang.String" %>
<%@ attribute name ="month" required="true" type="java.lang.String" %>
<%
int y = Integer.parseInt(year);
int m = Integer.parseInt(month);
LocalDate date = LocalDate.of(y,m,1);
int days = date.lengthOfMonth();
int space = 0;
DayOfWeek dayOfWeek = date.getDayOfWeek();
switch(dayOfWeek){
case SUNDAY:
space = 0;
break;
case MONDAY:
space = 1;
break;
case TUESDAY:
space = 2;
break;
case WEDNESDAY:
space = 3;
break;
case THURSDAY:
space = 4;
break;
case FRIDAY:
space = 5;
break;
case SATURDAY:
space = 6;
break;
}
String []calendar = new String[space + days];
for(int i=0;i<space;i++)
calendar[i] = "--";
for(int i=space,n=1;i<calendar.length;i++){
calendar[i] = String.valueOf(n);
n++;
}
%>
<h3><%= year %>年<%= month %>月的日历:</h3>
<table border=0>
<tr>
<th>星期日</th>
<th>星期一</th>
<th>星期二</th>
<th>星期三</th>
<th>星期四</th>
<th>星期五</th>
<th>星期六</th>
</tr>
<%
int n = 0;
while(n<calendar.length){
out.print("<tr>");
int increment = Math.min(7,calendar.length - n);
for(int i = n;i < n+increment;i++){
out.print("<td>"+calendar[i]+"</td>");
}
out.print("<tr>");
n = n+increment;
}
%>
</table>