使用JSP+Servlet的形式编写程序,输入日期,格式为YYYY-MM-DD,输出这个日期是星期几,javaweb作业自写;
jsp文件
Created by IntelliJ IDEA.
User: 17513
Date: 2021/11/3
Time: 16:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>输入一个日期判断星期几</title>
</head>
<body>
<form action="/week" method="post">
输入日期:<input type="text" name="date">(格式为YYYY-MM-DD)<br>
<input type="submit" value="提交">
</form>
</body>
</html>
Servlet文件
package Miderm;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@WebServlet(urlPatterns = {"/week"},name = "week")
public class week extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
request.setCharacterEncoding("gb2312");
String date=request.getParameter("date");
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Date d = null;
Calendar cal = Calendar.getInstance(); // 获取获取系统的当前日历对象
try {
d = f.parse(date);//使用parse()方法将字符串转换为日期
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(d);//设置日历的时间为给定的日期 d.
int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
if (w < 0)
w = 0;
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head></head><body>");
out.println(date+" : "+weekDays[w]);
out.println("</body></html>");
}
}
效果图