1.效果图
2.pom.xml
<!-- 验证码配置-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
3.config配置类
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Properties;
/**
* 图形验证码配置类
*/
@Configuration
public class KaptchaConfig implements WebMvcConfigurer {
@Bean
public DefaultKaptcha producer(){
Properties properties =new Properties();
properties.put("kaptcha.border","no");
properties.put("kaptcha.textproducer.font.color","black");
properties.put("kaptcha.textproducer.char.space","5");
Config config=new Config(properties);
DefaultKaptcha defaultKaptcha =new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
4.SmsService接口类
public interface SmsService {
Result sendAliSms(String number) throws ClientException, com.aliyuncs.exceptions.ClientException;
ServletOutputStream patternCode(HttpServletResponse response) throws IOException;
}
5.SmsServiceImpl业务类
import com.google.code.kaptcha.Producer;
@Service
public class SmsServiceImpl implements SmsService {
@Resource
private Producer producer;
/**
* 获取图型验证码
*/
@Override
public ServletOutputStream patternCode(HttpServletResponse response) throws IOException {
String text= producer.createText();//验证码内容
BufferedImage image=producer.createImage(text);//验证码图片流
ServletOutputStream out =response.getOutputStream();
ImageIO.write(image,"jpg",out);
IOUtils.closeQuietly(out);
存缓存
//redisDao.vSet(text,text,300);
return out;
}
}
6.SmsController控制方法
/**
* 短信
* 验证码
* 工具类
*/
@RestController
@RequestMapping("/sms")
public class SmsController {
@Resource
private SmsService smsService;
/**
* 发送图像验证码
*/
@GetMapping("/patternCode")
public ServletOutputStream patternCode(HttpServletResponse response) throws IOException {
return smsService.patternCode(response);
}
}
7.推荐程序员必备网站