protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws IOException, ServletException {
// Expire response
try {
//
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
byte[] captchaBytes;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
Hashtable<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
Random r = new Random();
String token = Long.toString(Math.abs(r.nextLong()), 36);
String ch = token.substring(0, 6);
Color c = new Color(0.6662f, 0.4569f, 0.3232f);
GradientPaint gp = new GradientPaint(30, 30, c, 15, 25,
Color.white, true);
graphics2D.setPaint(gp);
Font font = new Font("Verdana", Font.CENTER_BASELINE, 26);
graphics2D.setFont(font);
graphics2D.drawString(ch, 2, 22);
graphics2D.dispose();
HttpSession session = req.getSession(true);
session.setAttribute(CAPTCHA_KEY, ch);
OutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "jpeg", imgOutputStream);
captchaBytes = imgOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Max-Age", 0);
response.setContentType("image/jpeg");
outputStream.write(captchaBytes);
outputStream.close();
utils.PQSoftLogger.getInstance().log(
"Captch servlet: " + image.toString());
} catch (Exception e) {
utils.PQSoftLogger.getInstance().log(
e.toString() + ":" + e.getMessage());
for (StackTraceElement s : e.getStackTrace()) {
utils.PQSoftLogger.getInstance().log(
s.getLineNumber() + ":" + s.getMethodName() + ":"
+ s.getFileName());
}
} finally {
utils.PQSoftLogger.getInstance().log("temp dir-"+System.getProperty("java.io.tmpdir"));
utils.PQSoftLogger.getInstance().log("Captch servlet executed");
}
}
在tomcat服务器环境中调用servlet时,ImageIO.write
方法抛出异常,但它在本地系统上运行。
javax.imageio.IIOException: Can't create output stream!
答案 0 :(得分:6)
我遇到了同样的问题。我之前删除了Tomcat安装下的临时目录。 Tomcat在启动时不会创建此目录。再次添加临时目录后,问题就解决了。
答案 1 :(得分:2)
我想我很久以前就设法解决了类似的问题。但是,如果我能够正确记住,问题就与在temp目录中创建某种文件缓存有关。
因此,如果目录${CATALINA_TMPDIR}
(TOMCAT_HOME/temp
)目录不存在或用户tomcat运行不可写,则可能会发生这种情况。
希望它有所帮助。