关于JSP中Session 的先取后存问题(求帮助)

最近在做一个验证码的功能 (在一个平台的基础上,登录功能是平台封装好的)

我已经生成好了一个验证码的JSP 并且将验证码存入到session中

而在login页面取该session的时候 第一次取值为null值 再刷新页面 取到的是上一次存入的值
图片说明
多次试验结果: 是login页面先加载 取session值 (取到null) 之后验证码的JSP才将值存入session

求技术大牛给予帮助, 如何在login页面获取到JSP中的验证码(完成校验)

(注明:由于是平台开发,没有配置文件)

你的思路是可以的,但程序执行过程没按你的思路来,应该用ajax去请求,然后在请求返回图片后(成功的情况)再加上你的核验,要不然取到的验证码总有可能是慢半拍的,还有这年头还有人用“document.getElementById”?真是怪事,加个jquery.js,万事大吉,,,祝好运!

刷新验证码是异步请求吗

补充 :login页面

function loadimage(){ document.getElementById("randImage").src = "/JE/resource/zxj/login/img/image.jsp?"+Math.random(); } function submitFun(){ var userform = document.getElementById('userform'); var rand = userform.rand.value var rand2 = <%=session.getAttribute("code") %> <% System.out.println(session.getAttribute("code"));%> alert(rand); alert(rand2); //这里判断了验证码是否正确 if(rand == rand2 ){ //验证通过,提交表单数据 userform.submit(); }else{ alert('输入不符合规则'); } }


<%
// 读取cookie
String loginUserCode = "";
javax.servlet.http.Cookie userCode = org.springframework.web.util.WebUtils.getCookie(request, "loginUserCode");
if(null != userCode) {
loginUserCode = userCode.getValue();
}
String version=com.je.core.util.WebUtils.sysVar.get("JE_ICON_VERSION");
if(com.je.core.util.StringUtil.isNotEmpty(version)){
version=("?version="+version);
}else{
version="";
}
//处理登录错误消息

Exception e=(Exception)session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
String error="登录密码错误!";
if(e!=null){
String errorType=e.getMessage();
if(e instanceof org.springframework.security.concurrent.ConcurrentLoginException){
error="该用户已经在别处登录!";

}else if(LoginErrorType.NONE.equals(errorType)){
error="该用户不存在!";
}else if(LoginErrorType.DISABLED.equals(errorType)){
error="该用户已被禁用!";
}else if(LoginErrorType.NOSYS.equals(errorType)){
error="该用户不是系统用户!";
}else if(LoginErrorType.INVALID.equals(errorType)){
error="该用户已经失效!";
}else if(LoginErrorType.ERRORPROXY.equals(errorType)){
error="代理登录失败!";
}else if(LoginErrorType.ERRORDEPT.equals(errorType)){
error="该用户没有部门!";
}else{
error="登录密码错误!";
}
}
if(null== request.getParameter("error")){
error="";
}
%>

            <ul>
                <li><a href="##">课程查询</a></li>
                <li><a href="##">培养方案查询</a></li>
                <li><a href="##">导师查询</a></li>
                <li><a href="##">答辩公告</a></li>
                <li><a href="##">新生信息核对</a></li>
            </ul>
        </div>              
    </div>
    <div class="mybanner">
        <div class="container">
            <div class="mycontent">
                <div class="mycontent_left">
                    <img src="/JE/resource/zxj/login/img/left_1.png" alt="" />
                </div>
                <div class="mycontent_login">
                    <form name="userform" method="post" action="j_spring_security_check" id="userform" >
                        <h3>登录</h3>
                        <span></span>
                        <input name="j_username" type="text" id="j_username" value="<%=loginUserCode%>" class="ipt-t myuser" onfocus="this.className+=' ipt-t-focus'" onblur="this.className='ipt-t'" />
                        <input name="j_password" type="password" id="j_password" class="ipt-t mylock" onfocus="this.className+=' ipt-t-focus'" onblur="this.className='ipt-t'" />
                        <div class="myyzm clearfix">
                            <input type="text" id="rand" name= "rand" value="" placeholder="验证码" class="yzm"/>
                            <div class="myyzm_right"   float:right;> 
                                <img alt="code..." name="randImage" id="randImage" src="/JE/resource/zxj/login/img/image.jsp" width="60" height="30" border="1" align="absmiddle"  > 
                                <a href="javascript:loadimage();">看不清点我</a> 
                            </div> 

                        </div>
                        <div class="mypd clearfix">
                            <input type="checkbox" name="" id="" value="" />
                            <p>记住密码</p>
                            <a href="##">忘记密码?</a>                                
                        </div>
                        <div class="loginbtn">
                            <input name="login" type="button" value="登录"  onclick="submitFun()" class="button b-left" id="btnSearch" onmouseover="this.className+=' button-focus'" onmouseout="this.className='button b-left'" />
                        </div>
                    </form>
                    <div id="msg" style="color: red;"><%=error%></div>       
                </div>
            </div>


        </div>
    </div>

验证码页面:
<%@ page contentType="image/jpeg charset=UTF-8" pageEncoding="UTF-8"
import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!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);
}%>
<%
out.clear();//这句针对resin服务器,如果是tomacat可以不要这句
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
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(new Font("Times New Roman", Font.PLAIN, 18));
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 sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
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);
}
// 将认证码存入SESSION
//request.getSession().setAttribute("rand", sRand);

session.setAttribute("code",sRand);
String a  = (String)session.getAttribute("code");
System.out.println(a);
System.out.println(session.getId());

g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());

%>

你这个是先取验证码 后村验证码 所以 总是慢一拍

拿到验证码去后台验证的

图片说明
输入完验证码调用后台action中的方法
//异步校验证码
$.post("/portal/website/online/online!yzCode.action",{"sqCode":$("#sqCode").val()},function(response){
if(response=='true'){
layer.closeAll();
showNotice($("#qFlowForm"));
}else{
layer.tips('验证码错误!', '#sqCode');
$("#sqCode").focus();
}
});

public String yzCode() throws Exception {
String sqCode = request.getParameter("sqCode");
String sessionCode = (String) request.getSession().getAttribute("sqCode");
if (StringUtils.isEmpty(sessionCode)) {
sessionCode = (String) request.getSession().getAttribute("yzCode");
}
boolean result = (StringUtils.isNotBlank(sessionCode) && sessionCode.equals(sqCode));
Struts2Util.renderText(result+"");
return null;
}