方式一:(后台生成验证码)
(1):jsp页面
<img id="vcode_img" alt="点击更换" title="点击更换" src="${pageContext.request.contextPath}/user/getVerifyCode.do"
onclick="javascript:document.getElementById('vcode_img').src='${pageContext.request.contextPath}/user/getVerifyCode.do?'+new Date();" >
(2):Controller层
@Autowired
private VerifyCode vc;
@RequestMapping(value = "/user/getVerifyCode.do")
public void getVerifyCode(HttpServletResponse response){
BufferedImage b = vc.getImage();
try {
ImageIO.write(b, "jpg", response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
(3):验证码类VerifyCode
在xml文件中实例化VerifyCode类
<bean id="verifyCode" class="com.csdn.common.vcode.VerifyCode"></bean>
方式二:(前台生成验证码)
(1):jsp页面
<img id="vcode_img" alt="点击更换" title="点击更换" src="${pageContext.request.contextPath }/validatecode.jsp"
onclick="javascript:document.getElementById('vcode_img').src='${pageContext.request.contextPath }/validatecode.jsp?'+new Date();">
(2):validatecode.jsp生成验证码
将图片上的文字保存到session域中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ 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 = 80;
int height = 32;
//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);//将图片上的文字保存到session域中
g.setColor(new Color(0, 100, 0));
g.setFont(new Font("Candara", Font.BOLD, 24));
g.drawString(capstr, 8, 24);
g.dispose();
response.setContentType("image/jpeg");
out.clear();
out = pageContext.pushBody();
OutputStream strm = response.getOutputStream();
ImageIO.write(image, "jpeg", strm);
strm.close();
%>