JavaWeb基础——Cookie和Session

1、什么是Cookie和Session

什么是会话?
JavaWeb基础——Cookie和Session_第1张图片
JavaWeb基础——Cookie和Session_第2张图片
2、Cookie技术
JavaWeb基础——Cookie和Session_第3张图片

创建Cookie

package cn.itcast.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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;

/**
 * Servlet implementation class CookieDemo1
 */
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        out.print("您上次访问的时间是:");

        //获得用户的时间cookie
        Cookie cookies[]=request.getCookies();//创建Cookie,返回一个数组,Cookie最多保存300个
        for(int i=0;cookies!=null && iif(cookies[i].getName().equals("lastAccessTime")) {
                long cookieValue=Long.parseLong(cookies[i].getValue());//cookies[i].getValue()返回的是字符串
                Date date=new Date(cookieValue);
                out.print(date.toLocaleString());
            }
        }
        //给用户回送最新的访问时间
        Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(1*30*24*3600);//设置最大的cookie保存时间


        /*cookie.setPath()此处的参数,是相对于应用服务器存放应用的文件夹的根目录而言的(比如tomcat下面的webapp),
         * 因此cookie.setPath("/");之后,可以在webapp文件夹下的所有应用共享cookie,
         * 而cookie.setPath("/webapp_b/");是指cas应用设置的cookie只能在webapp_b应用下的获得,
         * 即便是产生这个cookie的cas应用也不可以。
         * 
         * 
         * */
        cookie.setPath("/day2");//获取cookie的访问地
        response.addCookie(cookie);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

删除Cookie

CookieDemo2.java

package cn.itcast.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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;

/**
 * 点击超链接删除该Cookie记录
 */
@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        out.print("清除上次访问时间
"
); out.print("您上次访问的时间是:"); //获得用户的时间cookie Cookie cookies[]=request.getCookies(); for(int i=0;cookies!=null && iif(cookies[i].getName().equals("lastAccessTime")) { long cookieValue=Long.parseLong(cookies[i].getValue()); Date date=new Date(cookieValue); out.print(date.toLocaleString()); } } //给用户会送最新的访问时间 Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+""); cookie.setMaxAge(1*30*24*3600);//设置最大的cookie保存时间 cookie.setPath("/day2"); response.addCookie(cookie); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

CookieDemo2_1.java

package cn.itcast.cookie;

import java.io.IOException;
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;

/**
 * Servlet implementation class CookieDemo2_1
 */
@WebServlet("/CookieDemo2_1")
public class CookieDemo2_1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie=new Cookie("lastAccessTime",System.currentTimeMillis()+"");//相当于覆盖,但设置Cookie存储期限为0由此达到删除目的
        cookie.setMaxAge(0);
        cookie.setPath("/day2");
        response.addCookie(cookie);



    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Cookie案例——显示历史清单

Demo1.java

package cn.itcast.cookieAplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

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;

/**
 * Servlet implementation class Demo1
 */
@WebServlet("/Demo1")
public class Demo1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        //1、输出网站所有商品
        out.write("本网站有如下商品:
"
); Mapmap=Db.getAll(); for(Map.Entryentry:map.entrySet()) { Book book=entry.getValue(); out.print(""+book.getName()+"
"); }//每一个都是超链接 //2、显示用户曾经看过的商品 out.print("
您曾经看过的商品:
"
); Cookie cookies[]=request.getCookies(); for(int i=0;cookies!=null && iif(cookies[i].getName().equals("bookHistory")) { String ids[]=cookies[i].getValue().split("\\,"); for(String id:ids) { Book book=(Book)Db.getAll().get(id); out.print(book.getName()+"
"
); } } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } class Db{ private static Map map=new LinkedHashMap(); static { map.put("1", new Book("1","javaweb开发","老张","一本好书")); map.put("2", new Book("2","jdbc开发","老张","一本好书")); map.put("3", new Book("3","spring开发","老黎","一本好书")); map.put("4", new Book("4","struts开发","老毕","一本好书")); map.put("5", new Book("5","android开发","老黎","一本好书")); } public static Map getAll() { return map; } } class Book{ public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, String description) { super(); this.id = id; this.name = name; this.author = author; this.description = description; } private String id; private String name; private String author; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }

