如何用bean写个日历
时间: 2024-02-26 10:59:01 浏览: 15
可以使用Java中的Calendar类来实现日历功能。下面是一个使用Java Bean写的简单日历:
```java
import java.util.Calendar;
public class CalendarBean {
private int year;
private int month;
private int day;
private int week;
public CalendarBean() {
Calendar calendar = Calendar.getInstance();
this.year = calendar.get(Calendar.YEAR);
this.month = calendar.get(Calendar.MONTH) + 1;
this.day = calendar.get(Calendar.DATE);
this.week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
}
```
在JSP页面中,可以通过使用JSTL标签库和EL表达式来使用这个Bean类,实现显示当前日期和月历的功能:
```jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Calendar</title>
</head>
<body>
<h1>Calendar</h1>
<p>Today is ${calendarBean.year}-${calendarBean.month}-${calendarBean.day}</p>
<table>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<c:forEach var="i" begin="1" end="${calendarBean.week}">
<td></td>
</c:forEach>
<c:set var="i" value="1"/>
<c:forEach var="j" begin="${calendarBean.week + 1}" end="7">
<td>${i}</td>
<c:set var="i" value="${i + 1}"/>
</c:forEach>
<c:forEach var="i" begin="${calendarBean.week + 8}" end="${calendarBean.week + 14}">
<tr>
<c:forEach var="j" begin="1" end="7">
<td>${i}</td>
<c:set var="i" value="${i + 1}"/>
</c:forEach>
</tr>
</c:forEach>
</table>
</body>
</html>
```
在这个JSP页面中,首先使用EL表达式获取当前日期,然后使用JSTL标签库中的<c:forEach>标签生成月历表格。月历表格中,使用<c:forEach>标签遍历每一行和每一列,使用EL表达式获取对应的日期,并显示在表格中。