1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.apache.struts.webapp.example;
24
25
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpSession;
28 import javax.servlet.http.HttpServletResponse;
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31 import org.apache.struts.action.Action;
32 import org.apache.struts.action.ActionMessage;
33 import org.apache.struts.action.ActionMessages;
34 import org.apache.struts.action.ActionForm;
35 import org.apache.struts.action.ActionForward;
36 import org.apache.struts.action.ActionMapping;
37
38 import org.apache.struts.util.ModuleException;
39 import org.apache.commons.beanutils.PropertyUtils;
40
41
42
43
44
45
46
47
48
49 public final class LogonAction extends Action {
50
51
52
53
54
55
56
57
58 private Log log =
59 LogFactory.getLog("org.apache.struts.webapp.Example");
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 public ActionForward execute(ActionMapping mapping,
80 ActionForm form,
81 HttpServletRequest request,
82 HttpServletResponse response)
83 throws Exception {
84
85
86 User user = null;
87
88
89 ActionMessages errors = new ActionMessages();
90 String username = (String)
91 PropertyUtils.getSimpleProperty(form, "username");
92 String password = (String)
93 PropertyUtils.getSimpleProperty(form, "password");
94 UserDatabase database = (UserDatabase)
95 servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
96 if (database == null)
97 errors.add(ActionMessages.GLOBAL_MESSAGE,
98 new ActionMessage("error.database.missing"));
99 else {
100 user = getUser(database, username);
101 if ((user != null) && !user.getPassword().equals(password))
102 user = null;
103 if (user == null)
104 errors.add(ActionMessages.GLOBAL_MESSAGE,
105 new ActionMessage("error.password.mismatch"));
106 }
107
108
109 if (!errors.isEmpty()) {
110 saveErrors(request, errors);
111 return (mapping.getInputForward());
112 }
113
114
115 HttpSession session = request.getSession();
116 session.setAttribute(Constants.USER_KEY, user);
117 if (log.isDebugEnabled()) {
118 log.debug("LogonAction: User '" + user.getUsername() +
119 "' logged on in session " + session.getId());
120 }
121
122
123 if (mapping.getAttribute() != null) {
124 if ("request".equals(mapping.getScope()))
125 request.removeAttribute(mapping.getAttribute());
126 else
127 session.removeAttribute(mapping.getAttribute());
128 }
129
130
131 return (mapping.findForward("success"));
132
133 }
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 public User getUser(UserDatabase database, String username)
149 throws ModuleException {
150
151
152 if ("arithmetic".equals(username)) {
153 throw new ArithmeticException();
154 }
155
156
157 if ("expired".equals(username)) {
158 throw new ExpiredPasswordException(username);
159 }
160
161
162 return (database.findUser(username));
163
164 }
165
166
167 }