【六禕- 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);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章