生成图片带有随机码的验证码

页面端:


<%@ page contentType="text/html; charset=GBK"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <%@ page import="zhjw.util.CommonUtil"%>
<html>
<head>
<title>URP 综合教务系统 - 登录</title>
<link href="<%=request.getContextPath()%>/css/newcss/login.css" rel="stylesheet" type="text/css">
<link href="<%=request.getContextPath()%>/css/newcss/project.css" rel="stylesheet" type="text/css">
</head>
<script type='text/javascript'>
function login(){
if(document.loginForm.zjh.value == ""){
alert("请输入您的帐号");
document.loginForm.zjh.focus();
return ;
     }
if(document.loginForm.mm.value == ""){
alert("请输入您的密码");
document.loginForm.mm.focus();
return ;
     }
if(document.loginForm.v_yzm.value == ""){
alert("请输入验证码");
document.loginForm.v_yzm.focus();
return ;
     }
    document.loginForm.submit();
}

//红色部分是重点
function m_changeOne(){

  document.getElementById("vchart").src="<%=request.getContextPath()%>/validateCodeAction.do?random="+Math.random();
 
}  
function valiCode(){
document.getElementById("vchart").src="<%=request.getContextPath()%>/validateCodeAction.do?random="+Math.random();
}

window.onload = function(){
    valiCode();
}

</script>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" style="overflow:auto;" >
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td align="center">
<table width="525" border="0" cellspacing="0" cellpadding="0" background="<%=request.getContextPath()%>/img/pic/login/bg-top.jpg">
  <tr>
    <td width="107"><img src="<%=request.getContextPath()%>/img/pic/login/top-left.jpg" width="107" height="39"></td>
    <td width="256" class="adtitle">提供全新教务管理方案</td>
    <td width="147" align="right" valign="bottom">
</td>
    <td width="10"><img src="<%=request.getContextPath()%>/img/pic/login/top-right.jpg" width="15" height="39"></td>
  </tr>
</table>
<table  border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="linelogin"></td>
  </tr>
</table>
<table border="0" cellspacing="0" cellpadding="0" class="mainbox">
  <tr>
    <td width="33">&nbsp;</td>
    <td width="352" valign="top">
    <form method="post" name="loginForm" action="<%=request.getContextPath()%>/loginAction.do" onSubmit="return login();">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td>
<table width="100%" border="0" cellspacing="20" cellpadding="0">
  <tr>
    <td height="60" class="font12" valign="bottom"> 
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td class="font11">
</td>
</tr>
              <tr>
                 <%if(!CommonUtil.hasActionErrors(request)) {%>
                 <td class="font12" id="welcomeMessage">
      <span id="welcomeMessage">欢迎来到URP综合教务系统,请输入您的帐号和密码</span>
      </td>
      <%}else{%>
      <td><img src="<%=request.getContextPath()%>/img/icon/alert.gif"></td>
      <td class="errorTop"><html:errors/></td>
      <%}%>
              </tr>
            </table></td>
  </tr>
</table></td>
      </tr>   
      <tr>
        <td>

<table width="100%" border="0" cellspacing="6" cellpadding="0" class="font-b">
  <tr>
    <td align="right" width="67">
    <span id="userName_label">帐号</span>:    </td>
    <td>
    <input type="text" name="zjh" value="" class="input01" title="帐号" alt="notnull"></td>
  </tr>
  <tr>
    <td align="right" width="67">
    <span id="password_label">密码</span>:    </td>
    <td>
    <input type="password" name="mm" value="" class="input01" title="密码" alt="notnull"></td>
  </tr>

<tr>
<td align="right" width="67">
<span id="password_label">验证码</span>:
</td>
<td colspan="2" align="left">
<input type="text" name="v_yzm" size="4"
title="验证码" alt="notnull">
<img id="vchart"  height="20" width="80" >
&nbsp; 
a href="" οnclick="m_changeOne();">看不清,换一张</a>
</td>
</tr>

</table> </td>
      </tr>
      <tr>
        <td align="center">
<table width="250" border="0" cellspacing="8" cellpadding="0">
 <tr>
<td align="right">
<input type="image" name="" src="<%=request.getContextPath()%>/img/zh/login.gif" border="0" οnclick="login(); return false;" id="btnSure" class="buttonImg" title="登录">         </td>
<td align="center">
<input type="image" name="" src="<%=request.getContextPath()%>/img/zh/reset.gif" border="0" οnclick="reset(); return false" class="buttonImg" title="重设"></td>
 </tr>
</table> </td>
      </tr>
      <tr height="100%">
        <td align="left" valign="bottom">&nbsp;</td>
      </tr>
    </table>
    </form>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td align="left" valign="bottom">&nbsp;</td>
  </tr>
   <tr>
    <td align="left" valign="bottom">&nbsp;</td>
  </tr>
    <tr>
    <td align="left" valign="bottom" class="font10black">
