當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSP和Servlet里的Cookie处理
生活随笔
收集整理的這篇文章主要介紹了
JSP和Servlet里的Cookie处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Cookie的設(shè)置方式
<% Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name",request.getParameter("last_name")); // cookie expire: 24 hours firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b><%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>瀏覽器里打開該jsp:http://localhost:9032/jerryjsp/main.jsp?first_name=Jerry&last_name=Wang
可以在Chrome開發(fā)者工具Application標(biāo)簽頁的Cookies區(qū)域查看到上述Java代碼在響應(yīng)結(jié)構(gòu)里設(shè)置的Cookie.
Cookie的讀取
新建一個(gè)jsp文件,源代碼如下:
<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>");for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>");}}else{out.println("<h2>No cookies founds</h2>");} %> </body> </html>瀏覽器打開,可以讀取出之前設(shè)置的cookie:
這個(gè)服務(wù)器端讀取到的Cookie是瀏覽器端發(fā)送給服務(wù)器并在服務(wù)器端解析的:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的JSP和Servlet里的Cookie处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个filter引起的404错误
- 下一篇: JSP的session处理