1 16 17 18 package org.apache.struts.webapp.example2; 19 20 21 import java.util.Locale ; 22 import javax.servlet.http.HttpServletRequest ; 23 import javax.servlet.http.HttpServletResponse ; 24 import javax.servlet.http.HttpSession ; 25 import org.apache.commons.beanutils.PropertyUtils; 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 import org.apache.struts.action.Action; 29 import org.apache.struts.action.ActionError; 30 import org.apache.struts.action.ActionErrors; 31 import org.apache.struts.action.ActionForm; 32 import org.apache.struts.action.ActionForward; 33 import org.apache.struts.action.ActionMapping; 34 import org.apache.struts.util.ModuleException; 35 36 37 43 44 public final class LogonAction extends Action { 45 46 47 49 50 53 private Log log = 54 LogFactory.getLog("org.apache.struts.webapp.Example"); 55 56 57 59 60 74 public ActionForward execute(ActionMapping mapping, 75 ActionForm form, 76 HttpServletRequest request, 77 HttpServletResponse response) 78 throws Exception { 79 80 Locale locale = getLocale(request); 82 User user = null; 83 84 ActionErrors errors = new ActionErrors(); 86 String username = (String ) 87 PropertyUtils.getSimpleProperty(form, "username"); 88 String password = (String ) 89 PropertyUtils.getSimpleProperty(form, "password"); 90 UserDatabase database = (UserDatabase) 91 servlet.getServletContext().getAttribute(Constants.DATABASE_KEY); 92 if (database == null) 93 errors.add(ActionErrors.GLOBAL_ERROR, 94 new ActionError("error.database.missing")); 95 else { 96 user = getUser(database, username); 97 if ((user != null) && !user.getPassword().equals(password)) 98 user = null; 99 if (user == null) 100 errors.add(ActionErrors.GLOBAL_ERROR, 101 new ActionError("error.password.mismatch")); 102 } 103 104 if (!errors.isEmpty()) { 106 saveErrors(request, errors); 107 return (mapping.getInputForward()); 108 } 109 110 HttpSession session = request.getSession(); 112 session.setAttribute(Constants.USER_KEY, user); 113 if (log.isDebugEnabled()) { 114 log.debug("LogonAction: User '" + user.getUsername() + 115 "' logged on in session " + session.getId()); 116 } 117 118 if (mapping.getAttribute() != null) { 120 if ("request".equals(mapping.getScope())) 121 request.removeAttribute(mapping.getAttribute()); 122 else 123 session.removeAttribute(mapping.getAttribute()); 124 } 125 126 return (mapping.findForward("success")); 128 129 } 130 131 132 134 135 144 public User getUser(UserDatabase database, String username) 145 throws ModuleException { 146 147 if ("arithmetic".equals(username)) { 149 throw new ArithmeticException (); 150 } 151 152 if ("expired".equals(username)) { 154 throw new ExpiredPasswordException(username); 155 } 156 157 return (database.findUser(username)); 159 160 } 161 162 163 } 164 | Popular Tags |