⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 loginservlet.java

📁 MasteringEJB20 Code Sample Include SessionBean,EntityBean,etc
💻 JAVA
字号:
package examples;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;

/**
 * This is the very first servlet the client deals with.
 * It's a Login authentication servlet. It asks the user
 * for his name and password, and pass it to the UserManager
 * stateless session bean for verificatiion. 
 * If the user authenticates properly, reference to a new
 * Cart is saved in his HttpSession object, and the user can
 * begin to add items to his cart and shop around.
 */
public class LoginServlet extends HttpServlet {

 /*
  * UserManager home object for authenticating user
  */
 private UserManagerHome userManagerHome;

 /*
  * Cart home object for creating a new cart when
  * the user logs in.
  */
 private CartHome cartHome;

 /**
  * The servlet engine calls this method once to
  * initialize a servlet instance.
  *
  * In the body of this method, we acquire all the
  * EJB home objects we'll need later.
  */
 public void init(ServletConfig config) throws ServletException {

  super.init(config);

  try {
   /*
    * Get the JNDI initialization parameters.
    * We externalize these settings to the
    * servlet properties to allow end-
    * users to dynamically reconfigure their
    * environment without recompilation.
    */
   String initCtxFactory =
    getInitParameter(Context.INITIAL_CONTEXT_FACTORY);
   
   String providerURL =
    getInitParameter(Context.PROVIDER_URL);

   /*
    * Add the JNDI init parameters to a
    * properties object.
    */
   Properties env = new Properties();
   env.put(Context.INITIAL_CONTEXT_FACTORY, initCtxFactory);
   env.put(Context.PROVIDER_URL, providerURL);

   /*
    * Get the initial JNDI context using the above
    * startup params.
    */
   Context ctx = new InitialContext(env);

   /*
    * Look up the UserManager and Cart Home Objects
    * we need via JNDI
    */
   userManagerHome = (UserManagerHome)
    ctx.lookup("UserManagerHome");
   
   cartHome = (CartHome) ctx.lookup("CartHome");
  }
  catch (Exception e) {
   log(e);
   throw new ServletException(e.toString());
  }
 }

 /**
  * The servlet engine calls this method when the user's
  * desktop browser sends an HTTP request.
  */
 public void service(HttpServletRequest request,
                     HttpServletResponse response)
                     throws ServletException, IOException {

  /*
   * Set up the user's HttpSession
   */
  HttpSession session = request.getSession(true);

  /*
   * Retrieve the login name / password from the
   * URL string.
   */
  String loginName = request.getParameter("Login");
  String password = request.getParameter("Password");
  boolean isLogin=false;
  
  /*
   * If user has not tried to log in yet, present
   * him with the login screen.
   */
  if ((loginName == null) || (password == null)) {
   writeForm(request, response, false);
  }

  /*
   * Otherwise, the user has been to this screen
   * already, and has entered some information.
   * Verify that information.
   */
  else {
   /*
    * Uses the UserManager Stateless Session bean to
    * autenticate the user credentials.
    */
   try {
    UserManager  userManager=userManagerHome.create();
    isLogin= userManager.validateUser(loginName,password);
   }
   catch (Exception e) {
    writeForm(request, response, true);
    e.printStackTrace();
    return;
   }
   /*
    * If the passwords match, make a new Cart Session
    * Bean, and add it to the user's HttpSession
    * object.  When the user navigates to other
    * servlets, the other servlets can access the
    * HttpSession to get the user's Cart.
    */
   if (isLogin) {
    try {
     Cart cart = cartHome.create(loginName);
     session.setAttribute("cart", cart);
     
     /*
      * Call the main page
      */
     RequestDispatcher disp =
      this.getServletContext().getRequestDispatcher("/wsf.jsp");
     disp.forward(request, response);
     
     return;
    }
    catch (Exception e) {
     log(e);
     throw new ServletException(e.toString());
    }
   }
  }
  
  /*
   * If there was no match, the user is
   * not authenticated.  Present another
   * login screen to him, with an error
   * message indicating that he is not
   * authenticated.
   */
  writeForm(request, response, true);
 }

 /**
  * Writes the Login Screen (private use only)
  *
  * @param showError true means show an error b/c client
  *        was not authenticated last time.
  */
 private void writeForm(HttpServletRequest request,
                        HttpServletResponse response,
                        boolean showError)
                        throws ServletException, IOException {

  /*
   * Set a variable indicating whether or not we failed to
   * log-in.  The JSP will read this variable.
   */
  request.setAttribute("loginFailed", new Boolean(showError));
    
  /*
   * Forward the request to the login JSP
   */
  RequestDispatcher disp =
   this.getServletContext().getRequestDispatcher("/login.jsp");
  disp.forward(request, response);
 }

 private void log(Exception e) {
  e.printStackTrace();
 }

 public String getServletInfo() {
  return "The Login servlet verifies a user.";
 }
}

⌨️ 快捷键说明

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