Servlet+JDBC实现登陆功能的小例子(带验证码)

作者:大象大象你的鼻子怎么那么长 时间:2021-05-29 03:04:25 

案例需求:访问带有验证码的登录页面login.jsp用户输入用户名,密码以及验证码。如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误如果验证码输入有误,跳转登录页面,提示:验证码错误如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您分析

Servlet+JDBC实现登陆功能的小例子(带验证码)

步骤

文件树展示

Servlet+JDBC实现登陆功能的小例子(带验证码)

1.配置文件和jar包在上个案例均有配置过,需要改的有:User类新增验证码成员变量,数据库增加了一个验证码字段(无用,只是为了UserDao包把查找到的数据值导入到User类不出错)。

2.登陆界面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>login</title>
 <script>
   window.onload = function(){
     document.getElementById("img").onclick = function(){
       this.src="/CaS/checkCodepic?time="+new Date().getTime();
     }
   }
 </script>
 <style>
   div{
     color: red;
   }
 </style>
</head>
<body>

<form action="/CaS/loginServlet" method="post">
   <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="img" src="/CaS/checkCodepic"></td>
     </tr>
     <tr>
       <td colspan="2"><input type="submit" value="登录"></td>
     </tr>
   </table>

</form>

<div><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></div>
 <div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div>

</body>
</html>

3.验证码,画了个验证码,每次都把随机数加入session中以便进行对比


package Test;

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("/checkCodepic")
public class CheckCodepic extends HttpServlet {
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   int width=100;
   int height=50;
   //创建图片对象
   BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

//美化图片
   //创建画笔
   Graphics g = image.getGraphics();
   //画笔颜色
   g.setColor(Color.pink);
   //画个矩形,填充为粉红色
   g.fillRect(0,0,width,height);
   //给矩形加边框
   g.setColor(Color.blue);
   g.drawRect(0,0,width-1,height-1);
   //写字母或数字
   g.setColor(Color.green);
   String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   Random rd=new Random();
   StringBuilder sb=new StringBuilder();
   for(int i=1;i<=4;i++){
     int index = rd.nextInt(str.length());
     char c = str.charAt(index);
     sb.append(c);
     g.drawString(c+"",width/5*i,height/2);
   }
   String checkCode_session = sb.toString();
   //将验证码存入session
   req.getSession().setAttribute("checkCode_session",checkCode_session);
   //加干扰线
   g.setColor(Color.blue);
   for(int i=1;i<=10;i++){
     int x1 = rd.nextInt(width);
     int x2 = rd.nextInt(width);
     int y1 = rd.nextInt(height);
     int y2 = rd.nextInt(height);
     g.drawLine(x1,y1,x2,y2);
   }

//输出展示
   ImageIO.write(image,"jpg",resp.getOutputStream());
 }

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

4.loginServlet类,用来判断验证码和用户名密码是否正确,注意先判断验证码;注意重定向和请求转发的不同,还有session的应用。


package Test;

import Test.dao.UserDao;
import Test.userclass.User;
import org.apache.commons.beanutils.BeanUtils;

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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   //设置request编码
   request.setCharacterEncoding("utf-8");
   //获取参数
//    String username = request.getParameter("username");
//    String password = request.getParameter("password");
//    String checkCode = request.getParameter("checkCode");
//    User user=new User();
//    user.setUsername(username);
//    user.setPassword(password);
//    user.setCheckCode(checkCode);
   Map<String, String[]> parameterMap = request.getParameterMap();
   User user=new User();
   try {
     BeanUtils.populate(user,parameterMap);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
   UserDao userDao=new UserDao();
   //先判断验证码是否正确
   String checkCode_session = (String)request.getSession().getAttribute("checkCode_session");
   request.getSession().removeAttribute("checkCode_session");
   if(checkCode_session!=null && checkCode_session.equalsIgnoreCase(user.getCheckCode())){//忽略大小写
     //如果正确,判断用户名密码是否正确
     User login = userDao.login(user);
     if(login!=null){
       //登陆成功,存储用户信息
       request.getSession().setAttribute("username",login.getUsername());
       //重定向到success.jsp
       response.sendRedirect(request.getContextPath()+"/success.jsp");

}else{//登陆失败,转发到登陆界面
       request.setAttribute("login_error","用户名或密码不正确");
       request.getRequestDispatcher("/login.jsp").forward(request,response);

}
   }else{ //如果不正确,转发到登陆界面
     request.setAttribute("cc_error","验证码不正确");
     request.getRequestDispatcher("/login.jsp").forward(request,response);

}
 }

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

5.成功登陆界面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Title</title>
</head>
<body>

<h1><%=request.getSession().getAttribute("username")%>,欢迎您</h1>

</body>
</html>

结果

登陆界面

Servlet+JDBC实现登陆功能的小例子(带验证码)

验证码错误情况

Servlet+JDBC实现登陆功能的小例子(带验证码)

用户名或密码不正确情况

Servlet+JDBC实现登陆功能的小例子(带验证码)

成功登陆

Servlet+JDBC实现登陆功能的小例子(带验证码)

来源:https://blog.csdn.net/weixin_41541562/article/details/106894355

标签:Servlet,JDBC,登陆
0
投稿

猜你喜欢

  • Java中JDBC连接数据库详解

    2023-08-10 16:57:18
  • C#设置Word文档背景的三种方法(纯色/渐变/图片背景)

    2022-07-08 01:33:09
  • java private关键字用法实例

    2022-01-16 10:08:06
  • Java通过FTP服务器上传下载文件的方法

    2021-08-15 07:26:39
  • 在IDEA中maven配置MyBatis的流程详解

    2021-08-26 17:02:27
  • Java适配器模式_动力节点Java学院整理

    2021-09-06 10:50:53
  • mybatis批量新增、删除、查询和修改方式

    2023-11-23 10:13:01
  • Spring boot如何快速的配置多个Redis数据源

    2023-05-12 18:27:32
  • Java面试必备八股文整理

    2023-11-29 12:03:50
  • java与c#的语法区别详细介绍

    2022-05-02 14:01:10
  • mybatis-plus分页查询三种方法小结

    2023-11-13 08:44:26
  • Android采取ContentObserver方式自动获取验证码

    2023-07-31 16:20:48
  • 详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑

    2021-06-01 07:28:41
  • java并发编程包JUC线程同步CyclicBarrier语法示例

    2023-01-18 07:44:58
  • Java关键字instanceof的两种用法实例

    2023-07-31 06:24:50
  • java String 转成Double二维数组的方法

    2023-04-28 12:11:02
  • java 实现文件复制和格式更改的实例

    2023-10-21 08:07:49
  • 使用JavaWeb webSocket实现简易的点对点聊天功能实例代码

    2023-10-29 00:14:17
  • List集合对象中按照不同属性大小排序的实例

    2023-06-07 14:27:41
  • 从dubbo zookeeper注册地址提取出zookeeper地址的方法

    2023-04-29 18:51:16
  • asp之家 软件编程 m.aspxhome.com