public class CodeServlert extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用jar生产验证码
ValidateCode vCode = new ValidateCode(100, 25, 4, 9);
//获取生产的验证码字符串
String code =vCode.getCode();
//传值方式1.拼接网址字符串 2.使用域对象
//使用session 来储存验证码
request.getSession().setAttribute("wcode", code);
System.out.println(code);
//写到网页上 (通过 响应中的字符流 写回网页)
vCode.write(response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function changeCode() {
//从文档中取出img图片
var img = document.getElementsByTagName("img")[0];
//获取图片的src 属性 并赋值
//注意:如果请求网址完全相同 则浏览器不会帮你刷新
//可以拼接当前时间 让每次请求的网址都不一样
img.src = "/SH-web-servlet04/code?time "+ new Date().getTime();
}
</script>
</head> <!-- com.lanou3g.code.Dologin -->
<%
// 书写java代码
//获取 request 域中的数据
String msg= (String)request.getAttribute("msg");
if(msg!=null){
out.write(msg);
}
%>
<form action="/SH-web-servlet04/dologin" method="post">
用户名:<input type="text" name="userName"/><br>
密码:<input type="password" name="pwd"/><br>
验证码:<input type="text" name="code"/>
<img src="/SH-web-servlet04/code" onclick="changeCode()"/>
<a href="javascript:changeCode()">看不清换一张</a>
<br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>
登陆功能验证码校验功能
public class Dologin extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(123123);
//设置响应编码格式
response.setContentType("text/html;charset=UTF-8");
//告诉服务器 请求的内容是什么编码格式的
request.setCharacterEncoding("UTF-8");
//获取到请求过来的参数(表单提交过来的数据)
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String code = request.getParameter("code");
//获取域中的session
HttpSession session = request.getSession();
String wcode = (String)session.getAttribute("wcode");
PrintWriter out = response.getWriter();
System.out.println(userName + pwd + code);
// wanglong 123
if (userName.equals("wanglong") && pwd.equals("123")) {
System.out.println(1230);
//判断验证码(忽略大小写)
if (!code.equalsIgnoreCase(wcode)) {
//提示用户 验证码有误
//把错误信息 从 dologin 页面传到 1.jsp页面上
//使用request域 保存 验证码错误的信息
request.setAttribute("msg", "验证码输错了");
//请求转发
request.getRequestDispatcher("/1.jsp").forward(request, response);
}
}else {
//提示登陆失败
//2秒回登陆页面
response.getWriter().write("登陆失败");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}