Struts2利用IO流制作简单验证码

利用Struts2制作简单验证码:

1、Struts.xml配置:





 
 
  /index.jsp
 

 
 
 
 
 
  inputStream
 
  ${contentType}
   
 

 
 

   
 

  

2、代码如下:

package com.strus1;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;


import javax.imageio.ImageIO;


public class YzmAction {


 


public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
private InputStream inputStream;
private String contentType;
private int contentLength;
public String execute() throws IOException{
//设置传输类型
contentType="image/jpeg";

//创建bufferedimage
BufferedImage bufferedImg=new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
//创建画笔
Graphics2D g= (Graphics2D) bufferedImg.getGraphics();
//g.setBackground(Color.WHITE);
Random random=new Random();
//随机画几个数字
for (int i = 0; i < 4; i++) {

g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.setFont(new Font("", Font.BOLD, 50));
g.drawString(random.nextInt(10)+"",i*50+10, 80);
}

ByteArrayOutputStream byteArrayOut=new ByteArrayOutputStream();

//把画好的bufferedImg 包装一下,写到byteArrayOut里面去
ImageIO.write(bufferedImg, "jpeg", byteArrayOut);
//contentLength=byteArrayOut.toByteArray().length;
  inputStream=new ByteArrayInputStream(byteArrayOut.toByteArray());
return "ok";
}
}

3、效果图

Struts2利用IO流制作简单验证码_第1张图片

你可能感兴趣的:(struts2)