servlet:
=============
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.ServletContext;
import java.io.OutputStream;
import java.util.Random;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import webutil.*;
/**
* @version 1.0
* @author dennis
*/
public class Getshowimg extends HttpServlet {
private String code;
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("image/jpeg;charset=gb2312");
int width=80, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RG;
Graphics g = image.getGraphics();
//以下填充背景颜色
g.setColor(Color.decode("#66CCCF"));
g.fillRect(0, 0, width, height);
g.setColor(Color.decode("#01556B"));
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);
}
String rstr = "";
RandomStrg rst = new RandomStrg();
rst.setCharset("a-zA-Z0-9");
rst.setLength("6");
try{
rst.generateRandomObject();
rstr= rst.getRandom();
}catch(Exception ex){
ex.printStackTrace();
}
String sRand="";
for (int i=0;i<rstr.length();i++){
String rand=String.valueOf(rstr.charAt);
// sRand+=rand;
// 将认证码显示到图象中
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand,13*i+5,15);
}
// g.drawString(req.getParameter("yzm"),5,15);
//g.drawString(rstr,5,15);
g.dispose();
OutputStream toClient = resp.getOutputStream();
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(toClient);
encoder.encode(image);
toClient.close();
req.getSession().setAttribute("rstr",rstr);
this.code = rstr;
System.out.println(req.getSession().getAttribute("rstr"));
}
public String getCode(){
return this.code;
}
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);
}
}
jsp:
=====
<form name = form1 method="post">
验证码:<input name="yzm" type="text" size="12" id="yzm0"></td>
<div id="yzm1" style="width:10" style="display:none"></div><IMG id="img0" src="Getshowimg" vspace=3>
<input type=submit name=submit value="submit" onclick="javascript:return checkcode();" >
</form>
<%
out.println("session::"+session.getAttribute("rstr") );
%>
为何第一次打印的session值为空??再刷新一次页面显示的session是刷新之前servlet里面设置的值??请问怎样才能第一次就显示和servlet里面的值一样啊??