您的位置:首页 > 其它

登陆验证码-----实现

2013-08-29 09:13 155 查看
方法一(通过servlet方式):

===========start================

public class AuthImg extends HttpServlet {

//private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

private Font mFont = new Font("Times New Roman", Font.PLAIN, 18);

// Initialize global variables

public void init(ServletConfig conf) throws ServletException {

super.init(conf);

}

// Process the HTTP Get request

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("image/jpeg");

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

ServletOutputStream out = response.getOutputStream();

int width = 60, height = 20;

BufferedImage image = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

Random random = new Random();

g.setColor(getRandColor(200, 250));

g.fillRect(0, 0, width, height);

g.setFont(mFont);

g.setColor(getRandColor(160, 200));

for (int i = 0; i < 155; i++) {

int x = random.nextInt(width);

int y = random.nextInt(height);

int xl = random.nextInt(12);

int yl = random.nextInt(12);

g.drawLine(x, y, x + xl, y + yl);

}

String rand = RandomChar.getChars(3,4);

char c;

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

c = rand.charAt(i);

g.setColor(new Color(20 + random.nextInt(110), 20 + random

.nextInt(110), 20 + random.nextInt(110))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成

g.drawString(String.valueOf(c), 13 * i + 6, 16);

}

HttpSession seesion = request.getSession();

seesion.setAttribute("authCode", rand);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(image);

out.close();

}

// Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

// Clean up resources

public void destroy() {

}

private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色

Random random = new Random();

if (fc > 255) {

fc = 255;

}

if (bc > 255) {

bc = 255;

}

int r = fc + random.nextInt(bc - fc);

int g = fc + random.nextInt(bc - fc);

int b = fc + random.nextInt(bc - fc);

return new Color(r, g, b);

}

}

-----web.xml中配置-------

<servlet>

<servlet-name>authimg</servlet-name>

<servlet-class>com.ue.common.util.AuthImg</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>authimg</servlet-name>

<url-pattern>/authimg</url-pattern>

</servlet-mapping>

<servlet>

----------------jsp页面及js------------------

---js----

function getImage(url)

{

$("#imgCode").removeAttr("src");

//$("#authCode").attr("src",url+"?it="+Math.random());

$("#imgCode").attr("src",url);

//document.forms[0].authCode.src=url;

}

---jsp----

<ul>

<li><h2>用户名:</h2><input id="usEname" name="usEname" type="text" onkeydown="enterTotab();" size="25" maxlength="20" tabindex="1" /></li>

<li><h2>密  码:</h2><input id="usPass" name="usPass" type="password" onkeydown="(window.event.keyCode==13)?submitForm():'';" size="25" maxlength="20" tabindex="2" /></li>

<li><h2>验证码:</h2><INPUT class=INPUT1 id="authCode" size=10 name=authCode maxlength="4"/> <img id="imgCode" name="authCode" alt="验证码" src="authimg" onclick="getImage('authimg')"/></li>

</ul>

-------------------

=========end===========

方法二(action方式):

/**

* 验证码生成

*/

public class ValidatecodeAction extends Action {

/*

* Generated Methods

*/

/**

* Method execute

* @param mapping

* @param form

* @param request

* @param response

* @return ActionForward

*/

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

String operation = request.getParameter(Constants.OPERATION_PARA_NAME);

// 新建

try {

int width = 50;

int height = 18;

// 取得一个4位随机字母数字字符串

String s = RandomStringUtils.random(4, false, true);

// 保存入session,用于与用户的输入进行比较.

// 注意比较完之后清除session.

HttpSession session = request.getSession(true);

session.setAttribute("validateCode", s);

response.setContentType("images/jpeg");

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

ServletOutputStream out = response.getOutputStream();

BufferedImage image = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

// 设定背景色

g.setColor(getRandColor(100, 250));

g.fillRect(0, 0, width, height);

// 设定字体

Font mFont = new Font("Arial", Font.ITALIC, 18);// 设置字体

g.setFont(mFont);

// 画边框

// g.setColor(Color.BLACK);

// g.drawRect(0, 0, width - 1, height - 1);

// 随机产生干扰线,使图象中的认证码不易被其它程序探测到

g.setColor(getRandColor(160, 200));

// 生成随机类

Random random = new Random();

for (int i = 0; i < 155; i++) {

int x2 = random.nextInt(width);

int y2 = random.nextInt(height);

int x3 = random.nextInt(12);

int y3 = random.nextInt(12);

g.drawLine(x2, y2, x2 + x3, y2 + y3);

}

// 将认证码显示到图象中

g.setColor(new Color(20 + random.nextInt(110), 20 + random

.nextInt(110), 20 + random.nextInt(110)));

g.drawString(s, 2, 16);

// 图象生效

g.dispose();

// 输出图象到页面

ImageIO.write((BufferedImage) image, "JPEG", out);

out.close();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色

Random random = new Random();

if (fc > 255)

fc = 255;

if (bc > 255)

bc = 255;

int r = fc + random.nextInt(bc - fc);

int g = fc + random.nextInt(bc - fc);

int b = fc + random.nextInt(bc - fc);

return new Color(r, g, b);

}

}

-----struts-config.xml中配置-------

<!--图片验证码 -->

<action path="/pubValidatecode" scope="request" type="admin.action.ValidatecodeAction" validate="false" >

<forward name="new" path="/WEB-INF/admin/adminUser/edit.jsp"/>

</action>

----------------jsp页面及js------------------

---js----

<script type="text/javascript">

function changeImage(){

//location.href="pubValidatecode.do?";

$("#aimage").removeAttr("src");

$("#aimage").attr("src","pubValidatecode.do?");

}

</script>

---jsp----

<li>

<span>验证码:</span>

<html:text property="validatecode" id="validatecode" styleClass="input" maxlength="4" style="width:35px;"/>

<img id="aimage" src="pubValidatecode.do?" style="cursor:pointer;" /> <a href="#" onclick="changeImage()" style="font-size:12px;">看不清?换一张</a>

</li>

-------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: