前台
action
后台
<script type="text/javascript">
window.onload=function(){
var verifyObj = document.getElementById("Verify");
verifyObj.src="securityCodeImage.action?timestamp="+new Date().getTime();
verifyObj.onclick=function(){
this.src="securityCodeImage.action?timestamp="+new Date().getTime();
};
}
</script>
<body>
${Message }
<form action="login" method="post">
用户名<input type="text" name="user.username" /><br />
密码<input type="password" name="user.password" /><br />
检验码<input type="text" name="securityCode" /><br />
<img id="Verify" style="cursor: hand;" alt="看不清,换一张" /><br />
<input type="submit" name="submit" value="登录" />
</form>
</body>
</html>
action
<action name="securityCodeImage" class="securityCodeImageAction" method="securityCodeImage">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">2048</param>
</result>
</action>
后台
/**
* 提供图片验证码
*
*/
@SuppressWarnings("serial")
@Component("securityCodeImageAction")
@Scope("prototype")
public class SecurityCodeImageAction extends ActionSupport {
// 图片流
private ByteArrayInputStream imageStream;
public ByteArrayInputStream getImageStream() {
return imageStream;
}
public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}
public String securityCodeImage() throws Exception {
String securityCode = getSecurityCode();
imageStream=getImageAsInputStream(securityCode);
// 放入session中
ActionContext actionContext = ActionContext.getContext();
Map session=actionContext.getSession();
session.put("SESSION_SECURITY_CODE", securityCode);
return SUCCESS;
}
private String getSecurityCode() {
// 字符集合(除去易混淆的数字0、数字1、字母l、字母o、字母O)
char[] codes = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
StringBuffer securityCode =new StringBuffer();
for (int i = 0; i < 4; i++) {
int r = (int) (Math.random() * codes.length);
securityCode =securityCode.append(codes[r]) ;
}
return securityCode.toString();
}
private ByteArrayInputStream getImageAsInputStream(String securityCode) throws Exception {
//图片
BufferedImage image=new BufferedImage(70, 20, BufferedImage.TYPE_INT_RGB);
Graphics g=image.createGraphics();
g.setColor(Color.LIGHT_GRAY);//设置边框颜色
//设置字体颜色和样式
g.setColor(new Color(19,148,246));
for(int i = 0; i < 4;i++){
g.drawString(String.valueOf(securityCode.charAt(i)), i * 15 + 5, 15);
}
//关闭资源
g.dispose();
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
jpeg.encode(image);
byte[] bts = bos.toByteArray();
inputStream = new ByteArrayInputStream(bts);
return inputStream;
}
}