9.会话跟踪技术(Cookie、Session)

会话跟踪技术(Cookie、Session)

笔记目录:(https://www.cnblogs.com/wenjie2000/p/16378441.html)

视频教程(P123~P133)

  • 会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次请求和响应

  • 会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据

  • HTTP协议是无状态的,每次浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内数据共享

  • 实现方式:

    1. 客户端会话跟踪技术:Cookie
    2. 服务端会话跟踪技术:Session

Cookie基本使用

  • Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问

  • Cookie基本使用

    发送Cookie:

    1. 创建Cookie对象,设置数据

      Cookie cookie = new Cookie("key","value");
      
    2. 发送Cookie到客户端:使用Response对象

      response.addCookie(cookie);
      

    Edge浏览器可以在 edge://settings/siteData 中查看到所有网站发回的Cookie数据

    获取Cookie:

    1. 获取客户端携带的所有Cookie,使用request对象

      Cookie[] cookies = request.getCookies();
      
    2. 遍历数组,获取每一个Cookie对象:for(Cookie cookie: cookies){}

    3. 使用Cookie对象方法获取数据

      cookie.getName();
      cookie.getValue();
      

Cookie原理

  • Cookie的实现是基于HTTP协议的

    • 响应头:set-cookie

    • 请求头:cookie

Cookie使用细节

  • Cookie存活时间

    • 默认情况下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁

    • cookie.setMaxAge(int seconds):设置Cookie存活时间

      1. 正数:将Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除(注意时间单位为妙)
      2. 负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁
      3. 零:删除对应Cookie
      //使用举例
      Cookie cookie = new Cookie("username", "z");
      cookie.setMaxAge(600);//设置保存600秒
      response.addCookie(cookie);
      
  • Cookie存储中文

    • Cookie不能直接存储中文

    • 如需要存储,则需要进行转码:URL编码

      String value ="张三";
      //URL编码
      value = URLEncoder.encode(value, "UTF-8");
      
      System.out.println("存储数据:"+value);//%E5%BC%AO%E4%B8%89
      
      Cookie cookie = new Cookie("username", value);
      response.addCookie(cookie);
      
      //获取到value(%E5%BC%AO%E4%B8%89)后再对其进行解码
      //URL解码
      value = URLDecoder.decode(value,enc: "UTF-8");
      
      System.out.println(value);//张三
      

Session

Session基本使用

  • 服务端会话跟踪技术:将数据保存到服务端

  • JavaEE提供HttpSession接口,来实现一次会话的多次请求间数据共享功能

  • 使用:

    1. 获取Session对象

      HttpSession session = request.getSession();
      
    2. Session对象功能:

      void setAttribute(String name, Object o):存储数据到session域中

      Object getAttribute(String name):根据key,获取值

      void removeAttribute(String name):根据key,删除该键值对

Session原理

  • Session是基于Cookie实现的

    session的id会跟着cookie发送到浏览器,下次服务器获取session会先在cookie中查找是否存在id对应的session,如果有就直接用,如果没有再来创建

Session使用细节

  • Session钝化、活化:

    • 服务器重启后,Session中的数据是否还在?

    钝化:在服务器正常关闭后,Tomcat会自动将Session数据写入硬盘的文件中

    活化:再次启动服务器后,从文件中加载数据到Session中

  • Seesion销毁:

    1. 默认情况下,无操作,30分钟自动销毁

      <!--apache-tomcat-8.5.82\conf\web.xml-->
      <session-config>
      	<session-timeout>30</session-timeout>
      </session-config>
      
    2. 调用Session对象的invalidate()方法

      HttpSession session = request.getSession();
      session.invalidate();
      

小结

  • Cookie和Session都是来完成一次会话内多次请求间数据共享的
  • 区别:
    • 存储位置:Cookie是将数据存储在客户端,Session将数据存储在服务端
    • 安全性:Cookie不安全,Session安全
    • 数据大小:Cookie最大3KB,Session无大小限制
    • 存储时间:Cookie可以长期存储,Session默认30分钟
    • 服务器性能:Cookie不占服务器资源,Session占用服务器资源

案例

登录注册案例

视频讲解(https://www.bilibili.com/video/BV1Qf4y1T7Hx?p=129)

如果要看视频,不要跟着一步步做,没有意义。可以看他做完后再自己完成

需求说明:

  1. 完成用户登录功能,如果用户勾选“记住用户”,则下次访问登录页面自动填充用户名密码

  2. 完成注册功能,并实现验证码功能

用户登录

记住用户(写Cookie)

  • 如果用户勾选“记住用户”,则下次访问登陆页面自动填充用户名密码

  • 如何自动填充用户名和密码?

    1. 将用户名和密码写入Cookie中,并且持久化存储Cookie ,下次访问浏览器会自动携带Cookie

    2. 在页面获取Cookie数据后,设置到用户名和密码框中:

      ${cookie.key.value}//key指存储在cookie中的键名称
      

  • 何时写Cookie?

    1. 登录成功
    2. 用户勾选记住用户复选框

注册

  • 注册功能:保存用户信息到数据库

  • 验证码功能:(这里可以用现成的工具类com/itwen/util/CheckCodeUtil.java生成验证码图片)

    1. 展示验证码:展示验证码图片,并可以点击切换

      • 验证码就是使用Java代码生成的一张图片

      • 验证码作用:防止机器自动注册,攻击服务器

    2. 校验验证码:验证码填写不正确,则注册失败

      • 判断程序生成的验证码和用户输入的验证码是否一样,如果不一样,则阻止注册

      • 验证码图片访问和提交注册表单是两次请求,所以要将程序生成的验证码存入Session中

代码

文件结构

login-web

src\main

java\com\itwen

mapper

UserMapper.java

package com.itwen.mapper;

import com.itwen.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {

 /**
     * 根据用户名和密码查找用户对象
     * @param username
     * @param password
     * @return
     */
    @Select("select * from tb_user where username=#{un} and password=#{pd}")
    public User selectUser(@Param("un") String username, @Param("pd") String password);

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    @Select("select * from tb_user where username=#{username}")
    public User selectByUsername(String username);

    /**
     * 添加用户
     * @param user
     */
    @Insert("insert into tb_user values (null,#{username},#{password})")
    public void add(User user);
}

pojo

User.java

package com.itwen.pojo;


public class User {

 private long id;
 private String username;
 private String password;

 public User() {
 }

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

 public long getId() {
     return id;
 }

 public void setId(long id) {
     this.id = id;
 }


 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;
 }

 @Override
 public String toString() {
     return "User{" +
             "id=" + id +
             ", username='" + username + '\'' +
             ", password='" + password + '\'' +
             '}';
 }
}

service

UserService.java

package com.itwen.service;

import com.itwen.mapper.UserMapper;
import com.itwen.pojo.User;
import com.itwen.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
 //2.1 获取sqlSessionFactory对象
 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

 /**
     * 登录方法
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) {
        //2.使用MyBatis查询(MyBatis部分学过)
        //2.2获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3获取Mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //2.4调用方法查询信息
        User user = mapper.selectUser(username, password);
        //2.5释放资源
        sqlSession.close();
        return user;
    }

    /**
     * 用户注册
     * @param user
     * @return 是否注册成功
     */
    public boolean register(User user) {
        //2.使用MyBatis查询(MyBatis部分学过)
        //2.2获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3获取Mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //2.4调用方法查询信息
        User u = mapper.selectByUsername(user.getUsername());

        if (u==null){
            //用户不存在
            //添加用户
            mapper.add(user);
            sqlSession.commit();
        }
        //2.5释放资源
        sqlSession.close();

        return u==null;
    }
}

