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

2023-12-30 17:02:25

实验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<cookies.length;i++){
            if("lastAccess".equals(cookies[i].getName())){
                //获取cookie的值赋值给lastAccessTime
                lastAccessTime=cookies[i].getValue();
                break;
            }
        }
        if(lastAccessTime==null){
            response.getWriter().println("您是首次访问本站!");
        }else{
            response.getWriter().println("您上次访问的时间是:"+lastAccessTime);
        }
        String currentTime=new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
        //创建cookie,名称为lastAccess,当前时间作为值
        Cookie cookie=new Cookie("lastAccess",currentTime);
        //设置cookie最大存活时长为60*60
        cookie.setMaxAge(60*60);
        //通过response添加cookie
        response.addCookie(cookie);
    }
}

第一次访问 :

第二次访问:

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<String ,Book> books=new LinkedHashMap<String,Book>();
    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<Book> 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<Book> books=BookDB.getAll();
        out.write("本站的图书有:<br/>");
        for(Book book:books){
            //遍历所有书籍,并将url设置为PurchaseServlet+书号
            String url="/weeebbbb_war_exploded/PurchaseServlet?id="+book.getId();
            out.write(book.getName()+"<a href='"+url+"'>点击购买</a><br>");
        }
    }
}

(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<Book> cart = (List) session.getAttribute("cart");
        //通过session获取属性名cart的属性值
        if (cart == null) {
            cart = new ArrayList<Book>();
            //通过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<Book> 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(("对不起,您没有购买任何商品!<br>"));
        }else{
            out.write("您购买的图书有:<br>");
            for (Book book:cart){
                out.write(book.getName()+"<br>");
            }
        }
    }


}

打开listbook:

?

点击购买:

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

(1)新建login.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/weeebbbb_war_exploded/LoginServlet1" method="post">
    <table align="center">
        <tr>
            <td>姓名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="reset" value="重置">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

(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="<h1 style='color:RED'>"+"欢迎"+session.getAttribute("username")+"登陆成功!!</h1>&nbsp;";
            html+="<a href='/LogoutServlet'>退出登录</a>";
            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");
    }
}

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

登录成功:

?

文章来源:https://blog.csdn.net/ysy1119/article/details/135305077
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。