jfinal 验证码的问题

配置路由那些就不说了啊,直接是Controller,

/**

 * 

 */

package top.rxrc.zhsq.website.controller.userInfo;


import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


import top.rxrc.zhsq.common.SystemConstant;

import top.rxrc.zhsq.render.SysCaptchaRender;

import top.rxrc.zhsq.utils.MD5Salt;

import top.rxrc.zhsq.utils.Tools;

import top.rxrc.zhsq.website.controller.CommonController;

import top.rxrc.zhsq.website.pojo.LoginUser;

import top.rxrc.zhsq.website.pojo.PropertyChargeCarDetail;

import top.rxrc.zhsq.website.pojo.PropertyChargeItem;

import top.rxrc.zhsq.website.pojo.Village;

import top.rxrc.zhsq.website.validator.LoginUserValidator;

import top.rxrc.zhsq.website.validator.RegisterUserValidator;


import com.jfinal.aop.Before;


/**

 * @author  joy 上午10:22:54

 */

public class UserController extends CommonController {


public void register() {

setAttr("vname", Village.dao.getVillage());

render("userInfo.jsp");

}


@SuppressWarnings("rawtypes")

public Map responseM = new HashMap();// 用来存放返回的数据(json)


// 生成验证码

public void imgcode() {

        //WEBSITE_LOGIN_RADOMKEY这是我的一个常量

//SysCaptchaRender render = new SysCaptchaRender(KEY);

render(new SysCaptchaRender(SystemConstant.WEBSITE_LOGIN_RADOMKEY, getSession()));

}


@Before(LoginUserValidator.class)

public void login() {

// 获取页面的用户名密码

String uname = getPara("uname");

String password = getPara("upassword");

// 进行密码加密

password = MD5Salt.getMd5(uname, password);

LoginUser user = LoginUser.dao.getUser(uname, password);

if (user == null) {

ajaxError("用户不存在或登录密码错误!");

} else {

// 查询登录用户的目录,并存入到session

user.set("last_login_time", new Date());

user.update();

setSessionAttr("websiteUser", user);

ajaxSuccess("");


}

}


public void logout() {

removeSessionAttr("websiteUser");

redirect("/");

}

}

然后验证Validator


/**

 * 

 */

package top.rxrc.zhsq.website.validator;


import top.rxrc.zhsq.common.SystemConstant;

import top.rxrc.zhsq.render.SysCaptchaRender;

import top.rxrc.zhsq.utils.StringUtils;


import com.jfinal.core.Controller;

import com.jfinal.validate.Validator;


/**

 * @author  joy

 * 上午10:37:16

 */

public class LoginUserValidator extends Validator {

@Override

protected void validate(Controller c) {

validateRequiredString("uname", "nameMsg", "请输入用户姓名!");

validateRequiredString("upassword", "passwordMsg", "请输入密码");

validateRequiredString("uvalidate", "validateMsg", "请输入验证码");

//验证码忽略大小写,这里用到了jfinal 自带的验证验证码的方法

String inputRandomCode = c.getPara("uvalidate");

//这里是拿验证码和session进行判断

String _code =  c.getSessionAttr(SystemConstant.WEBSITE_LOGIN_RADOMKEY);

_code = StringUtils.isValid(_code)?_code.toLowerCase():"";

inputRandomCode = StringUtils.isValid(inputRandomCode)?inputRandomCode.toLowerCase():"";

if(StringUtils.isValid(inputRandomCode) &&  !inputRandomCode.equals(_code)){

addError("validateMsg", "验证码错误");

}


@Override

protected void handleError(Controller controller) {

controller.renderJson(new String[]{"nameMsg","passwordMsg","validateMsg"});

}


}

接着是验证码这个类

/**

 * 

 */

package top.rxrc.zhsq.render;


import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.security.MessageDigest;

import java.util.Random;

 







import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.Cookie;

 


import javax.servlet.http.HttpSession;


import top.rxrc.zhsq.utils.StringUtils;


import com.jfinal.core.Controller;

import com.jfinal.kit.HashKit;

import com.jfinal.kit.StrKit;

import com.jfinal.kit.StringKit;

import com.jfinal.render.Render;

/**

 * @author zhuyongbo

 *

 * @createDate 2015年11月6日

 */

public class SysCaptchaRender extends Render{

private static final long serialVersionUID = -7599510915228560611L;

    

    private static final String[] strArr = {"3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"};

     


    private static String randomCodeKey = "JFINAL_JLHHWH_Key";

    private static HttpSession session;

    /**

     * md5散列后的随机码

     */

    private  String md5RandonCode;

    private static boolean caseInsensitive = true;

     

    private int img_width = 85;

    private int img_height = 20;

    private int img_randNumber = 6;

     

    public SysCaptchaRender() {

    }



