AJAX+JAVA 사용자 로그인 인증 구현 코드

7704 단어 AJAXJAVA상륙등록
수요
aax 비동기 리셋 페이지를 통해 사용자가 입력한 계정 비밀번호가 데이터베이스에 있는지 확인합니다.
기술 창고
JSP+Servlet+Oracle
구체적인 코드
JSP 섹션:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script>
  function createXMLHttpRequest() {
    try {
      xmlHttp = new XMLHttpRequest();// ie ajax
    } catch (tryMS) {
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//ie 
      } catch (otherMS) {
        try {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//ie 
        } catch (failed) {
          xmlHttp = null;
        }
      }
    }
    return xmlHttp;
  }
  // 
  var xmlHttp;
  function checkUserExists() {
    var u = document.getElementById("uname");
    var username = u.value;
    if (username == "") {
      alert(" ");
      u.focus();
      return false;
    }
    // 
    var url = "loginServlet";
    // xmlhttprequest 
    xmlHttp = createXMLHttpRequest();
    // 
    xmlHttp.onreadystatechange = proessRequest;
    // 
    xmlHttp.open("post", url, true);
    // 
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
    // 
    xmlHttp.send("uname="+username);
  }
  // 
  function proessRequest() {
    if (xmlHttp.status==200 && xmlHttp.readyState == 4) {
      var b = xmlHttp.responseText;// 
      if (b=="true") {
        document.getElementById("alert").innerHTML = "<font color='red'> !</font>";
      }else {
        document.getElementById("alert").innerHTML = "<font color='blue'> !</font>";
      }
    }
  }
</script>
<body>
   :
  <input id="uname" name="uname" type="text" onblur="checkUserExists()" /><div id="alert" style="display:inline"></div>
</body>
</html>
여기에는 Dao층을 사용하지 않고 servlet과 서비스층으로 직접 검증합니다.
다음은 서비스에서 JDBC가 조회한 코드입니다.

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.stx.service.User;
import com.stx.service.ConnectionManager;

public class ajaxService {
  public boolean searchUser (String uname) {
  //jdbc 
    boolean isFalse = false;
    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;
    connection = ConnectionManager.getConnection();
    try {
      stmt = connection.createStatement();
      String sql = "select * from user_b where uname='"+uname+"'";//sql 
      rs = stmt.executeQuery(sql);
      isFalse=rs.next();

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      ConnectionManager.closeResultSet(rs);
      ConnectionManager.closeStatement(stmt);
      ConnectionManager.closeConnection(connection);
    }
    return isFalse;
  }
}

JDBC 연결 코드:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ConnectionManager {
  private final static String DRIVER_CLASS = "oracle.jdbc.OracleDriver";
  private final static String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
  private final static String DBNAME = "ibook";
  private final static String PASSWORD = "qwer";

  public static Connection getConnection() {
    Connection connection = null;
    try {
      Class.forName(DRIVER_CLASS);
      connection = DriverManager.getConnection(URL, DBNAME, PASSWORD);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return connection;
  }

  public static void closeResultSet(ResultSet rs) {
    try {
      if (rs != null)
        rs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void closeConnection(Connection connection) {
    try {
      if (connection != null && !connection.isClosed())
        connection.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void closeStatement(Statement stmt) {
    try {
      if (stmt != null)
        stmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
사용자 클래스 정보:

 public class User {
    private String uname;
    public User() {
      super();
    }
    public User(String uname) {
      super();
      this.uname = uname;
  
    }
  
    public String getUname() {
      return uname;
    }
    public void setUname(String uname) {
      this.uname = uname;
    }
레이어 서브렛 제어:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stx.service.ajaxService;

/**
 * Servlet implementation class loginServlet
 */
public class loginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private ajaxService ajaxService = new ajaxService();

  /**
   * @see HttpServlet#HttpServlet()
   */
  public loginServlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String uname = request.getParameter("uname");// 
    boolean isUname = ajaxService.searchUser(uname);// service 
    response.setCharacterEncoding("UTF-8");// 
    PrintWriter out = response.getWriter();
    out.print(isUname);
    out.flush();
    out.close();// 
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기