JavaWeb学习-用户登录案例(多用户类型选择登录+验证码验证)

1、项目文件整体结构
在这里插入图片描述
2、准备每一种实体用户对应的数据库表
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3、index.jsp编写

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>LoginTest</title>
</head>
<body>
<form action="LoginServlet" method="post">
  账号:<input type="text" name="username"><br>&nbsp;&nbsp;(密码框)<input type="password" name="password"><br>
  <input type="radio" id="radio-1" name="type" checked value="1" />
  <label>学生</label>
  <input type="radio" id="radio-2" name="type" value="2" />
  <label>老师</label>
  <input type="radio" id="radio-3" name="type" value="3" />
  <label>管理员</label>
  <br>
  验证码:<input type="text" name="image">
  <img src="VerifyCodeServlet">
  <input type="button" value="看不清? 换一张." id="btn" /><font color="red">${requestScope.imageMess}</font>
  <br>
  <input type="submit" value="登录">
</form>
<script type="text/javascript">
  document.getElementById("btn").onclick = function () {
    // 获取img元素
    // 为了让浏览器发送请求到servlet, 所以一定要改变src
    document.getElementsByTagName("img")[0].src = "VerifyCodeServlet?time=" + new Date().getTime();
  };
</script>
</body>
</html>

4、数据库连接工具类DbUtil编写

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 *
 * @author llq
 *数据库连接util
 */
public class DbUtil {

    private String dbUrl = "jdbc:mysql://localhost:3306/logintest2?useUnicode=true&characterEncoding=utf8";
    private String dbUser = "root";
    private String dbPassword = "123456";
    private String jdbcName = "com.mysql.jdbc.Driver";
    private Connection connection = null;
    public Connection getConnection(){
        try {
            Class.forName(jdbcName);
            connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("数据库连接失败");
            e.printStackTrace();
        }
        return connection;
    }

    public void closeCon(){
        if(connection != null)
            try {
                connection.close();
                System.out.println("数据库连接已关闭");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //创建一个数据库对象
        DbUtil dbUtil = new DbUtil();
        //连接数据库
        dbUtil.getConnection();
    }
}

5、验证码生成工具类VerifyCodeUtil编写

package cn.zhukun.Util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
public class VerifyCodeUtil {
    private int w = 70;
    private int h = 35;
    private Random r = new Random();
    // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
    private String[] fontNames  = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
    // 可选字符
    private String codes  = "0123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    // 背景色
    private Color bgColor  = new Color(255, 255, 255);
    // 验证码上的文本
    private String text ;

    // 生成随机的颜色
    private Color randomColor () {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }

    // 生成随机的字体
    private Font randomFont () {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];//生成随机的字体名称
        int style = r.nextInt(4);//生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)
        int size = r.nextInt(5) + 24; //生成随机字号, 24 ~ 28
        return new Font(fontName, style, size);
    }