</td>
  </tr>
</table>


</td>
    <td width="138" align="right" valign="bottom"><img src="<%=request.getContextPath()%>/img/pic/login/stamp.jpg" width="138" height="103"></td>
  </tr>
</table>


<table width="525" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="20"><img src="<%=request.getContextPath()%>/img/pic/login/bottom-left.jpg" width="20" height="27"></td>
    <td width="490" class="bottom">版权所有 &copy; 2005-2008 北京清元优软科技有限公司 保留所有权利。</td>
    <td width="15"><img src="<%=request.getContextPath()%>/img/pic/login/bottom-right.jpg" width="15" height="27"></td>
  </tr>
</table>


</td>
  </tr>
</table>
</body>
</html>


后台生成验证码java代码:

package zhjw.util;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


import zhjw.util.struts.BaseAction;
public class ValidateCodeAction extends BaseAction {
StringBuffer randomCode = null; 
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
HttpSession session = httpServletRequest.getSession();
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();

// 设定背景色
g.setColor(getRandColor(102,250));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
Random random = new Random();
随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
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);
}
// 取随机产生的认证码(4位)
char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'd', 'e', 'f', 'g', 'h', 'j', 'm', 'n', 'q', 'r', 't',
'w', 'x', 'y'}; 
String sRand="";
for (int i=0;i<4;i++){
   String rand=String.valueOf(codeSequence[random.nextInt(50)]);
   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);
}
//  禁止图像缓存。
httpServletResponse.setHeader("Pragma", "no-cache"); 
httpServletResponse.setHeader("Cache-Control", "no-cache"); 
httpServletResponse.setDateHeader("Expires", 0); 
httpServletResponse.setContentType("image/jpeg"); 
// 将认证码存入SESSION
session.setAttribute(session.getId(),sRand.toLowerCase());  
// 将图像输出到Servlet输出流中。
ServletOutputStream sos;
try {
sos = httpServletResponse.getOutputStream();
ImageIO.write(image, "jpeg", sos); 
sos.close();
} catch (IOException 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);
}


}


登录验证java代码:

package zhjw.login.action;


import java.io.PrintWriter;
import java.util.Collections;
import java.util.Date;
import java.util.List;


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


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;


import zhjw.common.ZxjxjhbLogic;
import zhjw.data.fajh.JhZxjxjhb;
import zhjw.data.jcgl.PxCsb;
import zhjw.data.jxyxgl.XsXyyjbView;
import zhjw.data.sys.Menu;
import zhjw.data.sys.User;
import zhjw.grade.PxcsLogic;
import zhjw.jxyxgl.bo.XyyjBo;
import zhjw.login.dao.LoginDao;
import zhjw.login.logic.LoginService;
import zhjw.util.CommonUtil;
import zhjw.util.struts.BaseAction;


