您的位置:首页 > 其它

001——response生成图片验证码

2016-06-21 17:41 381 查看
用户登录界面


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function reloadImage() {
document.getElementById('btn').disabled = true;
document.getElementById('identify').src = 'IdentifyServlet?ts=' + new Date().getTime();
}
</script>
</head>

<body>
<div align="center">
<table>
<tr>
<td>
<form method="post" action="LoginServlet">
<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><img src="IdentifyServlet" id="identify" onload="btn.disabled=false;"/></td>
<td><input type="text" name="identifyCode"><input type="button" value="换张图片" id="btn" onclick="reloadImage()"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</div>
</body>
</html>


验证码生成代码

package com.java.identifyCode;

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

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class IdentifyServlet extends HttpServlet {

public static final char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
//生成随机数
public static Random random = new Random();

//获取刘伟随机数
public static String getRandomString() {
StringBuffer sb = new StringBuffer();
for (int i=0; i<4; i++) {
sb.append(CHARS[random.nextInt(CHARS.length)]);
}
return sb.toString();
}

//获取随机的颜色
public static Color getRandomColor() {
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}

//返回某颜色的反色
public static Color getReverseColor(Color color) {
return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue());
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置输出类型
response.setContentType("image/jpeg");
//获取随机字符串并放到session域中
String randomString = getRandomString();
request.getSession(true).setAttribute("code", randomString);
//设置图片的宽跟高
int width = 80;
int height = 20;
//随机颜色用于背景色
Color color = getRandomColor();
//反色用于前景色
Color reverse = getReverseColor(color);
//创建彩色图片
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取绘图对象
Graphics2D g = bi.createGraphics();
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
//		g.setColor(color);
g.fillRect(0, 0, width, height);
g.setColor(reverse);
g.drawString(randomString, 18, 20);
//画最多100个噪声点
for (int i=0; i<50; i++) {
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
//转换成jpeg
ServletOutputStream out = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//对图片进行编码
encoder.encode(bi);
out.flush();
}

}
登录验证

package com.java.identifyCode;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

public 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");
<span style="white-space:pre">		</span>//忽略大小写
String identifyCode = request.getParameter("identifyCode").toLowerCase();
String code = ((String) request.getSession().getAttribute("code")).toLowerCase();
if(username=="" || password=="" || identifyCode=="") {
request.setAttribute("msg", "登录失败");
request.getRequestDispatcher("/MyJsp.jsp").forward(request, response);
} else if(username.equals("admin") && password.equals("password") && identifyCode.equals(code.toLowerCase())) {
request.setAttribute("msg", "登录成功");
request.getRequestDispatcher("/MyJsp.jsp").forward(request, response);
} else {
request.setAttribute("msg", "用户名或密码或验证码错误");
request.getRequestDispatcher("/MyJsp.jsp").forward(request, response);
}
}

}
转发页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'MyJsp.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
This is my ${msg } JSP page. <br>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: