자바 구현 인증 코드 구체 적 인 코드

14538 단어 Java인증번호
여기 서 저 는 struts 2 시 뮬 레이 션 로그 인 기능 을 사용 하여 자바 가 실현 하 는 인증 코드 기능 을 검증 하 였 습 니 다.
자바 인증 코드 구현 절차:
1.RandomImageGenerator.자바 류 를 만 들 고 인증 코드 이미지 의 생 성 을 실현 합 니 다.
2.servlet 클래스,RandomImageServlet.java 를 만 들 고 생 성 된 인증 코드 를 페이지 에 출력 합 니 다.
3.Action 클래스,LoginAction.java 를 만 들 고 로그 인 을 제어 합 니 다.
4.struts.xml 웹.xml 파일 설정
5.페이지 작성
구체 적 실현 용 코드 표현
1.RandomImageGenerator.java 클래스 만 들 기

package com.tenghu.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

/**
 *
 * @author xiaohu
 *
 */
public class RandomImageGenerator {
 // Random
 static Random random=new Random();
 //
 public static String random(int num){
  //
  String[] str={"0","1","2","3","4","5","6","7","8","9",
       "a","b","c","d","e","f","g","h","i","j",
       "k","l","m","n","p","q","r","s","t"};
  int number=str.length;
  //
  String text = "";
  // 4
  for(int i=0;i<num;i++){
   text+=str[random.nextInt(number)];
  }
  return text;
 }
 /**
  *
  *
  * @return
  */
 private static Color getRandColor() {
  Random random = new Random();
  Color color[] = new Color[10];
  color[0] = new Color(32, 158, 25);
  color[1] = new Color(218, 42, 19);
  color[2] = new Color(31, 75, 208);
  color[3] = new Color(0, 102, 182);
  color[4] = new Color(171, 0, 85);
  return color[random.nextInt(5)];
 }
 /**
  *
  *
  * @return
  */
 private static Font getFont() {
  Random random = new Random();
  Font font[] = new Font[5];
  font[0] = new Font("Ravie", Font.BOLD, 30);
  font[1] = new Font("Antique Olive Compact", Font.BOLD, 30);
  font[2] = new Font("Forte", Font.BOLD, 30);
  font[3] = new Font("Wide Latin", Font.BOLD, 30);
  font[4] = new Font("Gill Sans Ultra Bold", Font.BOLD, 30);
  return font[random.nextInt(5)];
 }
 /**
  *
  * @throws IOException
  */
 public static void render(String randomStr,OutputStream out,int width,int height) throws IOException{
  //
  BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
  //
  Graphics2D g=(Graphics2D) bi.getGraphics();
  //
  g.setColor(Color.white);
  g.fillRect(0, 0, width, height);
  g.setFont(getFont());
  g.setColor(Color.BLACK);
  // ,
  String str1[]=new String[randomStr.length()];
  for(int i=0;i<str1.length;i++){
   str1[i]=randomStr.substring(i,i+1);
   int w=0;
   int x=(i+1)%3;
   //
   if(x==random.nextInt(7)){
    w=30-random.nextInt(7);
   }else{
    w=30+random.nextInt(7);
   }
   //
   g.setColor(getRandColor());
   g.drawString(str1[i], 20*i+10, w);
  }
  // , ,
  for(int i=0;i<100;i++){
   int x=random.nextInt(width);
   int y=random.nextInt(height);
   Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
   //
   g.setColor(color);
   g.drawOval(x, y, 0, 0);
  }
  //
  for(int i=0;i<15;i++){
   int x=random.nextInt(width);
   int y=random.nextInt(height);
   int x1=random.nextInt(width);
   int y1=random.nextInt(height);
   Color color=new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
   //
   g.setColor(color);
   g.drawLine(x, y, x1, y1);
  }
  //
  g.dispose();
  //
  ImageIO.write(bi, "jpg", out);
 }
 public static void main(String[] args) throws FileNotFoundException, IOException {
  //
  String randomStr=random(5);
  System.out.println(randomStr);
  //
  render(randomStr, new FileOutputStream("D:\\test.jpg"),130,40);
 }
}

2.RandomImageServlet.java 만 들 기

package com.tenghu.code.servlet;

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

import com.tenghu.code.RandomImageGenerator;

