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:
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.
form action="editinfo" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" value="<%if( request.getSession().getAttribute(" parameter_whatever_you_passed ") != null
{
request.getSession().getAttribute("parameter_whatever_you_passed ").toString();
}
%>" />
</td>
</tr>
</table>
</form>
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>
Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :
String id=(String)session.getAttribute("uid");
Here uid is the attribute in which you have stored the ID earlier. You can set it by:
session.setAttribute("uid",id);
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.
<%! String username=(String)session.getAttribute("username"); %>
form action="editinfo" method="post">
<table>
<tr>
<td>Username: </td><td> <input type="text" value="<%=username %>" /> </td>
</tr>
</table>
add <%! String username=(String)session.getAttribute("username"); %>