Demo2.java

package cn.itcast.cookieAplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;

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;

/**
 * 显示商品详细信息的Servlet
 */
@WebServlet("/Demo2")
public class Demo2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        //1、根据用户带过来的id,显示相应商品的详细信息
        String id=request.getParameter("id");
        Book book=(Book)Db.getAll().get(id);
        out.write(book.getId()+"
"
); out.write(book.getName()+"
"
); out.write(book.getDescription()+"
"
); out.write(book.getAuthor()+"
"
); //2、构建cookie,回写给浏览器 String cookieValue=buildCookie(id,request); Cookie cookie=new Cookie("bookHistory",cookieValue); cookie.setMaxAge(1*30*24*3600); cookie.setPath("/day2"); response.addCookie(cookie); } private String buildCookie(String id, HttpServletRequest request) { // TODO Auto-generated method stub //bookHistory=null 1 1 //bookHistory=2,5,1 1 1,2,5 //bookHistory=2,5,4 1 1,2,5 //bookHistory=2,5 1 1,2,5 String bookHistory=null; Cookie cookies[]=request.getCookies(); for(int i=0;cookies!=null && iif(cookies[i].getName().equals("bookHistory")) { bookHistory=cookies[i].getValue(); } } if(bookHistory==null) { return id; } LinkedList list=new LinkedList(Arrays.asList(bookHistory.split("\\,"))); /* if(list.contains(id)) { //bookHistory=2,5,1 1 1,2,5 list.remove(id); list.addFirst(id); }else { //bookHistory=2,5,4 1 1,2,5 if(list.size()>=3) { list.removeLast(); list.addFirst(id); }else { //bookHistory=2,5 1 1,2,5 list.addFirst(id); } } */ if(list.contains(id)) { list.remove(id); }else { if(list.size()>=3) { list.removeLast(); } } list.addFirst(id); StringBuffer sb=new StringBuffer(); for(String bid:list) { sb.append(bid+","); } return sb.deleteCharAt(sb.length()-1).toString(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

3、Session
JavaWeb基础——Cookie和Session_第4张图片
JavaWeb基础——Cookie和Session_第5张图片

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
    <a href="SessionDemo1">购买a>
    <a href="SessionDemo1_1">结账a>
body>
html>

example1

解决禁用Cookie的解决方案

package cn.itcast.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 禁用Cookie的解决方案
 */
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        String url1=response.encodeURL("SessionDemo1");//URL重写,在后面自动跟上session的id号
        String url2=response.encodeURL("SessionDemo1_1");//若没有禁用cookie则不会重写URL,没有就会自动重写URL

        out.print("购买");
        out.print("结账");

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

购买servlet

package cn.itcast.session;

import java.io.IOException;
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 javax.servlet.http.HttpSession;

/**
 * 购买的Servlet
 * 
 * Session的生命周期:
 * 当访问程序时,程序里面调用了getSession时Session生
 * 当会话关闭(不关,但当30分钟后也会死,这个时间可以在web.xml中通过session-config设置)后30分钟,Session才结束,它是由服务器管的
 * 
 * 
 */
@WebServlet("/SessionDemo1")
public class SessionDemo1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();//有session就不创建,没session就创建
        //下面的代码依据Session原理,回写sessionid到cookie中,并保持与session同样的有效期
        //能解决关闭浏览器后,仍可获取到sessionid
        String sessionid=session.getId();//获取session的id
        //将sessionid以cookie的方式存在磁盘中,有效期为30min
        Cookie cookie=new Cookie("JSESSIONID",sessionid);
        cookie.setPath("/day2");
        cookie.setMaxAge(30*60);



        session.setAttribute("name", "洗衣机");

    //  request.getSession(false);//不创建session,只获取session

    //  session.invalidate();//这句话也能摧毁session
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

结账servlet

