我已经开发了用于生成验证码和添加会话名称代码的 servlet
生成验证码
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
Random rnd;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rnd=new Random();
rep.setContentType("image/jpeg");
String random_String=getRandomNumbers();
HttpSession ses=req.getSession();
ses.setAttribute("code",random_String);
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
private String getRandomNumbers()
{
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
在其他 servlet 中使用 Generate capta-image
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
HttpSession ses=req.getSession();
String original=(String)ses.getAttribute("code");
if(original!=null)
{
out.println("<h1>Original Value "+original+"</h1>");
}
ses.invalidate();
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
两个 servlet 都可以正常工作,但我没有得到在 Capta-code servelt 中生成的会话值(在 servlet 中添加)
我得到的是在以前的 capta-image 中生成的会话值。
见输出:
输出 - 1
输出 - 2
输出 - 3
谢谢 ..