在前台页面有如下语句
<img onclick="this.src='/ran/random?random='+Math.random()" alt="验证码,点击图片更换" src="/ran/random?random=0.2868249340216069" width="86" height="40">
其中src 指向的地址不是一个img文件,而是一个转到SpringMVC的类中方法
src="/ran/random?random=0.2868249340216069"
方法如下:
@Controller
public class RandomCodeController {
@RequestMapping(value={"/ran/random"})
public void genericRandomCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "private,no-cache,no-store");
response.setContentType("image/png");
HttpSession session = request.getSession();
int width = 85;
int height = 28;
BufferedImage image = new BufferedImage(width, height, 2);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.getInstance(3, 1.0f));
Random random = new Random();
g.setColor(new Color(231, 231, 231));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Microsoft YaHei", 2, 24));
String sRand = "";
for (int responseOutputStream = 0; responseOutputStream < 4; ++responseOutputStream) {
String rand = String.valueOf(random.nextInt(10));
sRand = sRand + rand;
g.setColor(new Color(121, 143, 96));
g.drawString(rand, 13 * responseOutputStream + 16, 23);
}
session.setAttribute("COMMON_RAND_CODE", (Object)sRand);
g.dispose();
ServletOutputStream var12 = response.getOutputStream();
ImageIO.write((RenderedImage)image, "png", (OutputStream)var12);
var12.close();
}
}
所以其实这个src相联系的是一个ServletOutputStream
这个地方我不太理解
ServletOutputStream如何和一个图片联系起来?
不仅仅是图片,其他文件也是以流的形式传输的。浏览器把后台给的流解析成了图片了。