package com.gnomeshop.servlet; import com.gnomeshop.dto.ItemList; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.gnomeshop.ejb.*; import javax.naming.*; public class LoginServlet extends HttpServlet{ //private UserBean userBean = null; private User _user; // ============================= // Inits the servlet // This will get done only once // ============================= public void init (ServletConfig config) throws ServletException { super.init(config); try { InitialContext ctx = new InitialContext(); _user = (User) ctx.lookup("GnomeShop/UserBean/local"); } catch (Exception e) { e.printStackTrace (); } } public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { // =========================== // 1. Always do this // =========================== PrintWriter out=res.getWriter(); out.println("The Gnome Shop"); out.println("

The Gnome Shop

"); String username, pw ; int admin=0; boolean isAdmin = false; String isAdminStr; int loginUserId=0; // Get parameters username = req.getParameter ("username"); pw = req.getParameter ("pw"); // =========================== // 2. Check if the user posted a form // =========================== if (username != null && ( username.length() > 1) && pw != null && ( pw.length() > 1)){ // There is a username and password, try login admin = Integer.parseInt(req.getParameter ("admin")); if (admin == 1) { isAdmin = true; isAdminStr = "Y"; }else{ isAdmin = false; isAdminStr = "N"; } if(_user !=null){ try{ // Call EJB to do login loginUserId = _user.login(username, pw, isAdmin); }catch(Exception e){ out.println("Error in EJB call=" +e); } if(loginUserId > 0){ // Add objects to the Session to prove user logged in req.getSession().setAttribute("loginUserId", new Integer(loginUserId)); req.getSession().setAttribute("isAdmin", isAdminStr); req.getSession().setAttribute("shoppingCart", new ItemList()); out.println("Login success!

"); }else{ out.println("Login failed!

"); } }else{ out.println("Error: UserBean is not found!"); } } // =========================== // 3. Now, send the HTML to browser. // =========================== Integer uid= (Integer) req.getSession().getAttribute("loginUserId"); if(uid != null && uid.intValue() > 0){ // User authenticated, show toc out.println("

Logout"); out.println("
Enter the gnome shop"); out.println("
View shopping cart"); // Check admin String iaStr = (String) req.getSession().getAttribute("isAdmin"); if(iaStr != null && iaStr.equalsIgnoreCase("Y")){ out.println("

Admin privs"); out.println("
Ban User"); } }else { // Show login form. out.println("Here you can login to the Gnome Shop.
"); out.println("If you dont have a user: Go to create user"); out.println("
"); out.println("
User name: "); out.println("
Password: "); out.println("

Log in as administrator: "); out.println("

"); out.println("
"); } out.println(""); out.println(""); } }