util

CheckCodeUtil.java

package com.itwen.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Random;

/**
 * 生成验证码工具类
 */
public class CheckCodeUtil {

    public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Random random = new Random();

    public static void main(String[] args) throws IOException {
        OutputStream fos= new FileOutputStream("d://a.jpg");
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
        System.out.println(checkCode);

    }

    /**
     * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
     *
     * @param width  图片宽度
     * @param height 图片高度
     * @param os 输出流
     * @param verifySize 数据长度
     * @return 验证码数据
     * @throws IOException
     */
    public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(width, height, os, verifyCode);
        return verifyCode;
    }

    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        // 未设定展示源的字码,赋默认值大写字母+数字
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
     *
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     *
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        //文件不存在
        if (!dir.exists()) {
            //创建
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     *
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 创建颜色集合,使用java.awt包下的类
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW};
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);
        // 设置边框色
        g2.setColor(Color.GRAY);
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        // 设置背景色
        g2.setColor(c);
        g2.fillRect(0, 2, w, h - 4);

        // 绘制干扰线
        Random random = new Random();
        // 设置线条的颜色
        g2.setColor(getRandColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        // 噪声率
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            // 获取随机颜色
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }
        // 添加图片扭曲
        shear(g2, w, h, c);

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    /**
     * 随机颜色
     *
     * @param fc
     * @param bc
     * @return
     */
    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }
        }

    }
}

SqlSessionFactoryUtils.java

package com.itwen.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

web

CheckCodeServlet.java

package com.itwen.web;

import com.itwen.util.CheckCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //生成验证码
     ServletOutputStream os = response.getOutputStream();
     String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);

     //存入Session
     HttpSession session = request.getSession();
     session.setAttribute("checkCodeGen",checkCode);

 }

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

HelloServlet.java

package com.itwen.web;

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

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     request.getRequestDispatcher("/helloUser.jsp").forward(request,response);
 }

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

LoginServlet.java

package com.itwen.web;

