Home Java javaTutorial Spring code example generated through kaptcha configuration verification code

Spring code example generated through kaptcha configuration verification code

May 05, 2017 pm 03:19 PM
kaptcha spring Verification code generation

This article mainly introduces spring mvc using kaptcha to generate verification code examples, and introduces in detail the steps of using Kaptcha to generate verification codes. Those who are interested can learn more

Using Kaptcha to generate verification codes is very simple and The parameters can be customized, and the usage steps are simply recorded below.

1. Add maven dependency in pom.xml:

<dependency>
  <groupId>com.google.code.kaptcha</groupId>
  <artifactId>kaptcha</artifactId>
  <version>2.3</version>
  <classifier>jdk15</classifier>
</dependency>
Copy after login

2. Configure kaptcha attribute in web.xml:

<bean id="verifyCodeProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
    <property name="config">
      <bean class="com.google.code.kaptcha.util.Config">
        <constructor-arg>
          <props>
            <prop key="kaptcha.border">yes</prop>
            <prop key="kaptcha.border.color">105,179,90</prop>
            <prop key="kaptcha.border.thickness">1</prop>

            <prop key="kaptcha.noise.color">blue</prop>

            <prop key="kaptcha.image.width">150</prop>
            <prop key="kaptcha.image.height">50</prop>

            <prop key="kaptcha.session.key">verifyCode</prop>

            <!-- <prop key="kaptcha.textproducer.char.string">0123456789abcdefghijklmnopqrst!@#$%^*</prop> -->
            <prop key="kaptcha.textproducer.char.length">4</prop>
            <prop key="kaptcha.textproducer.char.space">4</prop>


            <prop key="kaptcha.textproducer.font.size">30</prop>
            <prop key="kaptcha.textproducer.font.color">blue</prop>

          </props>
        </constructor-arg>
      </bean>
    </property>
  </bean>
Copy after login

The id value of the bean node verifyCodeProducer is the name when referenced in the class@Resource; kaptcha.session.key in the attribute configuration The value is the access name in the session.

Configure in the servlet node

##3. Related methods in the controller class:

@Controller
public class CommonController {

  @Autowired
  private Producer verifyCodeProducer;

  @RequestMapping(path = "/getVerifyCodeImage", method = RequestMethod.GET)
  public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();

    ResponseUtils.noCache(response);
    response.setContentType("image/jpeg");

    String capText = verifyCodeProducer.createText();
    session.setAttribute(Constants.SESSION_KEY_VERIFY_CODE, capText);

    BufferedImage bi = verifyCodeProducer.createImage(capText);
    ServletOutputStream out = null;
    try {
      out = response.getOutputStream();
      ImageIO.write(bi, "jpg", out);
      out.flush();
    } catch (Exception ex) {
      LOGGER.error("Failed to produce the verify code image: ", ex);
      throw new ServerInternalException("Cannot produce the verify code image.");
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
}
Copy after login

Constants.SESSION_KEY_VERIFY_CODE is the value of kaptcha.session.key in the property configuration.


4.jsp

<p class="form-group has-feedback">
  <span class="glyphicon glyphicon-barcode form-control-feedback"></span> 
  <input id="verifyCode" name="verifyCode" type="text" maxlength="4" class="form-control" placeholder="<spring:message code=&#39;login.label.code&#39; />" />
  <p style="height: 1px"></p>
  <img src="${pageContext.request.contextPath}/getVerifyCodeImage" id="verifyCodeImage" style="margin-bottom: -3px" /> 
  <a href="#" rel="external nofollow" onclick="changeVerifyCode()"><spring:message code=&#39;login.code.tip&#39; /></a>
</p>
Copy after login
function changeVerifyCode() {
  $(&#39;#verifyCodeImage&#39;).hide().attr(&#39;src&#39;, &#39;${pageContext.request.contextPath}/getVerifyCodeImage?&#39; + Math.floor(Math.random()*100) ).fadeIn(); 
  event.cancelBubble=true; 
}
Copy after login

5.kaptcha attribute description:

  1. kaptcha.border.color Border color Default is Color.BLACK

  2. kaptcha.border.thickness Border thickness Default is 1

  3. kaptcha.producer.impl Verification code

    Generator The default is DefaultKaptcha

  4. ##kaptcha.textproducer.impl Verification code text generator The default is DefaultTextCreator
  5. kaptcha.textproducer.char.string Verification code text character content range Default is abcde2345678gfynmnpwx
  6. kaptcha.textproducer.char.length Verification code text character length Default is abcde2345678gfynmnpwx 5
  7. ##kaptcha.textproducer.font.names Verification code text font style Default is new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
  8. kaptcha.textproducer.font.size Verification code text character size The default is 40
  9. kaptcha.textproducer.font.color Verification code text character Color Default is Color.BLACK
  10. kaptcha.textproducer.char.space Verification code text character spacing Default is 2
  11. ##kaptcha.noise.impl Verification code noise generation

    Object
  12. Default is DefaultNoise
  13. kaptcha.noise.color Verification code noise color Default is Color.BLACK

  14. kaptcha.obscurificator.impl Verification code style engine Default is WaterRipple

  15. kaptcha.word.impl Verification code text character rendering Default is DefaultWordRenderer

  16. kaptcha.background.impl Verification code background generator Default is DefaultBackground

  17. kaptcha.background.clear.from Verification code background color gradient Default is Color.LIGHT_GRAY

  18. kaptcha.background.clear.to Verification code background color gradient Default is Color.WHITE

  19. ##kaptcha.image.width Verification code

    Image

    Width Default It is 200
  20. kaptcha.image.height Verification code image height The default is 50

  21. [Related recommendations]

    1.
  22. Java Free Video Tutorial

2.

YMP Online Manual

##3.

Java Video Tutorial on Implementing Equal-proportional Thumbnails for Images

The above is the detailed content of Spring code example generated through kaptcha configuration verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

The 7 most commonly used annotations in Spring, the most powerful organization in history! The 7 most commonly used annotations in Spring, the most powerful organization in history! Jul 26, 2023 pm 04:38 PM

With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in Java, spring has slowly begun to abandon xml configuration since it was updated to version 2.5, and more annotations are used to control the spring framework.

Spring Annotation Revealed: Analysis of Common Annotations Spring Annotation Revealed: Analysis of Common Annotations Dec 30, 2023 am 11:28 AM

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

Spring Security permission control framework usage guide Spring Security permission control framework usage guide Feb 18, 2024 pm 05:00 PM

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.

Detailed explanation of Bean acquisition methods in Spring Detailed explanation of Bean acquisition methods in Spring Dec 30, 2023 am 08:49 AM

Detailed explanation of the Bean acquisition method in Spring In the Spring framework, Bean acquisition is a very important part. In applications, we often need to use dependency injection or dynamically obtain instances of beans. This article will introduce in detail how to obtain beans in Spring and give specific code examples. Obtaining the Bean@Component annotation through the @Component annotation is one of the commonly used annotations in the Spring framework. We can do this by adding @Compone on the class

See all articles