我在youtube上关于创建cookie的教程。我键入了正确的代码,但我在以下行中收到错误:
cookie = new Cookie("test_cookie", Long.toString(new Date().getTime()));
错误说:The constructor Date() is undefined.
当有人可以在视频中运行时,有谁知道我是如何得到此错误的:
https://www.youtube.com/watch?v=hOColvr3pl0
我猜应该有一个参数,或者? 最诚挚的问候Mads
package ExamplePackage;
import java.io.IOException;
import java.util.Date;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieUsageServlet")
public class CookieUsageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = getCookie(request, response);
printResponse(response, cookie);
}
private Cookie getCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = null;
Cookie[] cookiesArray = request.getCookies();
if(cookiesArray != null) {
for(int x = 0; x < cookiesArray.length; x++) {
if(cookiesArray[x].getName().equals("test_cookie")) cookie = cookiesArray[x];
}
}
if(cookie != null) {
System.out.println("cookie retrieved");
} else {
int timeToExpireCookie = new Integer(getServletContext().getInitParameter("time-to-expire-cookie")).intValue();
cookie = new Cookie("test_cookie", Long.toString(new Date().getTime()));
cookie.setMaxAge(timeToExpireCookie);
cookie.setPath(request.getContextPath()); // Sti til login
System.out.println("Cookie created...");
response.addCookie(cookie);
}
return cookie;
}
private void printResponse(HttpServletResponse response, Cookie cookie) throws IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
printWriter.println("<html>");
printWriter.println("<head><title>Cookie In JAVA servlet</title></head>");
printWriter.println("<body>");
printWriter.println("<cookie name: " + cookie.getName() + "<br>");
printWriter.println("<cookie value: " + cookie.getValue() + "<br>");
printWriter.println("<time to expire cookie in seconds: " + cookie.getMaxAge() + "<br>");
printWriter.println("</body>");
printWriter.println("</html>");
}
}
答案 0 :(得分:2)
您正在导入java.sql.Date
- 其中没有具有无参数构造函数。你的意思是java.util.Date
。
然而,根本不需要创建一个Date
对象,以便以毫秒为单位获取当前时间 - 自Unix-epoch以来:
cookie = new Cookie("test_cookie", Long.toString(System.currentTimeMillis());
(或者理想情况下,在代码中注入某种Clock
表示,这样您就可以更轻松地进行测试。)
答案 1 :(得分:2)
java.sql.Date
没有no-arg构造函数。
java.sql.Date
将其更改为java.util.Date
cookie = new Cookie("test_cookie", Long.toString(new java.util.Date().getTime()));