springboot +thymeleaf+ kaptcha (图片验证码) 配置

springboot中整合thymeleaf ,之前试了好多次,有几个点要注意一下。
1.首先搭建springboot 这个就不说了。
2.然后添加依赖

 <!--thymeleaf模板jar,是很不错的html数据传递取值,类似jsp的jstl  -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
        这个是要的springboot 默认HTML5严格规范 有些不闭合的标签会报错,使用这个防止这个错误,
            <dependency>
                <groupId>nekohtml</groupId>
                <artifactId>nekohtml</artifactId>
                <version>1.9.6.2</version>
            </dependency>
简单配置一下:application.yml  
   spring:
     thymeleaf:
        mode: LEGACYHTML5
        prefix: classpath:/templates/
        suffix: .html
        content-type: text/html
        cache: false
        encoding: utf-8
  相信有开发经验的同学都知道意思           

扩展一个小知识点:(跟本项目没有关系)
Spring Boot的默认静态资源的路径为:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

3.简单创建几个页面 index.html

   <!DOCTYPE html>
<html lang="en" xmlns="http://www.thymeleaf.org" xmlns:th="http://www.w3.org/1999/xhtml">
// 如果要使用th标签的话上面这个链接不能少(就相当于jsp的jstl一样)
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<h1 th:text="${info}"></h1>
</body>
</html>

login.html

 <!DOCTYPE html> <html xmlns="http://www.thymeleaf.org"
    xmlns:th="http://www.w3.org/1999/xhtml"> <head>
        <meta charset="UTF-8"/>
        <title>login</title> </head> <body> <form action="imgvrifyControllerDefaultKaptcha">
        <input type="text" name="vrifyCode"/>

        <img alt="验证码" onclick="this.src='defaultKaptcha?d='+new Date()*1"
           src="defaultKaptcha">
        </br>
        <input type="submit" value="提交"/> </form> </body> </html>

4.添加kaptcha 验证码依赖

  <!-- 生产图片验证码依赖 -->
            <dependency>
                <groupId>com.github.penggle</groupId>
                <artifactId>kaptcha</artifactId>
                <version>2.3.2</version>
            </dependency>

5.配置KaptchaConfig

  package com.example.demowebapp.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 java.util.Properties;

    @Configuration public class KaptchaConfig {     @Bean
        public DefaultKaptcha getDefaultKaptcha() {
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 图片边框
            properties.setProperty("kaptcha.border", "yes");
            // 边框颜色
            properties.setProperty("kaptcha.border.color", "105,179,90");
            // 字体颜色
            properties.setProperty("kaptcha.textproducer.font.color", "red");
            // 图片宽
            properties.setProperty("kaptcha.image.width", "110");
            // 图片高
            properties.setProperty("kaptcha.image.height", "40");
            // 字体大小
            properties.setProperty("kaptcha.textproducer.font.size", "30");
            // session key
            properties.setProperty("kaptcha.session.key", "code");
            // 验证码长度
            properties.setProperty("kaptcha.textproducer.char.length", "4");
            // 字体
            properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);

            return defaultKaptcha;
        } }

6.访问confroller

/**
* @author
* @date 2018/8/21 10:50
*/
@Controller
public class LoginThymeleafController {

@Autowired
private DefaultKaptcha captchaProducer;

/**
 * 获取验证码 的 请求路径
 * @param httpServletRequest
 * @param httpServletResponse
 * @throws Exception
 */
@RequestMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
        //生产验证码字符串并保存到session中
        String createText = captchaProducer.createText();
        httpServletRequest.getSession().setAttribute("vrifyCode", createText);
        //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = captchaProducer.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream =
            httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}


/**
 * 验证的方法
 * @param httpServletRequest
 * @param httpServletResponse
 * @return
 */
@RequestMapping("/imgvrifyControllerDefaultKaptcha")
public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
    ModelAndView andView = new ModelAndView();
    String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
    String parameter = httpServletRequest.getParameter("vrifyCode");
    System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);

    if (!captchaId.equals(parameter)) {
        andView.addObject("info", "错误的验证码");
        andView.setViewName("index");
    } else {
        andView.addObject("info", "登录成功");
        andView.setViewName("success");
    }
    return andView;
}

@RequestMapping("/login")
public String  login(){

    return "login";
}

}

效果:
这里写图片描述
这里写图片描述

spring boot整合Thymeleaf的那些坑

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值