    public SysCaptchaRender(String randomKey) {

        if (StringUtils.isEmpty(randomKey))

            throw new IllegalArgumentException("randomKey can not be blank");

        randomCodeKey = randomKey;

    }

    

    public SysCaptchaRender(String randomKey,HttpSession session) {

        if (StringUtils.isEmpty(randomKey))

            throw new IllegalArgumentException("randomKey can not be blank");

        this.session = session;

        randomCodeKey = randomKey;

    }

    public SysCaptchaRender(int width, int height, int count, boolean isCaseInsensitive,String md5RandonCode) {       

        if(width <=0 || height <=0 || count <=0)

        {

            throw new IllegalArgumentException("Image width or height or count must be > 0");

        }

        this.img_width = width;

        this.img_height = height;

        this.img_randNumber = count;

        this.md5RandonCode = md5RandonCode;

        caseInsensitive = isCaseInsensitive;

    }

    

    

    

    public SysCaptchaRender(String randomKey,int width, int height, int count, boolean isCaseInsensitive) {

        if (StringUtils.isEmpty(randomKey))

            throw new IllegalArgumentException("randomKey can not be blank");

        randomCodeKey = randomKey;

         

        if(width <=0 || height <=0 || count <=0)

        {

            throw new IllegalArgumentException("Image width or height or count must be > 0");

        }

        this.img_width = width;

        this.img_height = height;

        this.img_randNumber = count;

        caseInsensitive = isCaseInsensitive;

    }

     

    public void render() {

        BufferedImage image = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);

        String vCode = drawGraphic(image);

        session.setAttribute(randomCodeKey,vCode);

        

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

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

        response.setDateHeader("Expires", 0);

        response.setContentType("image/jpeg");

         

        ServletOutputStream sos = null;

        try {

            sos = response.getOutputStream();

            ImageIO.write(image, "jpeg",sos);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        finally {

            if (sos != null)

                try {sos.close();} catch (IOException e) {e.printStackTrace();}

        }

    }

 

    private String drawGraphic(BufferedImage image){

        // 获取图形上下文

        Graphics g = image.createGraphics();

        // 生成随机类

        Random random = new Random();

        // 设定背景色

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

        g.fillRect(0, 0, img_width, img_height);

        // 设定字体

        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

 

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

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

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

            int x = random.nextInt(img_width);

            int y = random.nextInt(img_height);

            int xl = random.nextInt(12);

            int yl = random.nextInt(12);

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

        }

 

        // 取随机产生的认证码(img_randNumber位数字)

        String sRand = "";

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

            String rand = String.valueOf(strArr[random.nextInt(strArr.length)]);

            sRand += rand;

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

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

            // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成

            g.drawString(rand, 13 * i + 6, 16);

        }

 

        // 图象生效

        g.dispose();

         

        return sRand;

    }

     

    /*

     * 给定范围获得随机颜色

     */

    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);

    }

     

    private static final String encrypt(String srcStr) {

        try {

            String result = "";

            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] bytes = md.digest(srcStr.getBytes("utf-8"));

            for(byte b:bytes){

                String hex = Integer.toHexString(b&0xFF).toUpperCase();

                result += ((hex.length() ==1 ) ? "0" : "") + hex;

            }

            return result;

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

 



}


然后是页面


<div class="theme-popbod dform">

<form class="theme-signin" id="loginform" action=" " method="post">

<ol>

<li id="failmsg"></li>

<li><strong>用户名:</strong><input class="ipt" type="text"

name="uname" value="" size="20" id="nameMsg" /></li>

<li><strong>密&nbsp;&nbsp;&nbsp;码:</strong><input class="ipt"

type="password" name="upassword" value="" id="passwordMsg" size="20" /></li>

<li><strong>验证码:</strong><input id="validateMsg" style="padding-top: 12px;" class="ipt" type="text"

name="uvalidate" size="5" /> <img alt="点击刷新" src="user/imgcode"

onclick="this.src='user/imgcode?'+Math.random()" /></li>

<li><a class="btn btn-primary log_btn">登 录</a>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a class="btn btn-primary"

href="/user/register">注册</a></li>

</ol>

</form>

</div>

里面的id是和验证器的那个对应的

然后是js

$(document).ready(function(){

$(".log_btn").click(function(){

do_login();

});

});







function do_login(){

$.ajax({

url:"/user/login",

type:"post",

processData:false,

data:$("#loginform").serialize(),

success:function(result) {

if (result.status==200) {

window.location.reload();

}

else if(result.msg){

$("#failmsg").html(result.msg);

}

else if(result.nameMsg){

$("#failmsg").html(result.nameMsg);

}else if(result.passwordMsg){

$("#failmsg").html(result.passwordMsg);

}else if(result.validateMsg){

$("#failmsg").html(result.validateMsg);

}

}

});

这下全部都好了,效果是这样的,可能我描述的不清楚,效果图不能上传,反正就是这样的

你可能感兴趣的:(jfinal 验证码的问题)