各位老哥,江湖救急
在验证码生成时利用StringBuilder的append方法后又用toString生成了验证码字符串,然后将其存在session中,但是提交表单到servlet验证时,想要将session中存的验证码值取出来,但是一直报空异常。
异常如下:
相关代码段:
VerificationCode.java(验证码生成并将其存入session,主要代码)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//2.3生成随机验证码
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
Random ran=new Random();//创建随机函数
StringBuilder aa=new StringBuilder();//将验证码字符拼接为字符串
for(Integer i=0;i<4;i++) {
Integer index=ran.nextInt(str.length());//生成0到61不包括61的随机数(str字符串长度61)
char ch=str.charAt(index);//返回指定索引处字符(index限制0到length-1)
aa.append(ch);
Font font=new Font("Fixedsys", Font.BOLD, height);//设置验证码字体,PLAIN正常,BOLD加粗
g.setFont(font);
g.setColor(new Color(20 + ran.nextInt(110), 20 + ran.nextInt(110), 20 + ran.nextInt(110)));
g.drawString(new Character(ch).toString(), width/5*i+20, height/2);//将字符串写到图片上
}
String scyzm=aa.toString();
HttpSession session=req.getSession();
session.setAttribute("scyzm", scyzm);
ImageIO.write(image, "jpg", resp.getOutputStream());
}
}
index.jsp(登录提交的表单,主要代码)
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
<form action="${pageContext.request.contextPath }/loginServlet" method="post">
<input id="input1" type="text" name="acc" placeholder="账号" />
<input id="input2" type="password" name="pwd" placeholder="密码" />
<!-- 下拉列表:选择登录者身份 -->
<select id="input3" name="shenfen">
<option value="stu">学生</option>
<option value="adm">管理员</option>
</select>
<input type="hidden" id="" value=""/>
<input id="input4" type="text" name="yzm" placeholder="验证码" />
<img id="img1" src="/MyTest/verificationCode" onclick="changeCode()">
<a id="a1" href="#" onclick="changeCode()">看不清,换一张?</a>
<input id="input5" type="submit" value="登录"/>
</form>
</div>
</div>
<script type="text/javascript">
function changeCode(){
var img=document.getElementById("img1");
img.src="/MyTest/verificationCode?"+new Date().getTime();
}
</script>
LoginServlet.java(提交验证时取出session中值为null,主要代码)
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=req.getSession();
Map map=req.getParameterMap();
String yzm=((String[]) map.get("yzm"))[0];
String scyzm=(String)session.getAttribute("scyzm");
if(scyzm.equals(yzm)) {
出错在:if(scyzm.equals(yzm)) {
取出的值为null