日期:2014-05-17  浏览次数:20718 次

JSP bug求解
下面是验证登录的jsp代码,测试结果是这样的,若用户名密码输入不正确,验证码不正确它会弹出alert("输入的验证码错误!");若用户名密码输入正确,验证码不正确  就直接跳转到index.jsp页面了,为什么不执行验证码判断部分了啊。

<%@ page language="java" import="java.util.*,usr.*" pageEncoding="GB2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>用户验证</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
  
  <body>
  <%
   String usr = request.getParameter("usr");
   String pwd = request.getParameter("pwd");
  
   String u_code = request.getParameter("v_code").toString().trim();
   String s_code = session.getAttribute("s_code").toString().trim();
   //out.print(u_code);out.print(s_code);
   if(!u_code.equals(s_code))
   {
   %>
   <script language="javascript">
<!-- 
alert("输入的验证码错误!");
window.location="Login.jsp";
-->
</script>
   <%
   }
  
   usr u = new usr(usr.trim(),pwd.trim());
Boolean flag = usrDAO.checkUsr(u);
   out.print(flag);out.print(usr);out.print(pwd);
   if(flag)
   {
   session.setAttribute("usr",u.getUsername());
   response.sendRedirect("index.jsp");
   }
   else
   {
   %>
   <script language="javascript">
<!-- 
alert("用户名或密码错误!");
window.location="Login.jsp";
-->
</script>
   <%
   }
   %>
    <p><br/></p>This is my JSP page. <br>
  </body>
</html>

------解决方案--------------------
其实页面弹出了验证码错误的提示  只是同时执行了response.sendRedirect("index.jsp");

alert只会阻止js代码往下执行   但是不会阻止java代码

建议吧代码结构改成:
if(!u_code.equals(s_code)){
// 验证码错误处理
}else{
 // 如果验证码正确 则判断用户名
 if(用户名和密码是否正确){
  // 用户名验证通过处理
 }else{
  // 用户名验证错误处理
 }
}