Servlet和Image如何做出一个验证码程序的完整版的源码?
马克-to-win: 根据上面程序,我做了一个验证码程序的大概。所有的技术点都已经涵盖了。有兴趣的同学可以自己把完整版的验证码程序做出来。
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
例:4.4.4
<%@ page contentType="text/html; charset=GBK"%>
<script type="text/javascript">
function flushcode(){
var fName=document.getElementById("code").alt;
// alert(fName);
document.getElementById("code").src="MarkToWinServlet"+"?Name="+fName+Math.random();
}
</script>
<img id="code" src="MarkToWinServlet" alt="马克-to-win"/>
<button onclick="flushcode()">刷新</button>
package com;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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 javax.servlet.http.HttpSession;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class ServletHello1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image = new BufferedImage(350, 30,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 350, 30);
Random r = new Random();
g.setColor(Color.red);
for (int i = 0; i < 200; i++) {
/* @param n the bound on the random number to be returned. Must be
* positive.
*/
int x = r.nextInt(350);
int y = r.nextInt(30);
/* the following draw a point instead of a line. */
g.drawLine(x, y, x, y);
}
String fNameGBK=null;
String fNameiso = request.getParameter("Name");
if(fNameiso==null) fNameGBK="马克-to-win初始";
System.out.println("fNameiso is" + fNameiso);
if (fNameiso != null) {
try {
fNameGBK = new String(fNameiso.getBytes("iso8859-1"), "GBK");
System.out.println(fNameiso + "" + fNameGBK);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// String code="1234";
HttpSession session = request.getSession();
session.setAttribute("code", fNameGBK);
System.out.println("session.getAttribute(code) is"
+ session.getAttribute("code"));
g.setColor(Color.black);
Font font = new Font("黑体", Font.BOLD + Font.ITALIC, 20);
g.setFont(font);
g.drawString(fNameGBK, 0, 20);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpeg", out);
}
}