public class LoginAction extends BaseAction {
public LoginAction() {
}


public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {


HttpSession session = null;
session = httpServletRequest.getSession(false);
zhjw.data.sys.UserInfor userInfor = (zhjw.auth.UserInforVO) session.getAttribute("userInfor");
String zjh = (String) httpServletRequest.getParameter("zjh");

//2013-07-05:CJG强制清除登陆前其他登陆者留下的会话信息
if(httpServletRequest.getSession() != null){
if(httpServletRequest.getSession().getAttribute("userInfor") != null){
String sessionUserName = ((zhjw.data.sys.UserInfor)httpServletRequest.getSession().getAttribute("userInfor")).getUserZjh();
if(sessionUserName != null && !sessionUserName.equals(zjh)){
httpServletRequest.getSession().invalidate();
session=httpServletRequest.getSession(true);
}
}
}
//强制清除登陆前其他登陆者留下的会话信息结束

String mm = (String) httpServletRequest.getParameter("mm");
mm = CommonUtil.MD5(mm);
ActionMessages errors = new ActionMessages();
LoginService loginService = new LoginService();
String type=(String) httpServletRequest.getParameter("type");

//从前台页面获取验证码信息
String inputYzm  = (String)httpServletRequest.getParameter("v_yzm");

//生成验证码时已经放在session.getId()中了
        String generateYzm = (String)session.getAttribute(session.getId());

        
        System.out.println(inputYzm + "------"+generateYzm);
try {
           if(inputYzm != null  &&  !"".equals(inputYzm) && generateYzm.equalsIgnoreCase(inputYzm)){
// 原教务系统接口登录
//2012-11-08:wzp给中央民族增加单点登录接口
User user=null;
if(type!=null && !type.equals("") && type.equals("sso")){
if(userInfor!=null && userInfor.getUserZjh()!=null){
zjh=userInfor.getUserZjh();
}
user = loginService.getUserSSO(zjh);
}else{
user = loginService.getUser(zjh, mm);
}
if (user != null) {
String MMCZZT=user.getMMCZZT();//查看用户的密码存在状态如果为1正常进入系统主界面,如果为0计入强制修改密码界面
if(null!=MMCZZT&& "0".equals(MMCZZT)){
session.setAttribute("zjh", user.getUserName());
session.setAttribute("oldmm", user.getPassword());
session.setAttribute("inputYzm", inputYzm);

return actionMapping.findForward("UpdatemmAndMmzdzt");
}

if(userInfor==null){
userInfor = new zhjw.auth.UserInforVO();
userInfor.setUserZjh(zjh);

}else{
userInfor.setSessionId(session.getId());
}


userInfor.setUserMm(user.getPassword()); // 用户密码
userInfor.setUserXm(user.getRealName()); // 用户名
userInfor.setUserId(user.getId().toString()); // 用户ID
String userRole = loginService.getUserRole(user); // 用户角色

if(userRole != null && "1".equals(userRole)){
// 登陆时间
Date date = new Date();
userInfor.setLoginTime((date.getTime()));
// 系统允许停留时间
PxcsLogic pxcsLogic = new PxcsLogic();
PxCsb pxCsb = pxcsLogic.loadPxCsb("0910", "62");
if(pxCsb != null && !"".equals(pxCsb)){
String csz = pxCsb.getCsz();
if(csz != null && !"".equals(csz) && "1".equals(csz)){
userInfor.setXstlkg(true);
userInfor.setXttlsj(-1); // 初始值-1
if(pxCsb.getCsza() != null && !"".equals(pxCsb.getCsza())){
userInfor.setXttlsj(Integer.parseInt(pxCsb.getCsza()));
}
}
}
}



if(userRole != null){
userInfor.setUserYhlb(userRole);
}else{
return errorReturn(actionMapping, httpServletRequest,
"err.user.role.nonentity", "DataFailure");
}

/*
* 首次登陆时需要初始化的界面
*/
List<Menu> userAllMenus = loginService.getUserAllMenus(user);
List<Menu> firstMenus = loginService.getFirstMenus(userAllMenus);
httpServletRequest.getSession().setAttribute("index_first", firstMenus);
if (firstMenus.isEmpty()) {
httpServletRequest.getSession().setAttribute("index_other",
Collections.EMPTY_LIST);
} else {
httpServletRequest.getSession().setAttribute("index_other",
loginService.getOtherMenus(userAllMenus, firstMenus));
}
userInfor.setLoginType("platformLogin");

//取得学籍预警开关,csz(参数值) 1为开 .
XyyjBo bo = new XyyjBo();
PxCsb cs = bo.getCs();
if (cs != null) {
String csz = cs.getCsz();
String csza = cs.getCsza();
//如果开,则根据学号和学期号,查出学生预警 .
if ("1".equals(csz)) {
JhZxjxjhb zxjxjh = null;
       if (session.getAttribute("zhjw.common.zxjxjh") == null) {
           try {
zxjxjh = ZxjxjhbLogic.loadBxqZxjxjhb();
} catch (Exception e) {
e.printStackTrace();
}
           if (zxjxjh == null) {
               return errorReturn(actionMapping, httpServletRequest,
                                  "err.global.data.error",
                                  "DataFailure");
           }
           session.setAttribute("zhjw.common.zxjxjh", zxjxjh);
       }
       else {
           zxjxjh = (JhZxjxjhb) session.getAttribute("zhjw.common.zxjxjh");
       }
//        String zxjxjhh = zxjxjh.getZxjxjhh();        
       //通过证件号,学年学期号 查找预警信息 .
       List<XsXyyjbView> xyyjList = bo.getXsXyyj(zjh,csza);
       if(xyyjList.size() > 0 ) {
        session.setAttribute("hxl_logo", "1");
        XsXyyjbView v1 = xyyjList.get(0);
        XsXyyjbView v2 = null;
        if (xyyjList.size() > 1) {
        v2 = xyyjList.get(1);
        }
        session.setAttribute("v1", v1);
        session.setAttribute("v2", v2);
       } else {
        session.setAttribute("hxl_logo", "0");
       }
      
       session.setAttribute("hxl_xyyjList", xyyjList);
}
}

session.setAttribute("userInfor", userInfor);
return actionMapping.findForward("login");
}else{
String msg = "err.global.data.login.errorPwd"; 
errorSaveParam(errors, httpServletRequest,msg);
return actionMapping.findForward("failure");
}
           }else{
          String msg = "err.global.data.login.errorYzm"; 
errorSaveParam(errors, httpServletRequest,msg);
return actionMapping.findForward("failure");
           }

} catch (Exception e) {
e.printStackTrace();
return errorReturn(actionMapping, httpServletRequest,
"err.global.data.error", "DataFailure");
}
}
}




效果图:






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值