实现一个带有重复日程功能的 JavaWeb 日历
时间: 2023-12-15 17:07:01 浏览: 87
JavaWeb 实现多个文件压缩下载功能
下面是一个简单的 JavaWeb 日历的实现,包含了重复日程功能:
首先需要创建一个数据库表来存储日程信息:
```sql
CREATE TABLE `calendar` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`start_time` datetime NOT NULL,
`end_time` datetime NOT NULL,
`repeat_type` varchar(50) DEFAULT NULL,
`repeat_end_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
然后可以创建一个 JavaBean 来表示一个日程:
```java
public class Event {
private int id;
private String title;
private String description;
private Date startTime;
private Date endTime;
private RepeatType repeatType;
private Date repeatEndTime;
// getters and setters
}
public enum RepeatType {
NONE, DAILY, WEEKLY, MONTHLY, YEARLY
}
```
接下来创建一个 DAO 类来操作数据库:
```java
public class EventDAO {
private Connection conn;
public EventDAO(Connection conn) {
this.conn = conn;
}
public List<Event> getEvents(Date startDate, Date endDate) throws SQLException {
List<Event> events = new ArrayList<>();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM calendar WHERE start_time >= ? AND end_time <= ?");
stmt.setTimestamp(1, new Timestamp(startDate.getTime()));
stmt.setTimestamp(2, new Timestamp(endDate.getTime()));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Event event = new Event();
event.setId(rs.getInt("id"));
event.setTitle(rs.getString("title"));
event.setDescription(rs.getString("description"));
event.setStartTime(rs.getTimestamp("start_time"));
event.setEndTime(rs.getTimestamp("end_time"));
event.setRepeatType(RepeatType.valueOf(rs.getString("repeat_type")));
event.setRepeatEndTime(rs.getTimestamp("repeat_end_time"));
events.add(event);
}
rs.close();
stmt.close();
return events;
}
public void addEvent(Event event) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO calendar (title, description, start_time, end_time, repeat_type, repeat_end_time) VALUES (?, ?, ?, ?, ?, ?)");
stmt.setString(1, event.getTitle());
stmt.setString(2, event.getDescription());
stmt.setTimestamp(3, new Timestamp(event.getStartTime().getTime()));
stmt.setTimestamp(4, new Timestamp(event.getEndTime().getTime()));
stmt.setString(5, event.getRepeatType().name());
if (event.getRepeatEndTime() == null) {
stmt.setNull(6, Types.TIMESTAMP);
} else {
stmt.setTimestamp(6, new Timestamp(event.getRepeatEndTime().getTime()));
}
stmt.executeUpdate();
stmt.close();
}
public void updateEvent(Event event) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("UPDATE calendar SET title = ?, description = ?, start_time = ?, end_time = ?, repeat_type = ?, repeat_end_time = ? WHERE id = ?");
stmt.setString(1, event.getTitle());
stmt.setString(2, event.getDescription());
stmt.setTimestamp(3, new Timestamp(event.getStartTime().getTime()));
stmt.setTimestamp(4, new Timestamp(event.getEndTime().getTime()));
stmt.setString(5, event.getRepeatType().name());
if (event.getRepeatEndTime() == null) {
stmt.setNull(6, Types.TIMESTAMP);
} else {
stmt.setTimestamp(6, new Timestamp(event.getRepeatEndTime().getTime()));
}
stmt.setInt(7, event.getId());
stmt.executeUpdate();
stmt.close();
}
public void deleteEvent(int id) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("DELETE FROM calendar WHERE id = ?");
stmt.setInt(1, id);
stmt.executeUpdate();
stmt.close();
}
}
```
最后创建一个 Servlet 来处理请求:
```java
public class CalendarServlet extends HttpServlet {
private EventDAO eventDAO;
public void init() throws ServletException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/calendar?useUnicode=true&characterEncoding=utf-8", "root", "123456");
eventDAO = new EventDAO(conn);
} catch (ClassNotFoundException | SQLException e) {
throw new ServletException(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("list".equals(action)) {
listEvents(request, response);
} else if ("form".equals(action)) {
showEventForm(request, response);
} else if ("delete".equals(action)) {
deleteEvent(request, response);
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("add".equals(action)) {
addEvent(request, response);
} else if ("update".equals(action)) {
updateEvent(request, response);
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
}
private void listEvents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String startDateString = request.getParameter("start");
String endDateString = request.getParameter("end");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date startDate = dateFormat.parse(startDateString);
Date endDate = dateFormat.parse(endDateString);
List<Event> events = eventDAO.getEvents(startDate, endDate);
request.setAttribute("events", events);
request.getRequestDispatcher("/WEB-INF/views/calendar.jsp").forward(request, response);
} catch (ParseException | SQLException e) {
throw new ServletException(e);
}
}
private void showEventForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String idString = request.getParameter("id");
Event event = new Event();
if (idString != null) {
try {
int id = Integer.parseInt(idString);
event = eventDAO.getEvent(id);
} catch (NumberFormatException | SQLException e) {
throw new ServletException(e);
}
}
request.setAttribute("event", event);
request.getRequestDispatcher("/WEB-INF/views/eventForm.jsp").forward(request, response);
}
private void addEvent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Event event = getEventFromRequest(request);
try {
eventDAO.addEvent(event);
} catch (SQLException e) {
throw new ServletException(e);
}
response.sendRedirect(request.getContextPath() + "/calendar?action=list");
}
private void updateEvent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Event event = getEventFromRequest(request);
try {
eventDAO.updateEvent(event);
} catch (SQLException e) {
throw new ServletException(e);
}
response.sendRedirect(request.getContextPath() + "/calendar?action=list");
}
private void deleteEvent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String idString = request.getParameter("id");
if (idString != null) {
try {
int id = Integer.parseInt(idString);
eventDAO.deleteEvent(id);
} catch (NumberFormatException | SQLException e) {
throw new ServletException(e);
}
}
response.sendRedirect(request.getContextPath() + "/calendar?action=list");
}
private Event getEventFromRequest(HttpServletRequest request) throws ServletException, IOException {
String idString = request.getParameter("id");
String title = request.getParameter("title");
String description = request.getParameter("description");
String startString = request.getParameter("start");
String endString = request.getParameter("end");
String repeatTypeString = request.getParameter("repeat_type");
String repeatEndString = request.getParameter("repeat_end");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Event event = new Event();
if (idString != null) {
try {
int id = Integer.parseInt(idString);
event.setId(id);
} catch (NumberFormatException e) {
throw new ServletException(e);
}
}
event.setTitle(title);
event.setDescription(description);
try {
Date start = dateFormat.parse(startString);
event.setStartTime(start);
} catch (ParseException e) {
throw new ServletException(e);
}
try {
Date end = dateFormat.parse(endString);
event.setEndTime(end);
} catch (ParseException e) {
throw new ServletException(e);
}
if (repeatTypeString != null) {
RepeatType repeatType = RepeatType.valueOf(repeatTypeString.toUpperCase());
event.setRepeatType(repeatType);
}
if (repeatEndString != null && !repeatEndString.isEmpty()) {
try {
Date repeatEnd = dateFormat.parse(repeatEndString);
event.setRepeatEndTime(repeatEnd);
} catch (ParseException e) {
throw new ServletException(e);
}
}
return event;
}
}
```
最后在 web.xml 中配置 Servlet 映射:
```xml
<servlet>
<servlet-name>calendarServlet</servlet-name>
<servlet-class>com.example.calendar.CalendarServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>calendarServlet</servlet-name>
<url-pattern>/calendar</url-pattern>
</servlet-mapping>
```
这样就完成了一个简单的带有重复日程功能的 JavaWeb 日历。
阅读全文