【六祎- Java】设置Cookie的访问路径,实现自动登录的功能
为什么要设置访问路径?
如果没有设置访问路径,默认是:当前web项目访问地址,即:request.getContextPath()
只有访问指定的路径,浏览器才将Cookie的数据发送给服务器。
如:实现自动登录的功能,只能访问登录页面的时候,才将Cookie中用户名和密码发送给服务器。
/*
设置Cookie的访问路径
*/
@WebServlet("/demo6")
public class Demo6PathServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//request.getContextPath():得到当前web访问地址
out.print("Cookie的访问路径是:" + request.getContextPath() + "/login.html");
//1.创建Cookie
Cookie cookie = new Cookie("username", "Jack");
//2.设置Cookie的访问路径
cookie.setPath(request.getContextPath() + "/login.html");
//3.将Cookie写到浏览器端
response.addCookie(cookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
本文来自博客园,作者:你好,Alf,转载请注明原文链接:https://www.cnblogs.com/Alf-/p/16192910.html