简体   繁体   中英

How can i access jsp session in JavaScript?

I need to access some common login data like user id, name, etc in JavaScript. I can add the data to jsp session. But is there a way to access it in JavaScript?

No. Sessions are serverside concept. If you need that info on clientside, have your serverside code pass it along explicitly:

<script>
  var userID = <% out.print(userID); %>;
</script>

use the request Object to get the parameter you need like this,

`request.getSession().getAttribute("username)`.

Or use EL instead. And don't forget to add

`<%@page isELIgnored="false"%>`

on your jsp file.

EL will pick the parameter's value by action scope . Cause requestScope < sessionScope , so if there's a parameter named 'username' in requestScope and sessionScope , it will search and pick the value in requestScope first, then sessionScope , then... Just like the code below:

<script type="text/javascript">
        /* test in my own jsp file with isELIgnored="false"
          <%@ page language="java" contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8" isELIgnored="false"%>
          <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
        */
        <% request.getSession().setAttribute("author", "Vincent"); %>
        var author = "<%= request.getSession().getAttribute("author") %>";
        alert(author);
        author = "${sessionScope.author}";
        alert(author);
</script>

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