验证码生成无敌版

Posted Ashan-Da宝旗

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证码生成无敌版相关的知识,希望对你有一定的参考价值。

1.创建一个servlet

package cn.itcast.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import cn.itcast.common.web.SessionProvider;

/**
 * 提供验证码图片的Servlet
 */
@SuppressWarnings("serial")
public class JcaptchaServlet extends HttpServlet 
	public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";

	private ImageCaptchaService captchaService;
	
	private SessionProvider session;

	@Override
	public void init() throws ServletException 
		WebApplicationContext appCtx = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		captchaService = (ImageCaptchaService) BeanFactoryUtils
				.beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);
		session = (SessionProvider) BeanFactoryUtils
				.beanOfTypeIncludingAncestors(appCtx, SessionProvider.class);
	

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException 
		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try 
			// get the session id that will identify the generated captcha.
			// the same id must be used to validate the response, the session id
			// is a good candidate!

			String captchaId = session.getSessionId(request);
			BufferedImage challenge = captchaService.getImageChallengeForID(
					captchaId, request.getLocale());
			// Jimi.putImage("image/jpeg", challenge, jpegOutputStream);
			ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
		 catch (IllegalArgumentException e) 
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		 catch (CaptchaServiceException e) 
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		
		// catch (JimiException e) 
		// response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		// return;
		// 

		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

		// flush it in the response
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	


2.创建一个一个xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
	default-lazy-init="true">

	<bean id="captchaService" class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">
		<constructor-arg index="0" ref="imageEngine"/>
		<constructor-arg type="int" index="1" value="180"/>
		<constructor-arg type="int" index="2" value="100000"/>
		<constructor-arg type="int" index="3" value="75000"/>
	</bean>
	<bean id="imageEngine" class="com.octo.captcha.engine.GenericCaptchaEngine">
		<constructor-arg index="0">
			<list>
				<ref bean="captchaFactory"/>
			</list>
		</constructor-arg>
	</bean>

	<bean id="captchaFactory" class="com.octo.captcha.image.gimpy.GimpyFactory">
		<constructor-arg>
			<ref bean="wordgen"/>
		</constructor-arg>
		<constructor-arg>
			<ref bean="wordtoimage"/>
		</constructor-arg>
	</bean>

	<bean id="wordgen" class= "com.octo.captcha.component.word.wordgenerator.RandomWordGenerator">		
		<!--可选字符-->
		<constructor-arg>
			<value>aabbccddeefgghhkkmnnooppqqsstuuvvwxxyyzz</value>
		</constructor-arg>
	</bean>

	<bean id="wordtoimage" class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage">
		<constructor-arg index="0">
			<ref bean="fontGenRandom"/>
		</constructor-arg>
		<constructor-arg index="1">
			<ref bean="backGenUni"/>
		</constructor-arg>
		<constructor-arg index="2">
			<ref bean="decoratedPaster"/>
		</constructor-arg>
	</bean>

	<bean id="fontGenRandom" class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator">
		<!--最小字体-->
		<constructor-arg index="0">
			<value>26</value>
		</constructor-arg>
		<!--最大字体-->
		<constructor-arg index="1">
			<value>34</value>
		</constructor-arg>
		<constructor-arg index="2">
			<list>
				<bean class="java.awt.Font">
					<constructor-arg index="0"><value>Arial</value></constructor-arg>
					<constructor-arg index="1"><value>0</value></constructor-arg>
					<constructor-arg index="2"><value>32</value></constructor-arg>
				</bean>
			</list>
		</constructor-arg>
	</bean>
	<bean id="backGenUni" class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator">
		<!--背景宽度-->
		<constructor-arg index="0">
			<value>110</value>
		</constructor-arg>
		<!--背景高度-->
		<constructor-arg index="1">
			<value>50</value>
		</constructor-arg>
	</bean>

	<bean id="decoratedPaster" class="com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster">
		<!--最大字符长度-->
		<constructor-arg type="java.lang.Integer" index="0">
			<value>4</value>
		</constructor-arg>
		<!--最小字符长度-->
		<constructor-arg type="java.lang.Integer" index="1">
			<value>4</value>
		</constructor-arg>
		<!--文本颜色-->
		<constructor-arg index="2">
			<ref bean="colorGen"/>
		</constructor-arg>
		<!--文本混淆-->
		<constructor-arg index="3">
			<list>
				<!--<ref bean="baffleDecorator"/>-->
			</list>
		</constructor-arg>
	</bean>	
	<bean id="baffleDecorator" class="com.octo.captcha.component.image.textpaster.textdecorator.BaffleTextDecorator">
		<constructor-arg type="java.lang.Integer" index="0"><value>1</value></constructor-arg>
		<constructor-arg type="java.awt.Color" index="1"><ref bean="colorWrite"/></constructor-arg>
	</bean>
	<bean id="colorGen" class="com.octo.captcha.component.image.color.SingleColorGenerator">
		<constructor-arg type="java.awt.Color" index="0">
			<ref bean="colorBlack"/>
		</constructor-arg>
	</bean>
	<bean id="colorWrite" class="java.awt.Color">
		<constructor-arg type="int" index="0">
			<value>255</value>
		</constructor-arg>
		<constructor-arg type="int" index="1">
			<value>255</value>
		</constructor-arg>
		<constructor-arg type="int" index="2">
			<value>255</value>
		</constructor-arg>
	</bean>
	<bean id="colorBlack" class="java.awt.Color">
		<constructor-arg type="int" index="0">
			<value>50</value>
		</constructor-arg>
		<constructor-arg type="int" index="1">
			<value>50</value>
		</constructor-arg>
		<constructor-arg type="int" index="2">
			<value>50</value>
		</constructor-arg>
	</bean>
</beans>
3,在web.xml配置servlet

<servlet>
		<servlet-name>captcha</servlet-name>
		<servlet-class>cn.itcast.common.JcaptchaServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>captcha</servlet-name>
		<url-pattern>/captcha.svl</url-pattern>
	</servlet-mapping>
	</web-app>

4.创建一个session共享类,用于创建session,获取session和销毁session 并交给spring管理

package cn.itcast.common.web;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class HttpSessionProvide implements SessionProvider

	public void setAttribute(HttpServletRequest request, String name, Serializable value) 
		HttpSession session = request.getSession();
		session.setAttribute(name, value);
		
	

	public Serializable getAttribute(HttpServletRequest request, String name) 
		HttpSession session = request.getSession(false);
		if (session != null) 
			return(Serializable) session.getAttribute(name);
		
		return null;
	

	public void logout(HttpServletRequest request) 
		HttpSession session = request.getSession(false);
		if (session != null) 
			session.invalidate();
		
	

	public String getSessionId(HttpServletRequest request) 
		return request.getSession().getId();
	


在spring里面注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	 <!-- session实例化-->
	<bean id="sessionProvider" class="cn.itcast.common.web.HttpSessionProvide"></bean>
	 
</beans>

最后获取生成的验证吗图片

<img src="/captcha.svl" οnclick="this.src='captcha.svl?d='+new Date()" class="code" alt="换一张" /><a href="javascript:void(0);" οnclick="$('.code').attr('src','/captcha.svl?d='+new Date())" title="换一张">换一张</a></li>


效果图




以上是关于验证码生成无敌版的主要内容,如果未能解决你的问题,请参考以下文章

JavaWeb使用Kaptcha生成验证码(jar版)

无敌版头文件——万能头

用c语言编程求 18位 身份证的验证码

急求!1急求!!用c语言实现类似网页验证码的算法。拜托啦!!!

验证码识别100%?我飘了...

selenium自动化测试之--验证码处理