java獲取前端頁面傳送的cookie中的資訊

渴睡人的眼發表於2018-06-13
package com.xalo.cookie;

import java.io.IOException;
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("/getcookie")
public class GetCookieServlet extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		//獲取cookie
		Cookie cookies[] = req.getCookies();
		
		PrintWriter out = resp.getWriter();
		if(cookies==null || cookies.length == 0){
			System.out.println("沒有cookie");
		}else{
			for (Cookie cookie : cookies) {
				out.write("----------------------------------------"+"<br>");
				
				
				//獲取cookie的解釋內容
				String comment = cookie.getComment();
				out.write("comment:"+comment+"<br>");
				
				//獲取cookie的鍵
				String key = cookie.getName();
				out.write("key:"+key+"<br>");
				
				//獲取cookie的值
				String value = cookie.getValue();
				out.write("value:"+value+"<br>");
				
				//獲取cookie的有效時間。
				int time = cookie.getMaxAge();
				out.write("time:"+time+"<br>");
				
				//獲取伺服器的IP對應的域名
				String domain = cookie.getDomain();
				out.write("domain:"+ domain+"<br>");
				
				//獲取有效路徑
				String path = cookie.getPath();
				out.write("path:"+ path+"<br>");
				
				//設定cookie是否加密,和https有關
//				cookie.setSecure(true);//預設為fale
//				cookie.getSecure();
				
			}
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

相關文章