databaseauthenticator.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 76 行

JAVA
76
字号
package persistence.database;

import java.sql.*;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.servlet.ServletContext;
import persistence.*;

public class DatabaseAuthenticator implements Authenticator {
  private DataSource ds;

  public void init(ServletContext sctx) throws Exception {
    InitialContext ctx = new InitialContext();
    ds = (DataSource) ctx.lookup(sctx.getInitParameter("DataSourceConfig"));
  }

  public User authenticate(String username, String password)
      throws AuthenticationException, UnknownException {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs;
    try {
      System.out.println(ds.toString());
      try
      {
      conn = ds.getConnection();	
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      pstmt = conn.prepareStatement("SELECT user_id " + 
                                    "FROM users " + 
                                    "WHERE user_name = ? " + 
                                    "AND password = ?");
      pstmt.setString(1, username);
      pstmt.setString(2, password);
      rs = pstmt.executeQuery();

      // Determine whether the supplied user
      // credentials are correct.
      if (!rs.next()) {
        throw new AuthenticationException();
       }

      // Construct a User object.
      User usr = new User(username);
      long userID = rs.getLong("user_id");

      // Search for the groups the user is member of.
      pstmt = conn.prepareStatement("SELECT g.group_name AS name " + 
                                    "FROM groups g, users_groups ug " + 
                                    "WHERE g.group_id = ug.group_id " + 
                                    "AND ug.user_id = ?");
      pstmt.setLong(1, userID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        usr.addGroup(new Group(rs.getString("name")));
       }
      return usr;
    } catch (SQLException e) {
      throw new UnknownException(e);
    } finally {
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException ignored) {}
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ignored) {}
      }
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?