java怎么显示网页验证码图片

Python012

java怎么显示网页验证码图片,第1张

这个的话,要涉及到jsp、servlet、网页,后台的请求了。我这里写一个给你看看吧。

https://github.com/chinameepo/com_dengc_gradute_struts_learn/tree/master/Myfirst ,这个是我的github仓库,里面刚好就有个一个我自己写的输出验证码的。

使用ide:myeclipse

jdk:1.6.0

服务器:tomcat

原理,在servlet中随机生成一个4位数字1000-9999

然后把这数字写入session

输出一个图片,上面写有这四个数字

在服务器端根据用户输入的数字和

session中的值比较。

注意比较结束后要清空session中的值

有很多人问到验证码的作用。

我作个简单的解释。

验证码的作用:有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上是用验证码是现在很多网站通行的方式(比如招商银行的网上个人银行,腾讯的QQ社区),我们利用比较简易的方式实现了这个功能。虽然登陆麻烦一点,但是对社区还来说这个功能还是很有必要,也很重要。但我们还是提醒大家主要保护自己的密码,尽量使用混杂了数字、字母、符号在内的6位以上密码,不要使用诸如1234之类的简单密码或者与用户名相同、类似的密码。

还有就是注册时发表文章时加验证码,就防人用注册机,无限的自动注册,

package com.schoolwx.util

import java.io.*

import java.util.*

import com.sun.image.codec.jpeg.*

import javax.servlet.*

import javax.servlet.http.*

import java.awt.*

import java.awt.image.*

public class getImg extends HttpServlet {

private Font mFont=new Font("宋体", Font.PLAIN,12)//设置字体

//处理post

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException {

doGet(request,response)

}

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException {

//取得一个1000-9999的随机数

String s=""

int intCount=0

intCount=(new Random()).nextInt(9999)//

if(intCount<1000)intCount+=1000

s=intCount+""

//对session付值。

HttpSession session=request.getSession (true)

session.setAttribute("getImg",s)

response.setContentType("image/gif")

ServletOutputStream out=response.getOutputStream()

BufferedImage image=new BufferedImage(35,14,BufferedImage.TYPE_INT_RGB)

Graphics gra=image.getGraphics()

//设置背景色

gra.setColor(Color.yellow)

gra.fillRect(1,1,33,12)

//设置字体色

gra.setColor(Color.black)

gra.setFont(mFont)

//输出数字

char c

for(int i=0i<4i++) {

c=s.charAt(i)

gra.drawString(c+"",i*7+4,11)//7为宽度,11为上下高度位置

}

JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out)

encoder.encode(image)

out.close()

}

}