用MVC模式写一个通过form表单传入的日期计算出距离该年的12月31日的天数的java代码
时间: 2023-04-02 10:04:57 浏览: 108
好的,以下是用MVC模式写的通过form表单传入的日期计算出距离该年的12月31日的天数的java代码:
Model:
```java
public class DateModel {
private int year;
private int month;
private int day;
public DateModel(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getDaysToNewYear() {
LocalDate date = LocalDate.of(year, month, day);
LocalDate newYear = LocalDate.of(year, 12, 31);
return (int) ChronoUnit.DAYS.between(date, newYear);
}
}
```
View:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Days to New Year</title>
</head>
<body>
<h1>Days to New Year</h1>
<form action="/days-to-new-year" method="post">
<label for="year">Year:</label>
<input type="number" id="year" name="year" required><br><br>
<label for="month">Month:</label>
<input type="number" id="month" name="month" required><br><br>
<label for="day">Day:</label>
<input type="number" id="day" name="day" required><br><br>
<input type="submit" value="Calculate">
</form>
<br>
<div id="result">
<% if (daysToNewYear != null) { %>
<p>Days to New Year: <%= daysToNewYear %></p>
<% } %>
</div>
</body>
</html>
```
Controller:
```java
@WebServlet("/days-to-new-year")
public class DateController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int year = Integer.parseInt(request.getParameter("year"));
int month = Integer.parseInt(request.getParameter("month"));
int day = Integer.parseInt(request.getParameter("day"));
DateModel date = new DateModel(year, month, day);
int daysToNewYear = date.getDaysToNewYear();
request.setAttribute("daysToNewYear", daysToNewYear);
request.getRequestDispatcher("/WEB-INF/views/result.jsp").forward(request, response);
}
}
```
希望能够帮到你!
阅读全文