public class LoginAction extends ActionSupport {
private String username;
private String password;
@Override
public String execute() throws Exception {
ActionContext ctx = ActionContext.getContext();
Integer counter = (Integer)ctx.getApplication().get("counter");
// put counter into application
ctx.getApplication().put("counter", counter);
// put username into session
ctx.getSession().put("user", username);
if (getUsername().equals("crazyit.org")
&& getPassword().equals("leegang")) {
ctx.put("tip", "Login Success! ");
return SUCCESS;
}
else {
ctx.put("tip", "Login Falied!");
return ERROR;
}
}
}
I put "counter"
in application "user"
in session and "tip"
in ActionContext
. In JSP I can use ${session.user}
and ${sessionScope.user}
to reference the "user" property. ${request.tip}
and ${requestScope.tip}
to reference tip
.
My questions:
sessionScope
, requestScope
, applicationScope
in EL?ActionContext
and request(requestScope)
?P.S.:
I test ${request == requestScope}
which is true, this means they are the same?
With expression language (EL), the scope items are value maps of attributes in the objects that they refer to. For instance, the requestScope is a map representation of values in the request object. This is explained in pretty clear detail on this page: Java Servlet and JSP. If you read through the EL sections, you'll notice a point about request vs request scope here: The requestScope is NOT request object.
I would recommend reading through this page to get a better understanding of servlet/jsp in general.
As far as how the ActionContext relates to these items, it is really a wrapper used by struts to encapsulate the servlet. You can read more specifics about it here: Accessing application, session, request objects.
There have been some references to implicit values given here, but I feel like just saying it's implicit doesn't really explain much. When you are using EL to access servlet variables, you can explicitly declare which scope you want to reference, such as:
${requestScope.myVariable}
You can also reference it implicitly by omitting the scope:
${myVariable}
Now, the problem that can arise here is that variables with the same name can cause collision. EL will check implicit values in a specific order: pageScope, requestScope, sessionScope, and applicationScope, param, paramValues, header, headervalues, initParam, cookie, pageContext. What this means is that if you have a variable in the request scope with the same name as a variable in session or application scope for instance, the request scoped value will be referenced.