5) 创建ReadPropertyServlet,使用servletContext对象读取application.properties中的学院与班级信息并输出到控制台中。 6) 登录成功后显示上次登录时间(利用cookie技术)。
时间: 2024-06-05 19:06:20 浏览: 113
5) ReadPropertyServlet的代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadPropertyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
InputStream input = context.getResourceAsStream("/WEB-INF/application.properties");
Properties prop = new Properties();
prop.load(input);
String college = prop.getProperty("college");
String className = prop.getProperty("class_name");
System.out.println("College: " + college);
System.out.println("Class: " + className);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
6) 登录成功后显示上次登录时间的代码如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("admin")) {
HttpSession session = request.getSession();
Date lastLoginTime = (Date) session.getAttribute("lastLoginTime");
if (lastLoginTime != null) {
Cookie lastLoginCookie = new Cookie("lastLoginTime", lastLoginTime.toString());
response.addCookie(lastLoginCookie);
}
Date currentTime = new Date();
session.setAttribute("lastLoginTime", currentTime);
response.sendRedirect("home.jsp");
} else {
response.sendRedirect("login.jsp");
}
}
在home.jsp中可以添加以下代码来显示上次登录时间:
<%
Cookie[] cookies = request.getCookies();
String lastLoginTime = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("lastLoginTime")) {
lastLoginTime = cookie.getValue();
break;
}
}
}
if (lastLoginTime != null) {
out.println("Last Login Time: " + lastLoginTime);
}
%>
阅读全文