文章目录
一、Cookie基本使用
二、Cookie原理 三、Cookie使用细节
一、Cookie基本使用
1、发送Cookie
package com. itheima. web. cookie ;
import javax. servlet. * ;
import javax. servlet. http. * ;
import javax. servlet. annotation. * ;
import java. io. IOException ;
import java. net. URLEncoder ;
@WebServlet ( "/aServlet" )
public class AServlet extends HttpServlet {
@Override
protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
Cookie cookie = new Cookie ( "username" , "zs" ) ;
response. addCookie ( cookie) ;
}
@Override
protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
this . doGet ( request, response) ;
}
}
2、获取Cookie
package com. itheima. web. cookie ;
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 ;
import java. io. IOException ;
import java. net. URLDecoder ;
@WebServlet ( "/bServlet" )
public class BServlet extends HttpServlet {
@Override
protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
Cookie [ ] cookies = request. getCookies ( ) ;
for ( Cookie cookie : cookies) {
String name = cookie. getName ( ) ;
if ( "username" . equals ( name) ) {
String value = cookie. getValue ( ) ;
value = URLDecoder . decode ( value, "UTF-8" ) ;
System . out. println ( name+ ":" + value) ;
break ;
}
}
}
@Override
protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
this . doGet ( request, response) ;
}
}
二、Cookie原理
三、Cookie使用细节
package com. itheima. web. cookie ;
import javax. servlet. * ;
import javax. servlet. http. * ;
import javax. servlet. annotation. * ;
import java. io. IOException ;
import java. net. URLEncoder ;
@WebServlet ( "/aServlet" )
public class AServlet extends HttpServlet {
@Override
protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
String value = "张三" ;
value = URLEncoder . encode ( value, "UTF-8" ) ;
System . out. println ( "存储数据:" + value) ;
Cookie cookie = new Cookie ( "username" , value) ;
cookie. setMaxAge ( 60 * 60 * 24 * 7 ) ;
response. addCookie ( cookie) ;
}
@Override
protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
this . doGet ( request, response) ;
}
}