在页面上写一个验证码

2020-10-23 10:37:20 浏览数 (1)

1.首先导入jar包

2.servlet代码

代码语言:javascript复制
package com.itqf.controller;

import cn.dsna.util.images.ValidateCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * zt
 * 2020/9/14
 * 22:15
 */
@WebServlet(value = "/img")
public class ImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ValidateCode validateCode = new ValidateCode(100, 30, 4, 30);
        String code = validateCode.getCode();
        validateCode.write(response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3.jsp代码

代码语言:javascript复制
<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/9/14
  Time: 22:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<h2>欢迎登录</h2>
<h2>呱?!,当前登录用户</h2>
<img src="${pageContext.request.contextPath}/img">
</body>
</html>

4.或者将那个输出验证码的代码换成另一个

就是

代码语言:javascript复制
validateCode.write(response.getOutputStream());

换成

代码语言:javascript复制
ImageIO.write(validateCode.getBuffImg(), "jpg", response.getOutputStream());
代码语言:javascript复制
//其实底层代码都是一样的:validateCode.write(response.getOutputStream());的底层代码就是
public void write(OutputStream sos) throws IOException {
            ImageIO.write(this.buffImg, "png", sos);
            sos.close();
        }

结果:

0 人点赞