建议写成 public
然后在前台页面js中用 var code='<% =code %>'
获取值,然后跟你输入的文本框中的值进行对比
<html><head>
<script language="javascript" type="text/javascript">
var code
function createCode(){
code = new Array()
var codeLength = 4
var checkCode = document.getElementById("checkCode")
checkCode.value = ""
var selectChar = new Array(2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z')
for(var i=0i<codeLengthi++) {
var charIndex = Math.floor(Math.random()*32)
code +=selectChar[charIndex]
}
checkCode.value = code
}
function validate () {
var inputCode = document.getElementById("yzm").value.toUpperCase()
if(inputCode != code ){
alert("验证码错误!")
return false
}
else {
alert("验证码正确!")
return true
}
}
</script>
<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">
</head>
<body onLoad="createCode()">
验证码:<input type="text" id="yzm" size="5" />
<input type="button" id="checkCode" onClick="createCode()" title="刷新验证码" style="width:50pxcolor:#F00border:0letter-spacing:1pxfont-family:Arial" />
<input type="button" id="Button1" onClick="validate()" value="确定" />
</body>
</html>
验证码在我们的后台代码生成,也就是在java代码里生成。然后在页面上显示出来,当用户输入验证码后再检验用户输入的验证码是否和后台生成的验证码相同,比较的时候可以通过ajax去比较,坚决反对用个隐藏域来保存后台生成的验证码,因为这样很容易被攻击