[Java] login operation of randomly generated codes tools

Renderings:

Tools CreateImageCode.java:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class CreateImageCode {
    private int width = 70;
    private int height = 27;
    private int codeCount = 4;
    // 干扰线数
    //private int lineCount = 10;
    // 验证码图片Buffer
    // 验证码
    private String code = null;
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    private BufferedImage buffImg = null;

    Random random = new Random();

    public CreateImageCode() {
        createImage();
    }

    public CreateImageCode(int width, int height) {
        this.width = width;
        this.height = height;
        createImage();
    }

    public CreateImageCode(int width, int height, int codeCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        createImage();
    }

    public CreateImageCode(int width, int height, int codeCount, int lineCount) {
        this.width =width;
         the this .height = height;
         the this .codeCount = codeCount;
         // this.lineCount = lineCount; 
        the createImage (); 
    } 

    // generate picture 
    Private  void the createImage () {
         int fontwidth = width / codeCount; // font width. 
        int FontHeight = height - 5; // font height. 
        int , codeY = height -. 8 ; 

        // get the picture 
        buffImg = new new the BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); 
        Graphics G =buffImg.getGraphics (); 

        // set the background color 
        g.setColor (getRandColor (249, 250 )); 
        g.fillRect ( 0, 0 , width, height); 

        // Sets the border
         // g.setColor (getRandColor (200 is, 250));
         // g.drawRect (. 1,. 1, width - 2, height - 2); 

        // set the font 
        the Font font = new new the Font ( "the Fixedsys" , Font.PLAIN, FontHeight); 
        g.setFont (font) ; 

        / * // interference lines provided 
        for (int I = 0; I <lineCount; I ++) { 
            int random.nextInt X1 = (width); 
            int random.nextInt Y1 = (height);  
            int random.nextInt X2 = (width );
            int Y2 = random.nextInt (height );
            g.setColor(getRandColor(1, 255));
            g.drawLine(x1, y1, x2, y2);
        }*/
        /*// 添加噪点
        float yawpRate = 0.01f;// 噪声率
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);

            buffImg.setRGB(x, y, random.nextInt(255));
        }*/
        String str1 = randomStr(codeCount);// 得到随机字符
        this.code = str1;
        for (int0 = I; I <codeCount; I ++) {
            StrRand String = str1.substring (I, I +. 1 ); 
            g.setColor (getRandColor ( 50, 250 ));
             // g.drawString (A, x, Y);
             // A thing to be drawn, x (x, y) at the position of the leftmost character of the baseline and y 'art in this graphics context coordinate system 

            g.drawString (strRand, I * + fontwidth. 3 ,, codeY); 
        } 
    } 
    // get random characters 
    private randomStr String ( int n-) { 
        String str1 = "1234567890" ; 
        String str2 = "" ;
         int len = str1.length () -. 1;
         DoubleR & lt;
         for ( int I = 0; I <n-; I ++ ) { 
            R & lt = (Math.random ()) * len; 
            str2 = str2 str1.charAt + (( int ) R & lt); 
        } 
        return str2; 
    } 
    // get random color 
    Private color getRandColor ( int FC, int BC) { // the given color range obtained random 
        IF (FC> 255 ) 
            FC = 255 ;
         IF (BC> 255 ) 
            BC = 255 ;
         int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();

    }

}

Use this tool servlet class, the output codes into the page:

package com.utils;

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;

@WebServlet(name = "GetImageCodeServlet",urlPatterns = {"/servlet/code.servlet"})
public class GetImageCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jepg");
        // 控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        // 创建图片
        CreateImageCode image = new CreateImageCode();
        String str = Image.getCode ();
         // into the Session
 //         System.out.println ( "authentication code" + STR); 
        . Request.getSession () the setAttribute ( "code" , STR);
         // output to the page 
        image .write (response.getOutputStream ()); 
    } 
}

This image is displayed in the JSP form (without the use of Ajax when the demo directly submit form to another servlet judgment):

    <form action="${pageContext.request.contextPath}/servlet/codeTest.servlet">
        <input type="text" name="code">
        <img src="${pageContext.request.contextPath}/servlet/code.servlet"
             onclick="javascript:this.src='${pageContext.request.contextPath}/servlet/code.servlet?rm='+Math.random()"
             alt="获取验证码">
        <input type="submit" value="验证">
    </form>

Background verification servlet verification code:

package com.utils;

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;

@WebServlet(name = "CodeTestServlet" ,urlPatterns = {"/servlet/codeTest.servlet"})
public class CodeTestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        if (code.equals(request.getSession().getAttribute("code"))) {
            System.out.println("验证成功,验证码为:" + request.getSession().getAttribute("code"));
            // response.sendRedirect(getServletContext().getContextPath()+"/login.jsp");
        }else{
            System.out.println("Authentication failed" ); 
        } 
    } 
}

----

Using annotations development 3.0, web.xml configuration in need

If the project is a maven, it is dependent on:

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>

 

Guess you like

Origin www.cnblogs.com/to-red/p/11260628.html