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?
In JSP, the session is the most regularly used implicit object of type HttpSession. It is mainly used to approach all data of the user until the user session is active. Methods used in session Implicit Object are as follows: Method 1: isNew(): This method is used to check either the session is new or not.
The session object is used to track a client session between client requests. JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. a one-page request or. visit to a website or.
If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair.
getSession() will always give you session object, so you can use request. getSession(false) code to get session and if session does not exist, it will return null.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With