需求:

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

分析:

代码实现:

  login.jsp 页面

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<script> window.onloa = function() {
// 刷新验证码
document.getElementById("img").onclick = function() {
this.src = "/day13/checkcodeservletdemo"+new Date().getTime();
}
}
</script>
<style> div {
color:red;
}
</style> <body>
<form action="/day13/loginservletdemo" 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="/day13/checkcodeservletdemo"></td>
</tr> <tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table> <div><%=request.getAttribute("cc_error") == null ? "":request.getAttribute("cc_error") %></div>
<div><%=request.getAttribute("login_error") == null ? "":request.getAttribute("login_error") %></div> </form>
</body>
</html>

  success 页面

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

  生成验证码 servlet

 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("/checkcodeservletdemo")
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_BGR); // 2 修饰图片
// 2.1 填充背景色
Graphics g = image.getGraphics(); //获取画笔对象
g.setColor(Color.pink); // 设置画笔颜色
g.fillRect(0,0,width,height); // 绘制一个矩形,给定坐标与宽高 // 2.2 画边框
g.setColor(Color.blue); // 设置画笔颜色
g.drawRect(0,0,width-1,height-1); // 给图像绘制边框 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成随机角标
Random ran = new Random(); StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);//随机字符
sb.append(ch); //2.3写验证码
g.drawString(ch+"",width/5*i,height/2);
} String checkCode_session = sb.toString();
// 将验证码存入 session
request.getSession().setAttribute("checkCode_session",checkCode_session); //2.4画干扰线
g.setColor(Color.GREEN); // 随机生成坐标点 for (int i = 0; i < 6; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width); int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2); // 画干扰线
} // 3 将图片输出到页面展示:通过response 的 字符流,将图片输出到浏览器上
ImageIO.write(image,"jpg",response.getOutputStream());
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

  登录 servlet

 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("/loginservletdemo")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 设置编码
request.setCharacterEncoding("utf-8");
// 2. 获取参数
//Map<String, String[]> map = request.getParameterMap(); String username = request.getParameter("username");
String password = request.getParameter("password");
String checkcode = request.getParameter("checkcode"); // 3.先判断验证码是否正确
// 获取生成验证码
HttpSession session = request.getSession();
String checkCode_session = (String) session.getAttribute("checkCode_session");
// 删除 session中存储的验证码
session.removeAttribute("checkCode_session"); // 判断,忽略大小写
if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkcode)) {
//验证码正确
// 判断用户名和密码是否一致
if("zhangsan".equals(username) && "123".equals(password)) {
// 登录成功
// 存储用户信息 session.setAttribute("user",username);
// 重定向到 success.jsp
response.sendRedirect(request.getContextPath()+"/success.jsp");
}else {
// 存储提示信息到request
request.setAttribute("login_error","用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
} } else {
// 验证码不正确
// 存储提示信息到request
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);
}
}

最新文章

  1. ASP.NET MVC中获取URL地址参数的两种写法
  2. python 3.5.2 install pillow
  3. Mathematica(MMA)闪电入门系列 目录与说明
  4. Java for LeetCode 040 Combination Sum II
  5. hdu 2686 Matrix 最小费用最大流
  6. JNDI和在tomcat中配置DBCP连接池 元数据的使用 DBUtils框架的使用 多表操作
  7. Ubuntu 安装和配置minicom
  8. Spring MVC的文件上传
  9. 扒一扒offsetleft,srollleft,pagex,clientx,postion().left等精确位置的获取与理解
  10. 简述java接口和C++虚类的相同和不同之处
  11. mongos-sharding连接池配置
  12. ES6使用fetch请求数据
  13. Day27--Python--初识socket
  14. 【tmos】字段update_time如何动态的更新
  15. Hadoop之mapreduce
  16. CentOS7安装配置Bacula yum方法
  17. js跨域调用mvc ActionResult扩展
  18. Problem A: 踢罐子 解题报告
  19. 第1章 1.6计算机网络概述--OSI参考模型
  20. UGUI简易摇杆

热门文章

  1. ChannelEventRunnable handle RECEIVED operation error, channel is NettyChannel解决方法
  2. Windows删除空文件夹问题带来的学习与思考
  3. ImportError: this is MySQLdb version (1, 2, 5, &#39;final&#39;, 1), but _mysql is version (1, 4, 4, &#39;final&#39;, 0)
  4. django入门8之xadmin引入富文本和excel插件
  5. QT5.12 qtcreate 在Ubuntu14.04
  6. Excel VBA解读(54):排序——Sort方法
  7. (原)ffmpeg中的writing_filter翻译
  8. 使用Port Forwarding连接k8s集群的pod(redis、mysql等)
  9. Spring BeanFactory 初始化 和 Bean 生命周期
  10. 【ARM-Linux开发】ARM嵌入式设备Linux系统启动步骤和方式