JavaWeb登录页面的准备


用户登录

  • 创建Servlet 和静态页面和Mapper
  • 创建数据库。表,插入数据
  • 配置Mybatis核心配置文件mybatis-config.xml 和Mapper.xml映射文件和Mapper接口
  • 依赖添加 mysql驱动,mybatis,junit单元测试 logback日志
  • 添加获取SqlSessionFactory的工厂SqlSessionFactoryUtils
    mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "https://mybatis.org/dtd/mybatis-3-config.dtd">
   <configuration>
   <!--    别名给ResultType,不需要写com.kang.pojo,不区分大小写-->

    <!--    <typeAliases>-->
    <!--        <package name="com.kang.pojo"/>-->
 <!--    </typeAliases>-->

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
            <property name="username" value="root"/>
            <property name="password" value="1234"/>
        </dataSource>
    </environment>
</environments>
 <!--    //加载sql映射文件-->
<mappers>
    <package name = "com.kang.mapper"></package>
</mappers>
</configuration>

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
 <configuration>
<!--
    CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
    </encoder>
</appender>

<logger name="com.kang" level="DEBUG" additivity="false">
    <appender-ref ref="Console"/>
</logger>


<!--

  level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
 , 默认debug
  <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
  -->
<root level="DEBUG">
    <appender-ref ref="Console"/>
</root>
 </configuration>


    <!-- mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
 <version>3.5.5</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.31</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

<!-- 添加slf4j日志api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.2.3</version>
</dependency>
 <!--JSON转换-->
<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.79</version>
    </dependency>

<!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
  • Mapper代理开发
    /**
   * Mybatis 代理开发
    */
 public class MyBatisDemo2 {

public static void main(String[] args) throws IOException {

    //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    //2. 获取SqlSession对象,用它来执行sql
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //3. 执行sql
    //List<User> users = sqlSession.selectList("test.selectAll");
    //3.1 获取UserMapper接口的代理对象
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = userMapper.selectAll();

    System.out.println(users);
    //4. 释放资源
    sqlSession.close();

  }
}

SqlSessionFactoryUtils

package com.kang.utils;

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

import java.io.InputStream;

/**
 * SqlSessionFactory工厂
 * @author shkstart
 * @create 2023-05-18 20:01
 */
public class SqlSessionFactoryUtils {
private  static  SqlSessionFactory sqlSessionFactory;

static {
    try {
        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (Exception e){
        e.printStackTrace();
    }

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

然后在单独写

     //2. 获取SqlSession对象,用它来执行sql
    SqlSession sqlSession = sqlSessionFactory.openSession();

验证码工具包(CheckCodeUtil)

package com.kang.utils;

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

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

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



/**
 * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
 *
 * @param w
 * @param h
 * @param os
 * @param verifySize
 * @return
 * @throws IOException
 */
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
    String verifyCode = generateVerifyCode(verifySize);
    outputImage(w, h, 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);
        }

    }

  }
 }

获取验证码

先利用验证码工具包,创建CheckCodeServlet来获取验证码图片,用response来输出流,然后调用工具包拿出验证码来,返回一个里面相对应的字符串,将这个字符串存到session中,以便于和在文本框中输入的验证码做比较是否相同,然后在相应的登录注册地方,来获取表单验证码的name值,和获取存的session值,来判断两者是否相同。前端则用想换一个验证码,则点击换一个,来触发script,从交换id换到图片id,去CheckCodeServlet来重新生成验证码,在依次操作。

ServletOutputStream outputStream = response.getOutputStream();
    String s = CheckCodeUtil.outputVerifyImage(100, 40, outputStream, 4);

    //将s存到session,来发送记录session
    HttpSession session = request.getSession();
    session.setAttribute("checkImg",s);

判断输入的和图片验证码是否相同

        String checkCode = request.getParameter("checkCode");
        HttpSession session1 = request.getSession();
        String checkImg = (String)session.getAttribute("checkImg");

        if(!checkImg.equalsIgnoreCase(checkCode)){
            request.setAttribute("user_Msg","验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

验证码前端展示

    <p>
        验证码:
            <input type="text" name = "checkCode" id = "checkCode"/>
            <img id="checkCodeImg" src="checkCodeServlet">
            <a href="#" id="changeImg">看不清</a>
    </p>

<script>
    document.getElementById("changeImg").onclick=function () {
        document.getElementById("checkCodeImg").src = "checkCodeServlet?" + new Date().getMilliseconds();
    }
</script>

记住密码

先给记住密码弄一个值value=1,然后在登录的时候判断是否value值为1,为1的话代表勾选了记住创建两个Cookie,一个存用户名,一个存密码,设置Cookie使用周期,然后发送Cookie。在jsp文件中动态接收Cookie,在username和password的文本框添加value=”${session.key.value}”,key写Cookie的键值

发送Cookie
  //获取表单提交列表中的remember
  String remember = request.getParameter("remember");

 //判断是否记住登录
            if("1".equals(remember)){
                //勾选了,发送cookie
                Cookie cookie1 = new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);

                cookie1.setMaxAge(60*60*24*7);
                cookie2.setMaxAge(60*60*24*7);

                response.addCookie(cookie1);
                response.addCookie(cookie2);
接收Cookie
   <p>Username:<input type="text" id="username" name="username" value="${cookie.username.value}" placeholder="请输入用户名"></p>
    <p>Password:<input type="password" id="password" name="password" value="${cookie.password.value}" placeholder="请输入密码"></p>
错误信息可以放进request域中,在jsp中用el表达式动态获取
 ${错误信息的键}

增删改查

以增加为例,先点击新增按钮,然后转向add.jsp,提交add.jsp表单action指向InsertServlet,跳转到InsertServlet ,然后在调用service中insertBrand方法,然后在调用mapper中的方法连接数据库进行插入操作

过滤器Filter

1.判断是否是登录和注册的相关信息,是就直接放行,不是的话就进行登录验证
2.判断用户是否登录:session中是否有user信息
登录:直接放行
未登录:给出提示信息,并且跳转到登录页面

JSON

依赖

com.alibaba
fastjson
1.2.79

java->JSON 序列化
List brands = brandService.selectAll();

    //将集合转换为json,序列化

    String s = JSON.toJSONString(brands);

    //响应数据,考虑中文
    response.setContentType("text/json;charset=utf-8");
    response.getWriter().write(s);

JSON->java 反序列化
服务器接收json数据
//接收数据
//读请求体
BufferedReader reader = request.getReader();
String s = reader.readLine();
//将json转换为对象
Brand brand1 = JSON.parseObject(s, Brand.class);

事件
//给表单绑定单击事件
document.getElementById(“btn”).onclick = function ()

//页面加载完成1ho发送ajax请求,增加
window.onload =function () 


文章作者: 是小康呀~
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 是小康呀~ !
评论
  目录