如何用Jpatchca和SpringMVC实现验证码

如何用Jpatchca和Spring MVC实现验证码?这篇文章运用了实例代码展示,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联主要从事网站设计、网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务洛浦,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

Jpatchca不支持集群环境,默认的验证码不是保存在session中,如果想做个性化的处理很麻烦。其实我想要的就是一个声称图片的流就ok了,剩下的事情就交给程序员自己实现吧。

最终,选择了patchca(另一个开源的组件)来实现,这个验证码是放到session中的,也可以自己指定。很灵活。

这里对Jpatchca做个备忘:


    com.octo.captcha
    jcaptcha
    2.0-alpha-1


    com.octo.captcha
    jcaptcha-integration-simple-servlet
    2.0-alpha-1
    
        
            servlet-api
            javax.servlet
        
    


    Lrtech_framework
    
        contextConfigLocation
        classpath:framework/spring-front.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
        springMVC
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:/spring-servlet.xml
        
        1
    
    
        springMVC
        /
    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        encodingFilter
        /*
    



    
    
    
    
    
    
        
        
        
         
        
            
                json=application/json
                xml=application/xml
                html=text/html
            
        
        
    
    
        
        
        
            
                
                    
                    
                
            
        
    
    
        
        
        
        
    


    
    
    
    
        
            
        
        
            
        
        
            180
        
        
            100000
        
        
            75000
        
    
package com.lavasoft.ntv.web.captchea;
import com.octo.captcha.component.p_w_picpath.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.p_w_picpath.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.p_w_picpath.color.RandomListColorGenerator;
import com.octo.captcha.component.p_w_picpath.deformation.ImageDeformation;
import com.octo.captcha.component.p_w_picpath.deformation.ImageDeformationByFilters;
import com.octo.captcha.component.p_w_picpath.fontgenerator.FontGenerator;
import com.octo.captcha.component.p_w_picpath.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.p_w_picpath.textpaster.DecoratedRandomTextPaster;
import com.octo.captcha.component.p_w_picpath.textpaster.TextPaster;
import com.octo.captcha.component.p_w_picpath.textpaster.textdecorator.TextDecorator;
import com.octo.captcha.component.p_w_picpath.wordtop_w_picpath.DeformedComposedWordToImage;
import com.octo.captcha.component.p_w_picpath.wordtop_w_picpath.WordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.component.word.wordgenerator.WordGenerator;
import com.octo.captcha.engine.p_w_picpath.ListImageCaptchaEngine;
import com.octo.captcha.p_w_picpath.gimpy.GimpyFactory;
import java.awt.*;
import java.awt.p_w_picpath.ImageFilter;
/**
 * 生成验证码引擎实现
 *
 * @author leizhimin 14-5-4 上午10:55
 */
public class MyCaptchaEngine extends ListImageCaptchaEngine {
    protected void buildInitialFactories() {
        int minWordLength = 4;
        int maxWordLength = 4;
        int fontSize = 16;
        int p_w_picpathWidth = 120;
        int p_w_picpathHeight = 28;
        WordGenerator wordGenerator = new RandomWordGenerator("23456789abcdefghjkmnpqrstuvwxyz");
        TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
                maxWordLength, new RandomListColorGenerator(new Color[]{
                new Color(23, 170, 27), new Color(220, 34, 11),
                new Color(23, 67, 172)}), new TextDecorator[]{});
        BackgroundGenerator background = new UniColorBackgroundGenerator(p_w_picpathWidth, p_w_picpathHeight, Color.white);
        FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
                new Font[]{new Font("nyala", Font.BOLD, fontSize),
                        new Font("Bell MT", Font.PLAIN, fontSize),
                        new Font("Credit valley", Font.BOLD, fontSize)});
        ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[]{});
        ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[]{});
        ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[]{});
        WordToImage word2p_w_picpath = new DeformedComposedWordToImage(font,
                background, randomPaster, backDef, textDef, postDef);
        addFactory(new GimpyFactory(wordGenerator, word2p_w_picpath));
    }
}
package com.lavasoft.ntv.web;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.p_w_picpath.ImageCaptchaService;
import com.sun.p_w_picpath.codec.jpeg.JPEGCodec;
import com.sun.p_w_picpath.codec.jpeg.JPEGImageEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.p_w_picpath.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
 * 登录逻辑
 *
 * @author leizhimin 14-5-4 上午11:00
 */
@Controller
public class LoginController {
    @Resource(name = "p_w_picpathCaptchaService")
    private ImageCaptchaService p_w_picpathCaptchaService;
    /**
     * 生成验证码图片io流
     */
    @RequestMapping(value = "/generateImage")
    public void ImageCaptcha(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("-------------------  /generateImage");
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            String sessionid = request.getSession().getId();
            BufferedImage challenge = p_w_picpathCaptchaService.getImageChallengeForID(sessionid, request.getLocale());
            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
            jpegEncoder.encode(challenge);
        } catch (Exception e) {
            e.printStackTrace();
        }
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("p_w_picpath/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
    /**
     * 验证验证码,并进行登录
     */
    @RequestMapping("/login")
    private String LoginAction(HttpServletRequest request,
                               HttpServletResponse response,
                               String username,
                               String password,
                               String yzm) {
        boolean flag = false;
        String sessionid = request.getSession().getId();
        String captcha_value = request.getParameter("yzm");
        System.out.println("反馈的验证码:" + captcha_value);
        try {
            flag = p_w_picpathCaptchaService.validateResponseForID(sessionid, captcha_value);
        } catch (CaptchaServiceException e) {
        }
        System.out.println("验证结果为:" + flag + ",sessionID=" + sessionid + ",验证码=" + captcha_value);
        if (flag) {
            //todo:验证用户名和密码逻辑,
        }
        return flag ? "good" : "error";
    }
    @RequestMapping("/hello")
    private String hello() {
        System.out.println("-------hello!------");
        return "hello";
    }
    @RequestMapping("/mp")
    private ModelMap mp() {
        System.out.println("-------ModelMap!------");
        ModelMap map = new ModelMap();
        map.put("as", "sadfas");
        map.put("as1", "sadfas");
        map.put("as2", "sadfas");
        return map;
    }
    @RequestMapping("/mp2")
    private ModelAndView mp2() {
        System.out.println("-------ModelMap!------");
        ModelAndView mv = new ModelAndView();
        ModelMap map = mv.getModelMap();
        map.put("as1", "sadfas1");
        map.put("as2", "sadfas2");
        mv.setViewName("mp2");
        return mv;
    }
}


    
    
    
    
    
    
    
    
    
    
    


sdfasdf

<%----%>

上述就是小编为大家分享的用Jpatchca和Spring MVC实现验证码的方法了,如果您也有类似的疑惑,不妨参照上述方法进行尝试。如果想了解更多相关内容,请关注创新互联行业资讯。


文章标题:如何用Jpatchca和SpringMVC实现验证码
URL地址:http://ybzwz.com/article/gesggh.html