验证码很重要,它能有效防止对某一个特定注册用户用程序暴力破解方式进行不断的登陆尝试,降低了密码被破解的概率,也降低了服务器的压力。一般生成一个随机码的图片。这篇文章将探讨在jsp页面生成jpeg格式的临时图片验证码,并结合jsf实现登录的验证。
1. 验证码的生成页面:validateCode.jsp
<%@ page import="java.util.Random"%><%@ page
import="java.io.OutputStream"%><%@ page import="java.awt.Color"%><%@ page
import="java.awt.Font"%><%@ page import="java.awt.Graphics"%><%@ page
import="java.awt.image.BufferedImage"%><%@ page
import="javax.imageio.ImageIO"%>
<%
int width = 60;
int height = 22;
//create the image
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// set the background color
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// draw the border
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// create a random instance to generate the codes
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
// make some confusion
for (int i = 0; i < 50; i++)
{
int x = rdm.nextInt(width);
int y = rdm.nextInt(height);
g.drawOval(x, y, 0, 0);
}
// generate a random code
String capstr = hash1.substring(0, 4);
session.setAttribute("key",capstr);
g.setColor(new Color(0, 100, 0));
g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
g.drawString(capstr, 11, 17);
g.dispose();
response.setContentType("image/jpeg");
out.clear();
out = pageContext.pushBody();
OutputStream strm = response.getOutputStream();
ImageIO.write(image, "jpeg", strm);
strm.close();
%>
2. xhtml页面 login.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
......
<h:inputText size="14" id="uservalidate" value="#{blogin.validateCode}" />
<img src="validateCode.jsp" title="点击更换" align="absmiddle" style="cursor:pointer;" onClick="window.location.href=window.location.href" />
<h:commandButton value="登录" action="#{blogin.login}" />
......
</html>
3.BackBean LoginBackBean.java
public class LoginBackBean
{
private String validateCode;
public String getValidateCode()
{
return validateCode;
}
public void setValidateCode(String validateCode)
{
this.validateCode = validateCode;
}
public String login()
{
String key = (String)( ((HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(true)).getAttribute("key"));
if (!key.equals(validateCode))
{
setLoginError("验证码错误!");
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR, "", "验证码错误");
FacesContext.getCurrentInstance().addMessage(null, message);
return "failure";
}
return "success";
}
}