search
HomeJavajavaTutorialSpring code example generated through kaptcha configuration verification code

Spring code example generated through kaptcha configuration verification code

May 05, 2017 pm 03:19 PM
kaptchaspringVerification 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>

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>

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);
    }
  }
}

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="/static/imghwm/default1.png"  data-src="${pageContext.request.contextPath}/getVerifyCodeImage"  class="lazy"   id="verifyCodeImage"   style="max-width:90%" / alt="Spring code example generated through kaptcha configuration verification code" > 
  <a href="#" rel="external nofollow" onclick="changeVerifyCode()"><spring:message code=&#39;login.code.tip&#39; /></a>
</p>
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; 
}

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
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.