Cookie
package Binggan;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieServer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Cookie cookie=null;
Cookie[] cookies = request.getCookies();
if (cookies!=null) {
for (Cookie cookie2 : cookies) {
if(cookie2.getName().equals("name")){
cookie=cookie2;
}
}
}
if(cookie==null){
cookie=new Cookie("name", "1");
response.addCookie(cookie);
response.getWriter().println("第一次来");
}else{
Integer valueOf = Integer.valueOf( cookie.getValue());
valueOf++;
response.getWriter().println("你是第"+valueOf+"次来");
cookie=new Cookie("name", valueOf+"");
response.addCookie(cookie);
}
//Cookie 只能存放String (key,value)
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
???没懂 你到底想说啥,让我们分析一下? 判断用户第几次上网站?
第一次访问页面的时候 放入了一个cookie(key是name value是1)。在次刷新页面的时候会获取到这个cookie,用key获取到value,将这个value+1 在次存放到cookie中,就会替换掉原来的cookie.每次刷新都会加一,在记录你访问了几次这个网址 这个可以在客户端修改cookie值欺骗服务器 存cookie的话,可以随便修改,清一下缓存什么的 就没了 这个记录次数为什么要放cookie中? 挺好的, 继续分享分享session啥的
页:
[1]