如何在JSP页面中使用session来获取信息? [英] How to use session in JSP pages to get information?

查看:944
本文介绍了如何在JSP页面中使用session来获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于编辑某些用户信息的JSP页面。当用户登录网站时,我会将信息保存在会话中,然后在我的编辑页面中尝试以下操作:

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?

推荐答案

JSP 隐式对象喜欢 session JSP声明<%!中没有 request 等。 %> 代码。

JSP implicit objects likes session, request etc. are not available inside JSP declaration <%! %> tags.

您可以直接在表达式中使用

<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>

另外请注意,长期以来不推荐在JSP中使用scriptlet。强烈建议使用EL(表达式语言)和JSTL标记。例如,在这里你可以使用EL作为

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>

这篇关于如何在JSP页面中使用session来获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