简体   繁体   中英

Read session variable in javascript?

I am setting session variable in servlet and want to access that variable in javascript.

 ps = con.prepareStatement("select * from USERDETAILS where username=? and password=?");
 ps.setString(1, username);
 session.setAttribute("userName", username);

I tried these in javascript function. but it wasn't working...

var name = ${userName};
var name = '<%= Session["userName"] %>';

Seems you should be able to use getAttribute() :

var name = '<%= session.getAttribute("userName") %>';

Though, this depends on Java running through the file to replace the embedded <%= ... %> , which probably won't be the case in separate .js files.

尝试使用此代码访问会话:

var myName= '<%= Session["myName"]%>';

Unless your session is completely stored in a cookie, you cannot read a session variable in JavaScript. You should store the variable contents in a JavaScript variable during page generation, or use AJAX to fetch it later.

Did you check in the debugger(javascript debugger) what name contained?
Did you try to assign name to some html, to make sure data got assigned correctly?
Did you try to remove quotes?
also your code should be on the main page, so that server engine go through it and perform substitution of Session("userName") to the actual value.

for those who get an error with the code below about characters like <% vs.

var name = '<%= session.getAttribute("username") %>';

I had the same issue but it turned out that I placed the script in a wrong place in the code.

So you better check where you put the code.

Hope this helps

try this -> {sessionScope.username}

By default page, request, session and application objects are available to JSP pages. So you can access then using EL syntax.

And following table shows IMPLICIT objects available to EL.

       Implicit object            Description
1.     pageScope        Scoped variables from page scope
2.     requestScope     Scoped variables from request scope
3.     sessionScope     Scoped variables from session scope
4.     applicationScope Scoped variables from application scope
5.     param            Request parameters as strings
6.     paramValues      Request parameters as collections of strings
7.     header           HTTP request headers as strings
8.     headerValues     HTTP request headers as collections of strings
9.     initParam        Context-initialization parameters
10.    cookie           Cookie values
11.    pageContext      The JSP PageContext object for the current page

Reference: Are session and sessionScope the same in JSP EL?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM