blog

Spring "ブートで画像キャプチャを生成し、それを検証するには?

1.依存関係の追加 プロジェクト構造 すべてのコード Util...

Nov 26, 2020 · 5 min. read
シェア

1.依存関係の追加

 <dependency>
 <groupId>com.github.penggle</groupId>
 <artifactId>kaptcha</artifactId>
 <version>2.3.2</version>
 </dependency>
 
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

プロジェクト体制

すべてのコード

UserController
package com.yzm.config;
import java.util.HashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yzm.utils.Util;
@Controller
public class TestControler {
 @Resource
 private DefaultKaptcha captchaProducer;
 /**
 * ログイン CAPTCHA SessionKey
 */
 public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
 /**
 * ログインCAPTCHAイメージ
 */
 @RequestMapping(value = {"/loginValidateCode"})
 public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
 Util.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE);
 }
 /**
 * CAPTCHAが正しいかチェックする
 */
 @RequestMapping("/checkLoginValidateCode")
 @ResponseBody
 public HashMap checkLoginValidateCode(HttpServletRequest request,@RequestParam("validateCode")String validateCode) {
 String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString();
 HashMap<String,Object> map = new HashMap<String,Object>();
 if(loginValidateCode == null){
 map.put("status",null);//CAPTCHA期限切れ
 }else if(loginValidateCode.equals(validateCode)){
 map.put("status",true);//正しいCAPTCHA
 }else if(!loginValidateCode.equals(validateCode)){
 map.put("status",false);//不正なCAPTCHA
 }
 map.put("code",200);
 return map;
 }
}
package com.yzm.controller;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
@Component
public class TestConfig {
 
 @Bean
 public DefaultKaptcha getDefaultKaptcha() {
 DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
 Properties properties = new Properties();
 // イメージ・ボーダー
 properties.setProperty("kaptcha.border", "no");
 // ボーダーカラー
 properties.setProperty("kaptcha.border.color", "black");
 //ボーダーの厚さ
 properties.setProperty("kaptcha.border.thickness", "1");
 //  
 properties.setProperty("kaptcha.image.width", "200");
 //  
 properties.setProperty("kaptcha.image.height", "50");
 //イメージ実装クラス
 properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
 //テキスト実装クラス
 properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
 //テキストコレクション、このコレクションからのCAPTCHA値
 properties.setProperty("kaptcha.textproducer.char.string", "01234567890");
 //CAPTCHAの長さ
 properties.setProperty("kaptcha.textproducer.char.length", "4");
 // 
 properties.setProperty("kaptcha.textproducer.font.names", "ソング");
 //フォントの色
 properties.setProperty("kaptcha.textproducer.font.color", "black");
 //テキスト間隔
 properties.setProperty("kaptcha.textproducer.char.space", "5");
 //干渉実装クラス
 properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
 //干渉色
 properties.setProperty("kaptcha.noise.color", "blue");
 //イメージスタイルとの干渉
 properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
 //背景実装クラス
 properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
 //背景色グラデーション、終了色
 properties.setProperty("kaptcha.background.clear.to", "white");
 //テキスト・レンダラー
 properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
 Config config = new Config(properties);
 defaultKaptcha.setConfig(config);
 return defaultKaptcha;
 }
 
}

ユーティリティ

package com.yzm.utils;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.code.kaptcha.impl.DefaultKaptcha;
public class Util {
 
 /**
 * CAPTCHAイメージを生成する
 * @param request セッションを設定する
 * @param response イメージに変換する
 * @param captchaProducer イメージ生成メソッドクラス
 * @param validateSessionKey session 
 * @throws Exception
 */
 public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) throws Exception{
 // Set to expire far in the past.
 response.setDateHeader("Expires", 0);
 // Set standard HTTP/1.1 no-cache headers.
 response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
 // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
 response.addHeader("Cache-Control", "post-check=0, pre-check=0");
 // Set standard HTTP/1.0 no-cache header.
 response.setHeader("Pragma", "no-cache");
 
 // return a jpeg
 response.setContentType("image/jpeg");
 
 // create the text for the image
 String capText = captchaProducer.createText();
 
 // store the text in the session
 request.getSession().setAttribute(validateSessionKey, capText);
 
 // create the image with the text
 BufferedImage bi = captchaProducer.createImage(capText);
 
 ServletOutputStream out = response.getOutputStream();
 
 // write the data out
 ImageIO.write(bi, "jpg", out);
 try {
 out.flush();
 } finally {
 out.close();
 }
 }
}
Read next

Javaのいくつかの参照型

jvmの理解は、オブジェクトが参照との関係を持って生きているかどうかを判断するために、知っている 、参照記述のJDK1.2は非常に狭い値に格納されているデータの参照型は、アドレスの先頭にあるメモリの別の部分を表す場合、それは参照に代わってメモリのこの作品は、JDK1.2 Jの後、JDK1.2と言われています。

Nov 26, 2020 · 3 min read