Print session attributes in jsp

2019-01-14 06:51发布

My webapp is ready but I just wanted to add a little dropdown menu with the username as title. This is my jsp code:

                <i class="icon-user"></i> 
                <%
                    session.getAttribute("name");
                %>
                <span class="caret"></span>

and it sais

session cannot be resolved

9:              <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
10:                     <i class="icon-user"></i> 
11:                     <%
12:                         session.getAttribute("name");
13:                     %>
14:                     <span class="caret"></span>
15:                 </a>

There is a session because I'm logged in.

Kind regards,

4条回答
Explosion°爆炸
2楼-- · 2019-01-14 07:34

I agree with answer given by @Pau Kiat Wee. But you can also set this user name from the controller in modelmap and then just simple use it in a EL. That would also be a good option. Hope this helps you. Cheers.

查看更多
太酷不给撩
3楼-- · 2019-01-14 07:36

In your servlet:

 1) get your parameter:

    String param = request.getParameter("param");

 2) send it to the request object as an attribute:

    request.setAttribute("param", param);

In your JSP:

   use JSTL, and EL to return the attribute you sent from your servlet:

   <input type="text" name="param" value="<c:out value="${param}" />" />

and there you go.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-14 07:42

You can try an alternative:

<% request.getSession().getAttribute("name") %>

The reason that session is not getting resolved is because you must have set session="false" in your page directive.

Read this for further reference.

查看更多
叼着烟拽天下
5楼-- · 2019-01-14 07:43

You can use EL, which is prefered in JSP.

<c:out value="${sessionScope.name}"/>

Or if the name value is HTML safe, you can use

${sessionScope.name}

Make sure the JSP is allow access session.

<%@ page session="true" %>

To use core JSTL, make sure the following code is included.

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
查看更多
登录 后发表回答