public class RandomImageServlet extends HttpServlet {
 //
 int width=0;
 //
 int height=0;
 //
 int randomStrNum=0;
 public void destroy() {
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  // HttpSession
  HttpSession session=request.getSession();
  //
  String randomStr=RandomImageGenerator.random(randomStrNum);
  if(null!=session){
   //
   session.setAttribute("randomStr", randomStr);
   // ,
   response.setDateHeader("Expires", 1L);&nbsp;
   response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
   response.addHeader("Pragma", "no-cache");
   response.setContentType("image/jpeg"); 
   //
   RandomImageGenerator.render(randomStr, response.getOutputStream(), width, height);
  }
 }
 public void init() throws ServletException {
  //
  width=Integer.parseInt(this.getInitParameter("width"));
  //
  height=Integer.parseInt(this.getInitParameter("height"));
  //
  randomStrNum=Integer.parseInt(this.getInitParameter("num"));
 }
}   

3.LoginAction.java 클래스 만 들 기

package com.tenghu.code.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
 //
 private String userName;
 //
 private String password;
 //
 private String code;
 private InputStream inputStream;
 public InputStream getResult(){
  return inputStream;
 }
 //
 public String success() throws Exception{
  return SUCCESS;
 }
 //
 public String testLogin() throws Exception{
  //
  String randomStr=(String) ActionContext.getContext().getSession().get("randomStr");
  if(code.trim().equalsIgnoreCase(randomStr)){
   if("admin".equals(userName.trim())&&"admin".equals(password.trim())){
    //
    inputStream=new ByteArrayInputStream("1".getBytes("UTF-8"));
   }else{
    //
    inputStream=new ByteArrayInputStream("2".getBytes("UTF-8"));
   }
  }else{
   //
   inputStream=new ByteArrayInputStream("0".getBytes("UTF-8"));
  }
  return "result";
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
}

4.struts.xml,웹.xml 파일 설정

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts> 
 <package name="installs" extends="struts-default">
  <action name="login" class="com.tenghu.code.action.LoginAction">
   <!-- success.jsp -->
   <result name="success">success.jsp</result>
   <!-- -->
   <result name="result" type="stream">
    <param name="contentType">text/html</param>
    <param name="inputName">result</param>
   </result>
  </action>
 </package>
</struts>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>RandomImageServlet</servlet-name>
    <servlet-class>com.tenghu.code.servlet.RandomImageServlet</servlet-class>
    <!-- -->
    <init-param>
     <param-name>width</param-name>
     <param-value>130</param-value>
    </init-param>
    <!-- -->
    <init-param>
     <param-name>height</param-name>
     <param-value>40</param-value>
    </init-param>
    <!-- -->
    <init-param>
     <param-name>num</param-name>
     <param-value>4</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>RandomImageServlet</servlet-name>
    <url-pattern>/verification.do</url-pattern>
  </servlet-mapping>
  <!-- struts -->
  <filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

5.테스트 페이지 작성

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
 <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
 <script type="text/javascript" src="js/jquery.form.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
   CODE.initCode();
   //
   function checkInput(){
    if($('#userName').val()==''){
     alert(' !');
     return false;
    }
    if($('#password').val()==''){
     alert(' !');
     return false;
    }
    if($('#code').val()==''){
     alert(' !');
     return false;
    }
    return true;
   }

   //
   $('#btn').click(function(){
    if(checkInput()==true){
     $('#login_request').ajaxSubmit({
      url:'login!testLogin',
      cache:false,
      type:'POST',
      success:function(data){
       if(data==0){
        alert(' !');
        //
        CODE.initCode();
       }else if(data==1){
        alert(' !');
        //
        $('#login_request')[0].submit();
       }else if(data==2){
        alert(' !');
        //
        CODE.initCode();
       }
      },
      error:function(e){
       alert(' !');
      }
     });
     }
   });
  });
  var CODE={
    //
    initCode:function(){
     $("#code_img").attr("src","verification.do?rmd="+new Date().getTime())// ,
     .click(function(){
      $(this).attr("src","verification.do?rmd="+new Date().getTime());
     }); 
    }};
 </script>
  </head>

  <body>
   <form action="login!success" id="login_request" method="post">
    UserName:<input type="text" id="userName" name="userName"/><br/>
    Password:<input type="password" id="password" name="password"/><br>
    Verification_Code:<input type="text" id="code" name="code"/><img id="code_img" style="position:relative;top:8px;height:25px"><br>
    <input type="button" id="btn" value=" "/>
   </form>
  </body>
</html>
성공 페이지 가 붙 어 있 습 니 다.텍스트 일 뿐 결 과 를 표시 합 니 다.

좋은 웹페이지 즐겨찾기