会话技术

2023-01-23  本文已影响0人  不会写诗的苏轼
  1. cookie的特点和作用
    1.cookie存储数据在客户端浏览器
    2.浏览器对于单个cookie的大小有限制(4kb)以及对同一个域名下的总cookie数量也有限制(20个)
    *作用∶
    1.cookie—般用于存出少量的不太敏感的数据
    2.在不登录的情况下,完成服务器对客户端的身份识别
  2. 例子
     response.setContentType("text/html;charset=utf-8");
        //获取cookie
        Cookie[] cookies = request.getCookies();//获取cookies
        Boolean flag=false; //是否第一次访问

        /**不是第一次访问**/
        if(cookies!=null&&cookies.length>0){ //如果cookie存在
            for (Cookie cookie:cookies) {  //循环cookie
                if("lastTime".equals(cookie.getName())){ //如果cookie的名字是lastTime说明cookie存在
                    flag=true; //不是第一次访问
                    Date date = new Date(); //创建系统时间
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间对象
                    String str_date = dateFormat.format(date); //格式化时间
                    //编码
                    str_date=URLEncoder.encode(str_date,"utf-8");  //特殊字符空格会报错,用URL编码
                    cookie.setValue(str_date); //设置lastTime的值是系统时间
                    cookie.setMaxAge(30*24*60*60);//保存一个月
                    response.addCookie(cookie); //保存cookie
                    String value = cookie.getValue();//获取cookie的值
                    //解码
                    value=URLDecoder.decode(value,"utf-8");  //输出的时候要解码
                    response.getWriter().write("<h1>欢迎回来你上次访问的时间是"+value+"</h1>");
                    break;
                }


            }
        }
        /**第一次访问**/
        if(cookies==null||cookies.length==0||flag==false){
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str_date = dateFormat.format(date);
            //编码
            str_date=URLEncoder.encode(str_date,"utf-8");
            Cookie cookie=new Cookie("lastTime",str_date);
            cookie.setMaxAge(30*24*60*60);
            response.addCookie(cookie);
            response.getWriter().write("<h1>欢迎你首次访问</h1>");
        }

案例,验证码
jdbc工具类:

public class Druid {
    private static DataSource ds;

    static {

        try {
            Properties pro=new Properties();
            //查找数据库连接的配置文件
            InputStream  is= Druid.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pro.load(is);
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接池
    public static DataSource getDataSource(){
        return ds;
    }
    //获取数据库连接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

dao提供的login方法

public class UserDao {
    private JdbcTemplate template=new JdbcTemplate(Druid.getDataSource());

    public User login(User user) {
        try {
            String sql="select * from user where username=? and password=?";
            User BeanUser = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPassword());
            return BeanUser;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}

sessionLogin.jsp

<form action="/newServlet/SessionLoginServlet">
    <table>
        <tr><td>用户名</td><td><input type="text" name="username"></td></tr>
        <tr><td>密码</td><td><input type="password" name="password"></td></tr>
        <tr><td>验证码</td><td><input type="text" name="checkCode"></td></tr>
        <tr><td colspan="2"><img id="checkCodeImg" src="/newServlet/CheckCodeServlet" alt=""></td></tr>
        <tr><td colspan="2"><input type="submit" value="提交"></td></tr>
    </table>
</form>
<div><%= request.getAttribute("error_login")==null?"":request.getAttribute("error_login") %></div>
<div><%= request.getAttribute("error_code")==null?"":request.getAttribute("error_code") %></div>
<script>
    document.getElementById("checkCodeImg").onclick=function(){
        this.src="/newServlet/CheckCodeServlet?"+new Date().getTime();
    }
</script>

验证码图片

package com.xjbt.session;

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;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 画验证码
         * */
        int width=100;
        int height=50;
        //1.创建—对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //2.美化图片
        Graphics graphics = image.getGraphics();//画笔对象
        //填充粉红色
        graphics.setColor(Color.pink);//设置画笔颜色
        graphics.fillRect(0,0,width,height);//填充

        //蓝色边框
        graphics.setColor(Color.blue);
        graphics.drawRect(0,0,width-1,height-1);

        //写数字
        String str="ABCDEFGHIJKLMNOPQISCUVWSYZabcdefghijklmnopqiscuvwsyz0123456789";
        //生成随机角标
        Random rand = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <=4 ; i++) {
            int index = rand.nextInt(str.length());
            //获取随机字符
            char c = str.charAt(index);//随机字符
            sb.append(c);
            graphics.drawString(c+"",width/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        request.getSession().setAttribute("checkCode_session",checkCode_session);//将验证码存入session
        //4画干扰线
        graphics.setColor(Color.green);
        for (int i = 1; i <=10; i++) {
            int x1=rand.nextInt(width);
            int y1=rand.nextInt(height);
            int x2=rand.nextInt(width);
            int y2=rand.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }


        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1><%= request.getSession().getAttribute("user")%>,欢迎你!</h1>
</body>
</html>

sessionLoginServlet.java

@WebServlet("/SessionLoginServlet")
public class SessionLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        /*
        //获取输入框的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        */

        /**
         * 获取用户信息(包含了用户id,username,password)
         */

        Map<String, String[]> map = request.getParameterMap();
        User loginUser=new User();//登录对象(包含了所有的用户信息)
        try {
            //使用beanutils
            BeanUtils.populate(loginUser,map);//将传入的参数(输入框的内容),作为loginUser对象的成员变量的值
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        /**
         *判断验证码是否添加正确
         */

        //获取传入参数的验证码
        String checkCode = request.getParameter("checkCode");
        //获取session
        HttpSession session = request.getSession();
        //创建dao
        UserDao userDao = new UserDao();
        //获取存入session的checkCode_session【验证码】的值
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //删除验证码
        session.removeAttribute("checkCode_session");//解决登陆成功后点击返回验证码还是原来的
        if(checkCode_session!=null&&checkCode_session.equalsIgnoreCase(checkCode)){//忽略大小写(如果传入的验证码等于存入session的验证码)
            //验证用户名密码
            User user = userDao.login(loginUser);
            if(user!=null){
                //存用户信息
                session.setAttribute("user",user.getUsername());
                //重定向到登录成功页面
                response.sendRedirect(request.getContextPath()+"/success.jsp");
            }else{
                //登录失败
                //存入提示信息
                request.setAttribute("error_login","用户名或密码错误");
                request.getRequestDispatcher("/sessionLogin.jsp").forward(request,response);
            }

        }else{
            //存入提示信息
            request.setAttribute("error_code","验证码输入错误");
            request.getRequestDispatcher("/sessionLogin.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读