    // 画干扰线
    private void drawLine (BufferedImage image) {
        int num  = 3;//一共画3条
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        for(int i = 0; i < num; i++) {//生成两个点的坐标,即4个值
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.BLUE); //干扰线是蓝色
            g2.drawLine(x1, y1, x2, y2);//画线
        }
    }

    // 随机生成一个字符
    private char randomChar () {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    // 创建BufferedImage
    private BufferedImage createImage () {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }

    // 调用这个方法得到验证码
    public BufferedImage getImage () {
        BufferedImage image = createImage();//创建图片缓冲区
        Graphics2D g2 = (Graphics2D)image.getGraphics();//得到绘制环境
        StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本
        // 向图片中画4个字符
        for(int i = 0; i < 4; i++)  {//循环四次,每次生成一个字符
            String s = randomChar() + "";//随机生成一个字母
            sb.append(s); //把字母添加到sb中
            float x = i * 1.0F * w / 4; //设置当前字符的x轴坐标
            g2.setFont(randomFont()); //设置随机字体
            g2.setColor(randomColor()); //设置随机颜色
            g2.drawString(s, x, h-5); //画图
        }
        this.text = sb.toString(); //把生成的字符串赋给了this.text
        drawLine(image); //添加干扰线
        return image;
    }

    // 返回验证码图片上的文本
    public String getText () {
        return text;
    }

    // 保存图片到指定的输出流
    public static void output (BufferedImage image, OutputStream out)
            throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

6、用户实体编写这里有三类(Admin,Student,Teacher)

package cn.zhukun.Entity;

public class Admin {
    private int id;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public void setId(int 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;
    }
}
package cn.zhukun.Entity;

public class Student {
    private int id;
    private String sno;//学号
    private String password;//密码

    public int getId() {
        return id;
    }

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

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

package cn.zhukun.Entity;

public class Teacher {
    private int id;
    private String tno;//教工号
    private String password;//密码

    public int getId() {
        return id;
    }

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

    public String getTno() {
        return tno;
    }

    public void setTno(String tno) {
        this.tno = tno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

7、Dao编写(BaseDao,AdminDao,StudentDao,TeacherDao)

package cn.zhukun.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.zhukun.Util.DbUtil;

/**
 *
 * @author llq
 *基础dao,封装基本操作
 */
public class BaseDao {
    private DbUtil dbUtil = new DbUtil();
    /**
     * 及时关闭数据库连接,释放资源
     */
    public void closeCon(){
        dbUtil.closeCon();
    }

    /**
     * 基础查询,多条查询
     */
    public ResultSet query(String sql){
        try {
            PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
            return prepareStatement.executeQuery();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /**
     *增删改
     */
    public boolean update(String sql){
        try {
            return dbUtil.getConnection().prepareStatement(sql).executeUpdate() > 0;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    public Connection getConnection(){
        return dbUtil.getConnection();
    }
}
package cn.zhukun.Dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import cn.zhukun.Entity.Admin;


/**
 *
 * @author llq
 *管理员数据库操作封装
 */
public class AdminDao extends BaseDao {
    //将从表单获取到的username和password作为参数传入,返回一个在数据库的user表中对应了用户名和密码的user对象
    /*
    * 1、如果成功返回一个user对象说明在数据库中找到和表单输入对应的用户名和密码,登录成功
    * 2、如果返回为空说明在数据库中没有找到和表单对应的用户名和密码,登录失败*/
    public Admin login(String username , String password){
        String sql = "select * from Admin where username = '" + username + "' and password = '" + password + "'";
        ResultSet resultSet = query(sql);
        try {
            if(resultSet.next()){
                Admin admin = new Admin();
                admin.setId(resultSet.getInt("id"));
                admin.setUsername(resultSet.getString("username"));
                admin.setPassword(resultSet.getString("password"));
                return admin;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
package cn.zhukun.Dao;

import cn.zhukun.Entity.Student;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDao extends BaseDao{
    public Student login(String sno,String password)
    {
        String sql = "select * from  Student where sno = '" + sno + "' and password = '" + password + "'";
        ResultSet resultSet = query(sql);
        try {
            if(resultSet.next()){
                Student student = new Student();
                student.setId(resultSet.getInt("id"));
                student.setSno(resultSet.getString("sno"));
                student.setPassword(resultSet.getString("password"));
                return student;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
package cn.zhukun.Dao;

import cn.zhukun.Entity.Student;
import cn.zhukun.Entity.Teacher;

import java.sql.ResultSet;
import java.sql.SQLException;

public class TeacherDao extends BaseDao {
    public Teacher login(String tno,String password)
    {
        String sql="select * from  Teacher where tno = '" + tno + "' and password = '" + password + "'";
        ResultSet resultSet = query(sql);
        try {
            if(resultSet.next()){
                Teacher teacher= new Teacher();
                teacher.setId(resultSet.getInt("id"));
                teacher.setTno(resultSet.getString("tno"));
                teacher.setPassword(resultSet.getString("password"));
                return teacher;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

8、Servlet编写(LoginServlet、VerifyCodeServlet)

package cn.zhukun.Servlet;

import cn.zhukun.Dao.AdminDao;
import cn.zhukun.Dao.StudentDao;
import cn.zhukun.Dao.TeacherDao;
import cn.zhukun.Entity.Admin;
import cn.zhukun.Entity.Student;
import cn.zhukun.Entity.Teacher;

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("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username= request.getParameter("username");
        String password = request.getParameter("password");
        //获取选择登陆对象的类型参数
        int type = Integer.parseInt(request.getParameter("type"));
        //验证码验证
        String imageText = request.getParameter("image");
        // 图片的验证码
        String text = (String) request.getSession().getAttribute("text");
        if (!text.equalsIgnoreCase(imageText)) {
            request.setAttribute("imageMess", "验证码输入错误!");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        //验证码验证通过,对比用户名密码是否正确
        switch (type) {
            case 1:{
                StudentDao studentDao = new StudentDao();
                Student student = studentDao.login(username,password);
                studentDao.closeCon();
                if (student == null)
                {
                    response.getWriter().write("学生登录失败");
                    return;
                }else {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", student);
                    session.setAttribute("userType", type);
                    response.getWriter().write("学生登录成功");
                }
                break;
            }
            case 2:{
                TeacherDao teacherDao = new TeacherDao();
                Teacher teacher = teacherDao.login(username,password);
                teacherDao.closeCon();
                if(teacher == null){
                    response.getWriter().write("教师登录失败");
                    return;
                }else{
                    HttpSession session = request.getSession();
                    session.setAttribute("user", teacher);
                    session.setAttribute("userType", type);
                    response.getWriter().write("教师登录成功");
                }
                break;
            }
            case 3:{
                AdminDao adminDao = new AdminDao();
                Admin admin = adminDao.login(username, password);
                adminDao.closeCon();
                if(admin == null){
                    response.getWriter().write("管理员登录失败");
                    return;
                }else {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", admin);
                    session.setAttribute("userType", type);
                    response.getWriter().write("管理员登录成功");
                }
                break;
            }
            default:
                break;
        }
    }
    //注销登录  退出
    private void logout(HttpServletRequest request,HttpServletResponse response) throws IOException{
        request.getSession().removeAttribute("user");
        response.sendRedirect("index.jsp");
    }
}
package cn.zhukun.Servlet;

import cn.zhukun.Util.VerifyCodeUtil;

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

/**
 * 用来生成图片验证码
 *
 */
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建对象
        VerifyCodeUtil vc = new VerifyCodeUtil();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        String text = vc.getText();
        // 将系统生成的文本内容保存到session中
        request.getSession().setAttribute("text", text);
        //向浏览器输出图片
        vc.output(bi, response.getOutputStream());

    }
}

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

  • 24
    点赞
  • 199
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值