图形验证码生成(地址为checkcode)
package servlet;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class CheckCode
*/
@WebServlet("/checkcode")
public class CheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CheckCode() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/jpeg");
HttpSession session=request.getSession();
int width=60;
int height=30;
//设置浏览器不要缓存此图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no=cache");
response.setDateHeader("Expires", 0);
//创建内存图像并获得其图形上下文
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
//产生随机验证码
//定义验证码的字符表
String chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands=new char[4];
for(int i=0;i<4;i++){
int rand=(int)(Math.random()*62);
rands[i]=chars.charAt(rand);
}
//产生图像
//画背景
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
//随机产生120个干扰点
for(int i=0;i<120;i++){
int x=(int)(Math.random()*width);
int y=(int)(Math.random()*height);
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
g.setColor(new Color(red,green,blue));
g.drawOval(x, y, 1, 0);
}
g.setColor(Color.BLACK);//设置字体为黑色
g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
//在不同的高度上输出验证码的不同字符
g.drawString(""+rands[0], 1, 17);
g.drawString(""+rands[1], 16, 15);
g.drawString(""+rands[2], 31, 18);
g.drawString(""+rands[3], 46, 16);
g.dispose();
//将图像输出到客户端
ServletOutputStream sos=response.getOutputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", baos);
byte[] buffer=baos.toByteArray();
response.setContentLength(buffer.length);
sos.write(buffer);
baos.close();
sos.close();
//将验证码放到session中
String str=new String(rands);
session.setAttribute("checkCode", str);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
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>登录页面</title>
</head>
<script type="text/javascript">
function refresh(){
document.getElementById("img1").src="checkcode?a="+Math.random();
}
</script>
<body>
<form method="get" name="form1">
用户名:<input type="text" name="userid"
onclick="mes.innerHTML=''"value="${param.userid}"/><br>
密码:<input type="password" name="userpwd" value="${param.userpwd}"/><br>
验证码:<input type="text" name="checkcode" />
<img border="0" src="checkcode" id="img1"/>
<input type="submit" value="换一张" onclick="refresh()"/><br>
<input type="submit" value="登录" onclick="form1.action='logcheck'">
<input type="reset" value="重置">
<div id="mes">${info}</div>
</form>
</body>
</html>
处理登录请求的servlet(地址为logcheck)
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LogCheck
*/
@WebServlet("/logcheck")
public class LogCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogCheck() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
String userid=request.getParameter("userid");
String userpwd=request.getParameter("userpwd");
String usercheckcode=request.getParameter("checkcode");
String info="";
HttpSession session=request.getSession();
String servercheckcode=(String)session.getAttribute("checkCode");
if(servercheckcode==null){
info="验证码为空!";
}
else if(!servercheckcode.equalsIgnoreCase(usercheckcode)){
info="验证码不正确,请重新输入";
}else if("张三".equals(userid)&&"123".equals(userpwd)){
info="登录成功!";
}else{info="用户名或密码错误!";}
request.setAttribute("info", info);
RequestDispatcher rd=request.getRequestDispatcher("/输入界面.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
其中两个servlet之间的传参也可使用request
request.getSession().setAttribute("checkCode", str);
request.getSession().getAttribute("checkCode");