package cn.itcast.session;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 结账的Servlet,如果另外再开一个浏览器访问结账是拿不到的,它只为一个会话服务。
 */
@WebServlet("/SessionDemo1_1")
public class SessionDemo1_1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        HttpSession session=request.getSession();
        String product=(String)session.getAttribute("name");
        out.write("您购买的商品是:"+product);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

example2

login.html


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
    <form action="LoginServlet" method=post>
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        <input type="submit" value="登陆">    

    form>
body>
html>

User.java

package cn.itcast.session;

public class User {
    private String username;
    private String password;

    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

LoginServlet.java

package cn.itcast.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        String username=request.getParameter("username");
        String password=request.getParameter("password");

        Listlist=DB.getAll();
        for(User user:list) {
            if(user.getUsername().equals(username) && user.getPassword().equals(password)) {
                request.getSession().setAttribute("user",user);//登陆成功,向session中存入一个登陆标识
                response.sendRedirect("LoginIndex.jsp");
                return;
            }
        }
        out.write("用户名或密码不对!!");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}


class DB{

    public static List list=new ArrayList();
    static {
        list.add(new User("aaa","123"));
        list.add(new User("bbb","123"));
        list.add(new User("ccc","123"));
    }
    public static List getAll() {
        return list;
    }
}

LoginIndex.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
    欢迎您:$(User.username) <a href="">登陆a><br/>
    <a href="LogoutServlet">退出登录a>
    <br/><br/><br/>
body>
html>

LogoutServlet.java

package cn.itcast.session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 完成用户注销
 */
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession(false);
        if(session==null) {
            response.sendRedirect("login.html");
            return;
        }
        session.removeAttribute("user");
        response.sendRedirect("login.html");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

example3(购买书籍、禁用cookie、关闭浏览器的应用)

Session1

package cn.itcast.sessionAplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 代表网站首页,列出所有书
 */
@WebServlet("/Session1")
public class Session1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.print("本网站有如下商品:
"
); request.getSession();//只有在此处得到了session,才能在response.encodeURL()中得到session的Id号 Mapmap=Db.getAll(); for(Map.Entryentry:map.entrySet()) { Book book=entry.getValue(); //out.print(book.getName()+"购买
");
//用于解决禁用Cookie的写法 String url=response.encodeURL("BuyServlet?id="+book.getId()); out.print(book.getName()+"购买
"
); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } class Db{ private static Map map=new LinkedHashMap(); static { map.put("1", new Book("1","javaweb开发","老张","一本好书")); map.put("2", new Book("2","jdbc开发","老张","一本好书")); map.put("3", new Book("3","spring开发","老黎","一本好书")); map.put("4", new Book("4","struts开发","老毕","一本好书")); map.put("5", new Book("5","android开发","老黎","一本好书")); } public static Map getAll() { return map; } } class Book implements Serializable{ public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, String description) { super(); this.id = id; this.name = name; this.author = author; this.description = description; } private String id; private String name; private String author; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }

BuyServlet.java

package cn.itcast.sessionAplication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 完成购买
 */
@WebServlet("/BuyServlet")
public class BuyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        Book book=(Book)Db.getAll().get(id);

        //HttpSession session=request.getSession();
        HttpSession session=request.getSession(false);//配合禁用cookie的写法
        //手工以cookie形式发sessionid,以解决关闭浏览器后,上次买的东西还在

        //从session得到用户用于保存所有书的集合(购物车)
        List list=(List)session.getAttribute("list");
        if(list==null) {
            list=new ArrayList();
            session.setAttribute("list", list);

        }
        list.add(book);
        //配合禁用cookie的写法
        String url=response.encodeRedirectURL("ListCartServlet");
        response.sendRedirect(url);

        //response.sendRedirect(request.getContextPath()+"ListCartServlet");

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

ListCartServlet.java

package cn.itcast.sessionAplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 显示用户购买的商品
 */
