How to use session in JSP pages to get information?
I have a JSP page used for editing some user's info. When a user logins to the website, I keep the information in the session, then in my edit page I try the following:
<%! String username=session.getAttribute("username"); %>
<form action="editinfo" method="post">
<table>
<tr>
<td>Username: </td><td> <input type="text" value="<%=username %>" /> </td>
</tr>
</table>
</form>
but it gives error saying session cannot be resolved. What can I do about it?
Solution 1:
JSP implicit objects likes session
, request
etc. are not available inside JSP declaration <%! %>
tags.
You could use it directly in your expression as
<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>
On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as
<td>Username: </td>
<td><input type="text" value="${username}" /></td>
The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as
<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>
Solution 2:
Use
<% String username = (String)request.getSession().getAttribute(...); %>
Note that your use of <%! ... %>
is translated to class-level, but request is only available in the service()
method of the translated servlet.
See how JSP code is translated to a servlet.
Solution 3:
The reason why you are getting the compilation error is, you are trying to access the session in declaration block (<%! %>
) where it is not available. All the implicit objects of jsp are available in service method only. Code of declarative blocks goes outside the service method.
I'd advice you to use EL. It is a simplified approach.
${sessionScope.username}
would give you the desired output.