1. Prefácio
Pode -se dizer que os códigos de verificação são muito comuns em nossas vidas. Algum site ou aplicativo terá essa função, mas por que você precisa disso? Como fazer isso? Abaixo, o editor levará todos a usar o Java para concluir a função de um código de verificação.
2. A função do código de verificação
Geralmente, pode impedir que as pessoas usem robôs para se registrar automaticamente em lotes e fazer login continuamente em usuários registrados específicos usando programas específicos para métodos de rachaduras de força bruta. Como o código de verificação é uma imagem que mistura números e símbolos, parece difícil para o olho humano reconhecer e é ainda mais difícil para a máquina reconhecer.
3. Implementação de Java
3.1 Estabeleça uma classe de servlet para código de verificação:
pacote com.bjPowerNode.drp.util.servlet; importar java.awt.color; importar java.awt.font; importar java.awt.graphics; importar java.awt.image.bufferiMage; import java.io.ioException; importação.util.TrandomMage; javax.servlet.servletexception; importar javax.servlet.http.httpServlet; importar javax.servlet.http.httpServletReQuest; import javax.servlet.http.httpsletletpsonse; @Author Ares * */public class Authimage estende httpServlet {private static final string content_type = "text/html; charset = gb2312"; // Defina o tamanho das letras, tamanho de fonte privada mfont = new Font ("Times New Roman", font.plain, 17); public void init () lança servletexception {super.init (); } Color getRandcolor (int fc, int bc) {aleather aleatória = new aleatória (); if (fc> 255) fc = 255; if (bc> 255) bc = 255; int r = fc+aleatoriamente.nextInt (bc-fc); int g = fc+aleatória.nextInt (BC-FC); int b = fc+aleatoriamente.nextint (bc-fc); int b = fc+aleatoriamente.nextint (bc-fc); retornar nova cor (R, G, B); } Serviço public void (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {Response.setheader ("Pragma", "sem cache"); Response.setheader ("Cache-Control", "No-Cache"); Response.SetDateHeader ("Expira", 0); // indica que a resposta gerada é a resposta da imagem.SetContentType ("Image/jpeg"); int width = 100, altura = 18; Imagem bufferedImage = new bufferImage (largura, altura, bufferImage.type_int_rgb); Gráficos g = image.getGraphics (); Aleatório aleatório = novo aleatório (); G.SetColor (Getrandcolor (200.250)); G.FillRect (1, 1, largura-1, altura-1); g.setColor (nova cor (102.102.102)); G.Drawrect (0, 0, largura-1, altura-1); g.setFont (MFONT); g.setColor (getrandcolor (160.200)); // Desenhe uma linha aleatória para (int i = 0; i <155; i ++) {int x = random.nextInt (largura - 1); int y = random.nextint (altura - 1); int xl = random.nextInt (6) + 1; int yl = random.nextint (12) + 1; G.Drawline (x, y, x + xl, y + yl); } // Desenhe uma linha aleatória da outra direção para (int i = 0; i <70; i ++) {int x = random.nextint (largura - 1); int y = random.nextint (altura - 1); int xl = random.nextInt (12) + 1; int yl = random.nextint (6) + 1; G.Drawline (x, y, x - xl, y - yl); } // gerar números aleatórios e converter números aleatórios em letras string srand = ""; for (int i = 0; i <6; i ++) {int iTmp = aleatom.nextInt (26)+65; char ctmp = (char) itmp; srand += string.valueof (ctmp); g.setColor (nova cor (20+Random.NextInt (110), 20+Random.NextInt (110), 20+Random.Nextint (110))); G.DrawString (String.ValueOf (CTMP), 15*i+10,16); } HttpSession Session = request.getSession (true); session.setAttribute ("rand", srand); G.Dispose (); Imageio.Write (Image, "JPEG", Response.getOutputStream ()); } public void Destroy () {}}3.2 Configurando o servlet em web.xml no arquivo web-inf
// Nome e localização do servlet <Vertlet> <Verlet-name> Authimage </servlet-name> <Servlet-class> com.bjpowernode.drp.util.servlet.authImage </servlet-class> </servlet> // servlet funciona nesses mapeamentos <Verlet-Mapping> <Verlet-Name> authimage </ervlet> <url-pattern>/servlet/login/authimage </url-tattern> </servlet-mapping>
3.3 A recepção chama o servlet
Código JSP:
<img id = "img" style = "cursor: pointer;" src = "$ {PageContext.request.ContextPath}/servlet/login/authimage" onclick = "changeImg ()">JS:
// Clique no código de verificação para alterar a função de imagem alterar () {var iMg = document.getElementById ("img"); img.src = "$ {pageContext.request.contextpath}/servlet/login/authimage? d ="+math.random (); retornar false;}4. Resumo
Com esse aprendizado do código de verificação, também adquiri uma certa compreensão da interação entre todo o servlet e o código front-end, e a transmissão de dados também foi bastante aprimorada. Portanto, ainda preciso aprender mais sobre essas habilidades e resumir -as no futuro. Somente dessa maneira o conhecimento pode ser sólido.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.