@WebServlet("/ListCartServlet")
public class ListCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        HttpSession session=request.getSession(false);
        if(session==null) {
            out.write("您没有购买任何商品!!");
            return;
        }
        out.write("您购买了如下商品:
"
); Listlist=(List)session.getAttribute("list"); for(Book book:list) { out.write(book.getName()); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

example4 (防止表单重复提交)

javascript防表单重复提交(不能完全解决)


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
<script type="text/javascript">

    
    function dosubmit(){
        var input=document.getElementById("submit");
        input.disabled='disabled';
        return true;
    }
script>
head>
<body>
    <form action="DoFormServlet" method="post" onsubmit="return dosubmit()">
        用户名:<input type="text" name="username">
        <input type="submit" value="提交">

    form>
body>
html>

base64编码
JavaWeb基础——Cookie和Session_第6张图片

服务器端和前端同时防止表单重复提交
FormServlet.java

package cn.itcast.sessionAplication1;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

/**
 * 产生表单
 */
@WebServlet("/FormServlet")
public class FormServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //产生随机数(表单)
        TokenProcessor tp=TokenProcessor.getInstance();
        String token=tp.generateToken();

        request.getSession().setAttribute("token", token);

        request.getRequestDispatcher("formServletJS.jsp").forward(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}


class TokenProcessor{   //创建一个令牌
    /*
     * 1、把构建方法私有
     * 2、自己创建一个
     * 3、对外暴露一个方法,允许获取上面创建的对象
     * 
     * */

    private TokenProcessor() {};
    private static final TokenProcessor instance=new TokenProcessor();
    public static TokenProcessor getInstance(){
        return instance;
    }
    //随机数发生器
    public String generateToken() {
        //获取随机数,但由此获取到的随机数长度可能不一样,但它们的摘要一样,所以为了保证它们的长度一致选用它们的数据摘要
        String token=System.currentTimeMillis()+new Random().nextInt()+"";//获取随机数
        try {
            //通过md5算法得到数据摘要,无论数据有多大,它的数据摘要始终是128位
            MessageDigest md=MessageDigest.getInstance("md5");//
            byte[]md5=md.digest(token.getBytes());//返回的是任意二进制字节数组

            //return new String(md5);//这样行不通,因为没有没有指定码表,它会默认查GB2312码表,然而它与二进制字节数组不一定有对应的码值,所以必定是个乱码
            //为了让它不是乱码,所以采用base64编码
            BASE64Encoder encoder=new BASE64Encoder();
            return encoder.encode(md5);
        }catch(NoSuchAlgorithmException e){
            throw new RuntimeException(e);
        }
    }
}

formServletJS.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
<script type="text/javascript">
function dosubmit(){
    var input=document.getElementById("submit");
    input.disabled='disabled';
    return true;
}

script>
head>
<body>
    <form action="DoFormServlet" onsubmit="return dosubmit()" method="post">
        <input type="hidden" name="token" value="$(token)">
        用户名:<input type="text" name="username"><br/>
        <input type="submit" value="提交">
    form>
body>
html>

DoFormServlet.java

package cn.itcast.sessionAplication1;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理表单提交请求
 */
@WebServlet("/DoFormServlet")
public class DoFormServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean b=isTokenValid(request);
        if(!b) {
            System.out.println("请不要重复提交");
            return;
        }
        request.getSession().removeAttribute("token");
        System.out.println("向数据库注册用户----");
    }
    //判断表单号是否有效
    private boolean isTokenValid(HttpServletRequest request) {
        // TODO Auto-generated method stub
        String client_token=request.getParameter("token");//客户端的token表单
        if(client_token==null) {
            return false;
        }
        String server_token=(String)request.getSession().getAttribute("token");//获取服务器中的token表单
        if(server_token==null) {
            return false;
        }
        if(!client_token.equals(server_token)) {
            return false;
        }
        return true;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

example5 验证码校验

Checkcode1.java

package cn.itcast.sessionCheckcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Checkcode1
 */
@WebServlet("/Checkcode1")
public class Checkcode1 extends HttpServlet {
private static final long serialVersionUID = 1L;

    public static final int WIDTH=120;
    public static final int HEIGHT=25;
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);//构建出一张图片
        Graphics g=image.getGraphics();//使得能在图片上进行设置

        //1、设置背景色
        setBackGround(g);
        //2、设置边框
        setBorder(g);
        //3、画干扰线
        drawRandomLine(g);
        //4、写随机数
        String random=drawRandomNum((Graphics2D) g);
        request.getSession().setAttribute("imagecheckcode",random);

        //5、图形写给浏览器
        //发头控制浏览器不要缓存,如果没有这步的话当我们访问Register网页时不点刷新,直接按回车,图片还是保持不变
        //点击刷新的时候会产生两个动作:一是重新清空缓存;二是重新运行程序
        response.setDateHeader("expire", -1);//控制所有浏览器都不要缓存
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpg", response.getOutputStream());


    }

    private String drawRandomNum(Graphics2D g) {
        // TODO Auto-generated method stub
        g.setColor(Color.RED);
        g.setFont(new Font("宋体",Font.BOLD,20));

        String base="\u6d4e\u8499\u68cb\u7aef\u817f\u62db\u91ca\u4ecb\u70e7\u8bef";

        StringBuffer sb=new StringBuffer();
        //[\u4e00-\u9fa5]
        int x=5;
        for(int i=0;i<4;i++) {

            int degree=new Random().nextInt()%30;//从-30-30之间产生一个随机数

            //Graphics2D类才有旋转功能
            //new Random().nextInt(base.length()):在base的长度以内产生一个随机数
            String ch=base.charAt(new Random().nextInt(base.length()))+"";
            sb.append(ch);
            g.rotate(degree*Math.PI/180,x,20);//设置旋转角度
            g.drawString(ch, x, 20);
            g.rotate(-degree*Math.PI/180,x,20);//转回去
            x+=30;
        }
        return sb.toString();
    }

    private void drawRandomLine(Graphics g) {
        // TODO Auto-generated method stub
        g.setColor(Color.GREEN);
        for(int i=0;i<5;i++) {
            int x1=new Random().nextInt(WIDTH);
            int y1=new Random().nextInt(HEIGHT);

            int x2=new Random().nextInt(WIDTH);
            int y2=new Random().nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
    }

    private void setBorder(Graphics g) {
        // TODO Auto-generated method stub
        g.setColor(Color.BLUE);
        g.drawRect(1, 1,WIDTH-2, HEIGHT-2);
    }

    private void setBackGround(Graphics g) {
        // TODO Auto-generated method stub
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Checkcode.html


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>

<script type="text/javascript">
    function changeImage(img){
        //如果只写img.src=img.src则点击不会变,它会调用缓存中的图片(我们没刷新,也没访问之前的地址),当我们给它加上"?"后则每次请求的都是新地址
        //缓存中自然没有之前的图片,所以会调用新的图片(没有后面的new Date().getTime()也能运行)
        img.src=img.src+"?"+new Date().getTime();
    }
script>

head>
<body>
    
    <form action="RegisterServlet" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        认证码:<input type="text" name="checkcode">
        <img src="Checkcode1" onclick="changeImage(this)" alt="换一张" style="cursor:pointer "><br/>
        <input type="submit" value="注册">
    form>
body>
html>

RegisterServlet.java

package cn.itcast.sessionCheckcode;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet中的context域用的地方:产生的数据,页面不仅显示,等会儿用完了,还要给其他的servlet用
 * request域的用处:产生的数据,显示完了,就不用了
 * session:产生的数据,显示完了,还要用
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");//没有这句,则我们输入的中文,c_checkcode收到的将是乱码

        //处理注册请求之前,校验认证码是否有效
        String c_checkcode=request.getParameter("checkcode");
        String s_checkcode=(String) request.getSession().getAttribute("imagecheckcode");
        if(c_checkcode!=null && s_checkcode!=null && c_checkcode.equals(s_checkcode)) {
            System.out.println("处理注册请求!");
        }else {
            System.out.println("认证码错误!");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

你可能感兴趣的:(java)