import com.itwen.mapper.UserMapper;
import com.itwen.pojo.User;
import com.itwen.service.UserService;
import com.itwen.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
 private UserService service=new UserService();
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //1.接收用户名密码
     String username = request.getParameter("username");
     String password = request.getParameter("password");
     String remember = request.getParameter("remember");

     //2.调用service查询
     User user = service.login(username, password);


     //3.判断user是否为空

     if(user!=null){
         //登录成功

         //判断是否要记住账号密码
         if("1".equals(remember)){
             //勾选了

             //创建cookie
             Cookie c_username = new Cookie("username", username);
             Cookie c_password = new Cookie("password", password);
             //cookie保存一周
             c_username.setMaxAge(7*24*60*60);
             c_password.setMaxAge(7*24*60*60);

             response.addCookie(c_username);
             response.addCookie(c_password);
         }

         //将登陆成功后的user对象,存储到session
         HttpSession session = request.getSession();
         session.setAttribute("user",user);

         String contextPath = request.getContextPath();
         response.sendRedirect(contextPath+"/HelloServlet");
     }else {
         //登录失败
         System.out.println("1111111111111111111111");

         //存储错误信息到request
         request.setAttribute("login_msg","用户名或密码错误");
         //跳转到登录界面
         request.getRequestDispatcher("login.jsp").forward(request,response);
     }

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

RegisterServlet.java

package com.itwen.web;

import com.itwen.pojo.User;
import com.itwen.service.UserService;

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

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
 private UserService service = new UserService();

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //判断验证码是否正确
     String checkCode = request.getParameter("checkCode");
     HttpSession session = request.getSession();
     String checkCodeGen = (String) session.getAttribute("checkCodeGen");
     if (!checkCodeGen.equals(checkCode)){
         request.setAttribute("register_msg","验证码错误");
         request.getRequestDispatcher("register.jsp").forward(request,response);
         return;//记得要return,否者程序会继续执行,不能进行forward转发。会报错
     }

     //获取账号密码
     String username = request.getParameter("username");
     String password = request.getParameter("password");
     User user = new User();
     user.setUsername(username);
     user.setPassword(password);

     //调用service注册
     boolean flag = service.register(user);

     //判断是否注册成功
     if (flag==true){
         //注册成功
         //跳转到登录界面
         request.setAttribute("register_msg","注册成功请登录");
         request.getRequestDispatcher("login.jsp").forward(request,response);
     }else {
         //注册失败
         //提示注册失败
         request.setAttribute("register_msg","注册失败,该用户已存在");
         request.getRequestDispatcher("register.jsp").forward(request,response);
     }
 }

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

resources

com.itwen.mapper

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itwen.mapper.UserMapper">
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--起别名-->
    <typeAliases>
        <package name="com.itwen.pojo"/>
    </typeAliases>

    <!--设置连接数据库的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db1"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <package name="com.itwen.mapper"/>
    </mappers>
</configuration>

webapp

helloUser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Title</title>
</head>
<body>
<h1>${user.username},欢迎你</h1>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>登录界面</title>
</head>
<body>
 <h1>${login_msg} ${register_msg}</h1>
<form action="/login-web/loginServlet" method="post" >
 用户名:<br><input name="username" value="${cookie.username.value}"><br>
 密码:<br><input type="password" name="password" value="${cookie.password.value}"><br>
 记住:<input type="checkbox" name="remember" value="1"><br>
 <input type="submit" value="登录">
 <a href="register.jsp">注册</a>
</form>
</body>
</html>

register.jsp

<%--
Created by IntelliJ IDEA.
User: ZWJ
Date: 2022/12/27
Time: 16:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>注册界面</title>
</head>
<body>
<h1>${register_msg}</h1>
<form action="/login-web/registerServlet" method="post">
 用户名:<br><input name="username"><br>
 密码:<br><input type="password" name="password"><br>
 验证码:<br><input name="checkCode"><img id="checkCodeImg" src="/login-web/checkCodeServlet"><br>
 <input type="submit" value="注册">
</form>
<script>
 /*点击切换验证码图片*/
 document.getElementById("checkCodeImg").onclick = function () {
     // 因为重复请求相同地址时,浏览器会认为已经做过了,不会刷新。所以需要在后面加上一个参数来保证地址有差异
     document.getElementById("checkCodeImg").src = "/login-web/checkCodeServlet?" + new Date().getMilliseconds();
 }
</script>
</body>
</html>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>login-web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope><!--编译和测试环境有效,运行环境无效。因为tomcat自带了这个jar包,会冲突-->
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope><!--因为tomcat自带了这个包-->
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!--           <configuration>&lt;!&ndash;配置(可选项)&ndash;&gt;
                               <port>80</port>&lt;!&ndash;访问端口号(默认8080)&ndash;&gt;
                               <path>/</path>&lt;!&ndash;项目访问路径(默认为项目名)&ndash;&gt;
                           </configuration>-->
            </plugin>
        </plugins>
    </build>

</project>
posted @ 2023-01-09 09:06  文杰2000  阅读(38)  评论(0编辑  收藏  举报