3、利用Session实现一次性验证码 ,类似下图,当正确时转到成功页面
第一步:新建login.jsp
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PHBvpUju-1618118775840)(C:\Users\16286\AppData\Roaming\Typora\typora-user-images\image-20210411131653436.png)]](https://i-blog.csdnimg.cn/blog_migrate/c15e4ca4d92d96297a2bff1567a155be.png)
第二步:login.jsp内容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
table {
border: 1px solid lightgray;
margin: auto;
}
body{
text-align: center;
padding-top: 50px;
}
label{
width: 40px;
}
div{
color: red;
}
</style>
</head>
<body>
<form method="post" action="<%=request.getContextPath() %>/LoginServlet">
<table cellspacing="0" cellpadding="5px" >
<tr>
<td><label for="username">用户名:</label></td>
<td><input type="text" id="username" name="username" width="100px" placeholder="请输入用户名"> </td>
</tr>
<tr>
<td><label for="username">密码:</label></td>
<td><input type="password" id="password" name="password" width="100px" placeholder="请输入密码" > </td>
</tr>
<tr>
<td><label for="v_code">验证码:</label></td>
<td>
<input type="text" id="v_code" name="v_code" width="100px" placeholder="请输入验证码" >
<img src="<%=request.getContextPath() %>/ValidateCodeServlet" id="img"/>
<a href="<%=request.getContextPath() %>/login.jsp" id="a">看不清?点击换一张</a>
</td>
</tr>
<tr>
<td style="text-align: center"> <input type="submit" value="登录" > </td>
</tr>
</table>
</form>
<div>
<%--三元运算符 判断如果==null 则显示空字符 不等于null 原样显示--%>
<%= request.getAttribute("v_code_err")==null? "":request.getAttribute("v_code_err") %>
</div>
<script>
var img=document.getElementById("img");
img.οnclick=function () {
img.src="/ValidateCodeServlet";
}
var a=document.getElementById("a");
a.οnclick=function () {
img.src="/CheckCodeServlet";
}
</script>
</body>
</html>
第三步:运行查看效果
这里验证码还不能显示,下面会讲解如何显示验证码,不要着急~
我是已经写完了,所以能显示
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dB3WqqOq-1618118775842)(C:\Users\16286\AppData\Roaming\Typora\typora-user-images\image-20210411131828420.png)]](https://i-blog.csdnimg.cn/blog_migrate/048d113bfc820f2e182f96603651cc88.png)
第四步:创建LoginServlet
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ekQVl3Id-1618118775845)(C:\Users\16286\AppData\Roaming\Typora\typora-user-images\image-20210411131924011.png)]](https://i-blog.csdnimg.cn/blog_migrate/7d7ee68a4be663d8b60a46abe6eabdb4.png)
第五步:编写LoginServlet的doGet方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String v_code = request.getParameter("v_code");
// 获取session里面的验证码
String session_code = request.getSession().getAttribute("check_code").toString();
JavaWeb利用Session实现一次性验证码

最低0.47元/天 解锁文章
1675

被折叠的 条评论
为什么被折叠?



