生成驗證碼的基本過程是:
<%@ page language=java import=java.util.* pageEncoding=UTF-8%>
<%@ page import=java.awt.*,java.awt.image.BufferedImage,javax.imageio.ImageIO %>
<%
response.setHeader(Cache-Control, no-cache);
int width=60,height=20;
BufferedImage image=new BufferedImage( width,height,BufferedImage.TYPE_INT_RGB);
//由bufferdImage對象獲得畫筆g
Graphics g=image.getGraphics();
//畫筆填充矩形
g.setColor(new Color(200,200,200));
g.fillRect(0, 0, width, height);
//生成隨機數
Random rd=new Random();
int rdNum=rd.nextInt(8999)+1000;
String rdstr=String.valueOf(rdNum);
//把隨機數放入session中
session.setAttribute(rdStr, rdstr);
//畫筆g畫隨機數
g.setColor(Color.BLUE);
g.setFont(new Font(,Font.PLAIN,20));
g.drawString(rdstr, 10, 20);//這裡的坐標是一個字符的左下角基線
//畫100個隨機點
g.setColor(Color.green);
for(int i=0;i<100;i++){
int x=rd.nextInt(width);
int y=rd.nextInt(height);
g.drawOval(x, y, 1, 1);
}
//用ImageIO的靜態函數write輸出圖像
ImageIO.write(image, JPEG, response.getOutputStream());
out.clear();
out=pageContext.popBody();
%>
畫圖的基本思想是:
<%@ page language=java import=java.util.* pageEncoding=UTF-8%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+://+request.getServerName()+:+request.getServerPort()+path+/;
%>
<script type=text/javascript>
function refresh(){ document.loginform.imgcode.src=http://blog.csdn.net/tuke_tuke/article/details/codes.jsp;
}
</script>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class codeServlet extends HttpServlet {
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取表單的驗證碼
String code=request.getParameter(yanzhengma);
//獲取session中的驗證碼
HttpSession session=request.getSession();
String randstr=(String) session.getAttribute(rdStr);
response.setCharacterEncoding(gb2312);//respons設為中文編碼
PrintWriter out=response.getWriter();//獲得輸出寫出器
if(code.equals(randstr)){//輸入的驗證碼和session保存的驗證碼相比較
out.println(恭喜你,驗證碼正確!);
}
else{
//response.sendRedirect(/code/back.jsp);
out.println(驗證碼錯誤!!);
}
}
}
輸入結果是: