添加验证码
- 修改casLoginView.jsp
<!--验证码开始--->
<div class="vCodeBox imgCode" >
<input name = "j_captcha_response" type = "text" tabindex="3" class="formInt" placeholder="请输入验证码" />
<span class="vCodeImg">
<img id="verifyCode_img" title="看不清楚,请重新点击" src="captcha.htm" onclick="this.src=this.src+'?';"/>
</span>
</div>
<!--验证码结束-->
<div>
<!--验证码错误提示-->
<c:if test="${not empty captchaValidatorError}">
<jsp:forward page="casLoginViewValidatorWarn.jsp" />
</c:if>
</div>
- 在 login-webflow.xml 添加验证码 如下
<view-state id="viewLoginForm" view="casLoginView" model="credential">
<binder>
<binding property="username" required="true"/>
<binding property="password" required="true"/>
<binding property="j_captcha_response" required="true"/>
<!--<binding property="rememberMe" />-->
</binder>
<on-entry>
<set name="viewScope.commandName" value="'credential'"/>
<!--
<evaluate expression="samlMetadataUIParserAction" />
-->
</on-entry>
<transition on="submit" bind="true" validate="true" to="captchaValidate"/>
</view-state>
<action-state id="captchaValidate">
<evaluate expression="captchaValidateAction"/>
<transition on="success" to="realSubmit" />
<transition on="error" to="viewLoginForm" />
</action-state>
- 在 applicationContext.xml配置
<bean id="handlerMappingC"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
p:order="1000"
p:alwaysUseFullPath="true">
<property name="mappings">
<util:properties>
<prop key="/authorizationFailure.html">passThroughController</prop>
<prop key="/statistics/ping">pingController</prop>
<prop key="/statistics/threads">threadsController</prop>
<prop key="/statistics/metrics">metricsController</prop>
<prop key="/statistics/healthcheck">healthController</prop>
<prop key="/captcha.htm">captchaImageCreateController</prop> <!--添加验证码-->
</util:properties>
</property>
</bean>
<!--新增内容 -->
<bean id="captchaErrorCountAction" class="com.ist.cas.CaptchaErrorCountAction"/>
<bean id="captchaValidateAction" class="com.ist.cas.CaptchaValidateAction"
p:captchaService-ref="jcaptchaService"
p:captchaValidationParameter="j_captcha_response"/>
<bean id="captchaImageCreateController" class="com.ist.cas.CaptchaImageCreateController">
<property name="jcaptchaService" ref="jcaptchaService"/>
</bean>
<bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore" />
<bean id="jcaptchaService" class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">
<constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
<ref bean="fastHashMapCaptchaStore"/>
</constructor-arg>
<constructor-arg type="com.octo.captcha.engine.CaptchaEngine" index="1">
<bean class="com.ist.cas.JCaptchaEngineEx"/>
</constructor-arg>
<constructor-arg index="2">
<value>180</value>
</constructor-arg>
<constructor-arg index="3">
<value>100000</value>
</constructor-arg>
<constructor-arg index="4">
<value>75000</value>
</constructor-arg>
</bean>
com.ist.cas包下是验证码对应的后台代码
CaptchaErrorCountAction 类如下:
package com.ist.cas;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
public final class CaptchaErrorCountAction extends AbstractAction {
protected Event doExecute(final RequestContext context) {
int count;
try {
count = (Integer) context.getFlowScope().get("count");
} catch (Exception e) {
count = 0;
}
count++;
context.getFlowScope().put("count", count);
return success();
}
}
CaptchaImageCreateController
package com.ist.cas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class CaptchaImageCreateController implements Controller,InitializingBean {
private ImageCaptchaService jcaptchaService;
public CaptchaImageCreateController() {
}
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
/* byte captchaChallengeAsJpeg[] = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
String captchaId = request.getSession().getId();
java.awt.image.BufferedImage challenge=jcaptchaService.getImageChallengeForID(captchaId,request.getLocale());
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0L);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();*/
int width = 82;
int height = 42;
Random random = new Random();
// 设置response头信息 禁止缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 生成缓冲区image类
BufferedImage image = new BufferedImage(width, height, 1);
// 产生image类的Graphics用于绘制操作
Graphics g = image.getGraphics();
// Graphics类的样式
g.setColor(this.getRandColor(200, 250));
g.setFont(new Font("Times New Roman", 0, 28));
g.fillRect(0, 0, width, height);
// 绘制干扰线
for (int i = 0; i < 40; i++) {
g.setColor(this.getRandColor(130, 200));
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y, x + x1, y + y1);
}
// 绘制字符
String strCode = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
strCode = strCode + rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 28);
}
// 将字符保存到session中用于前端的验证
// session.setAttribute("verifycode", strCode);
request.getSession().setAttribute("verifycode", strCode);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
response.getOutputStream().flush();
return null;
}
/**
* 颜色
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
public void setJcaptchaService(ImageCaptchaService jcaptchaService) {
this.jcaptchaService = jcaptchaService;
}
public void afterPropertiesSet() throws Exception {
if (jcaptchaService == null)
throw new RuntimeException("Image captcha service wasn`t set!");
else
return;
}
}
- 在web.xml文件中 添加验证
<servlet-mapping>
<servlet-name>cas</servlet-name>
<url-pattern>/captcha.htm</url-pattern>
</servlet-mapping>