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