了解 Cookie
、Session
、Filter
和 Listener
是 Java Web 开发中非常重要的部分。
Cookie
是服务器在客户端浏览器上存储的小数据片段,用于在不同请求之间保持状态。Cookie
通常用于保存用户信息、跟踪会话、保存用户偏好等。
示例:创建和读取 Cookie
设置 Cookie(在 Servlet 中):
@WebServlet("/setCookie")
public class SetCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = new Cookie("username", "john_doe");
cookie.setMaxAge(60 * 60); // 1 hour
response.addCookie(cookie);
response.getWriter().write("Cookie has been set!");
}
}
读取 Cookie(在 Servlet 中):
@WebServlet("/getCookie")
public class GetCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
response.getWriter().write("Cookie value: " + cookie.getValue());
return;
}
}
}
response.getWriter().write("Cookie not found!");
}
}
Session
用于在服务器端保存与特定用户相关的信息,它可以跨多个请求和页面保持状态。每个用户都有一个唯一的 Session
对象,用于存储用户特定的数据,如登录状态、购物车信息等。
示例:创建和读取 Session
设置 Session 属性(在 Servlet 中):
@WebServlet("/setSession")
public class SetSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("username", "john_doe");
response.getWriter().write("Session attribute has been set!");
}
}
读取 Session 属性(在 Servlet 中):
@WebServlet("/getSession")
public class GetSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
String username = (String) session.getAttribute("username");
if (username != null) {
response.getWriter().write("Session value: " + username);
} else {
response.getWriter().write("Session attribute not found!");
}
} else {
response.getWriter().write("Session does not exist!");
}
}
}
Filter
用于在请求到达 Servlet 之前或响应发送到客户端之前对请求和响应进行处理。常用于日志记录、请求修改、身份验证等任务。
示例:创建一个简单的 Filter
用于记录请求时间
@WebFilter("/*")
public class LoggingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// Initialization code
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
long startTime = System.currentTimeMillis();
System.out.println("Request received at: " + startTime);
// Continue with the next filter or servlet
chain.doFilter(request, response);
long endTime = System.currentTimeMillis();
System.out.println("Response sent at: " + endTime);
System.out.println("Request processing time: " + (endTime - startTime) + " ms");
}
@Override
public void destroy() {
// Cleanup code
}
}
Listener
用于监听和响应特定的事件,如 Session
创建、销毁、请求生命周期等。常用于全局状态的管理和应用级的事件处理。
示例:创建一个 Session
监听器,记录 Session
的创建和销毁事件
@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created: " + se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session destroyed: " + se.getSession().getId());
}
}
Session
创建和销毁等。这些组件共同作用,帮助开发者管理和维护 Java Web 应用的状态和行为。