authenticationservlet.java

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

JAVA
68
字号
package persistence.servlet;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import persistence.*;

public class AuthenticationServlet extends HttpServlet {

  /** User object attribute */
  public static final String USER = "user";

  /** User name attribute */
  public static final String USER_NAME = "username";

  /** Password attribute */
  public static final String PASSWORD = "password";

  // Instance variables.
  private Authenticator auth;
  private String authenticationExceptionURI;
  private String authenticatedURI;
  private String unknownExceptionURI;

  public void init() throws ServletException {
    try {
      ServletContext sctx = getServletContext();
      ServletConfig sc = getServletConfig();
      AuthenticationConfig cfig = new AuthenticationConfig();
      cfig.init(sctx, sc.getInitParameter("AuthenticationConfigXML"));
      auth = cfig.getAuthenticator();
      authenticationExceptionURI = cfig.getAuthenticationExceptionURI();
      authenticatedURI = cfig.getAuthenticatedURI();
      unknownExceptionURI = cfig.getUnknownErrorURI();
    } catch (Throwable t) {
      getServletContext().log("AuthenticationServlet", t);
    }
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

System.out.println("doPost() called");

    // Determine the validity of this request.
    if (request.getParameter(USER_NAME) == null ||
        request.getParameter(PASSWORD) == null) {
      response.sendRedirect(authenticationExceptionURI);
    }
    
    // Authenticate the user.
    try {
      System.out.println(request.getParameter(USER_NAME));
      System.out.println(request.getParameter(PASSWORD));
            System.out.println(auth.toString());
            System.out.println("about to call authenticate()");
      User usr = auth.authenticate(
              request.getParameter(USER_NAME), request.getParameter(PASSWORD));
      request.getSession().setAttribute(USER, usr);
      response.sendRedirect(authenticatedURI);
    } catch (AuthenticationException a) {
      response.sendRedirect(authenticationExceptionURI);
    } catch (UnknownException e) {
      getServletContext().log("AuthenticationServlet", e);
      response.sendRedirect(unknownExceptionURI);
    }
  }
}

⌨️ 快捷键说明

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