web一些实验代码——会话管理

实验5:会话管理

1、新建HelloServlet1代码,熟悉Cookie的创建、获取与相关操作。

package com.example.weeebbbb.the5.cookie;
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.text.SimpleDateFormat;
import java.util.Date;
@WebServlet(name = "HelloServlet1", value = "/HelloServlet1")
public class HelloServlet1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String lastAccessTime=null;
        //通过request调用getCookies获取cookie
        Cookie[] cookies=request.getCookies();
        for(int i=0;cookies!=null && i

第一次访问 :

web一些实验代码——会话管理_第1张图片

第二次访问:

web一些实验代码——会话管理_第2张图片

2、完成以下实验步骤,实现简单的购书操作。

(1)新建Book.java:用于封装图书的信息。

package com.example.weeebbbb.the5.session;

public class Book {
    private String id;
    private String name;
    public Book(String id,String name){
        this.id=id;
        this.name=name;
    }
    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;
    }
}

(2)新建BookDB.java:用于模拟保存所有图书的数据库。通过Map集合存储了多个不同的Book对象,提供了获取指定图书和所有图书的相关方法。

package com.example.weeebbbb.the5.session;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class BookDB {
    private static Map books=new LinkedHashMap();
    static {
        books.put("1",new Book("1","JavaWeb开发"));
        books.put("2",new Book("2","JDBC开发"));
        books.put("3",new Book("3","Java基础"));
        books.put("4",new Book("4","Spring开发"));
        books.put("5",new Book("5","Struts开发"));
    }
    public static Collection getAll(){
        return books.values();
    }
    public static Book getBook(String id){
        return books.get(id);
    }
}

(3)新建ListBookServlet代码,用于显示所有可购买图书的列表,通过点击“购买”链接,便可将指定的图书添加到购物车中。遍历所有书籍,并将url设置为PurchaseServlet+书号;

package com.example.weeebbbb.the5.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@WebServlet(name = "ListBookServlet", value = "/ListBookServlet")
public class ListBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        Collection books=BookDB.getAll();
        out.write("本站的图书有:
"); for(Book book:books){ //遍历所有书籍,并将url设置为PurchaseServlet+书号 String url="/weeebbbb_war_exploded/PurchaseServlet?id="+book.getId(); out.write(book.getName()+"点击购买
"); } } }

(4)新建PurchaseServlet代码,通过cookie共享数据,有两个功能,一是将用户购买的图书信息保存到Session对象中,二是在用户购买图书结束后,将页面重定向到用户已经购买的图书列表。;

package com.example.weeebbbb.the5.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "PurchaseServlet", value = "/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if (id == null) {
            String url = "ListBookServlet";
            response.sendRedirect(url);
            return;
        }
        Book book = BookDB.getBook(id);

        //通过request获取session
        HttpSession session = request.getSession();
        List cart = (List) session.getAttribute("cart");
        //通过session获取属性名cart的属性值
        if (cart == null) {
            cart = new ArrayList();
            //通过session设置cart的属性值
            session.setAttribute("cart", cart);
        }
        cart.add(book);
        //创建cookie,并存入JSESSIONID
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 30);
        cookie.setPath("/");
        //通过response对象将cookie发送到浏览器
        response.addCookie(cookie);
        String url = "CartServlet";
        //通过response对象重定向到url指定的位置
        response.sendRedirect(url);
    }

}

(5)新建CartServlet通过cookie获取共享的数据,用于展示用户已经购买的图书列表。该类在实现时,需要通过getSession()获取到所有的Session对象,然后判断用户是否已经购买图书,如果已经购买过,则显示购买的图书列表,否则在页面显示友好的提示“对不起!您还没有购买任何商品”。

package com.example.weeebbbb.the5.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/CartServlet")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        List cart=null;
        boolean purFlag=true;
        //通过request获取session
       HttpSession session=request.getSession(false);
        if(session==null){
            purFlag=false;
        }else{
            //通过session 获取cart对应的属性值
            cart=(List)session.getAttribute("cart");
            if (cart==null){
                purFlag=false;
            }
        }
        if(!purFlag){
            out.write(("对不起,您没有购买任何商品!
")); }else{ out.write("您购买的图书有:
"); for (Book book:cart){ out.write(book.getName()+"
"); } } } }

打开listbook:

web一些实验代码——会话管理_第3张图片 

点击购买:

web一些实验代码——会话管理_第4张图片

3、使用session和cookie,实现用户一定时间内免登录。

(1)新建login.html页面




    
    Title


姓名:
密码:

(2)新建IndexServlet.java代码

package com.example.weeebbbb.the5.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet(name = "IndexServlet",value = "/IndexServlet")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session= req.getSession(false);
        if (null==session||!"叶兹".equals(session.getAttribute("username"))){
            resp.sendRedirect("login1.html");
        }else{
            String html="

"+"欢迎"+session.getAttribute("username")+"登陆成功!!

 "; html+="退出登录"; resp.getWriter().append(html); } } }

(3)新建LoginServlet1.java代码

package com.example.weeebbbb.the5.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet1",value = "/LoginServlet1")
public class LoginServlet1 extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.setCharacterEncoding("UTF-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
       if ("叶兹".equals(username)&&"123".equals(password)){
           HttpSession session= req.getSession(true);
           session.setMaxInactiveInterval(60*60);
           session.setAttribute("username",username);
           Cookie cookie=new Cookie("JSESSIONID",session.getId());
           cookie.setMaxAge(60*60);
           resp.addCookie(cookie);
           resp.sendRedirect("/weeebbbb_war_exploded/IndexServlet");
       }else{
           resp.sendRedirect("login1.html");
       }
    }
}

(4)新建LogoutServlet.java代码

package com.example.weeebbbb.the5.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet(name = "LogoutServlet",value = "/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session= req.getSession(false);
    if (session!=null){
        session.invalidate();
    }
        Cookie cookie=new Cookie("JSESSIONID","");
    cookie.setMaxAge(0);
    resp.addCookie(cookie);
    resp.sendRedirect("/IndexServlet");
    }
}

登录填写信息(注意这个登录的账号和密码是写死的,页面上输入的账号密码要和代码里写的一样才能成功登录,否则一直都会在登陆界面):

web一些实验代码——会话管理_第5张图片

登录成功:

web一些实验代码——会话管理_第6张图片 

你可能感兴趣的:(前端)