简体   繁体   English

如何使用JavaScript访问jsp会话?

[英]How can i access jsp session in JavaScript?

I need to access some common login data like user id, name, etc in JavaScript. 我需要在JavaScript中访问一些常见的登录数据,例如用户ID,名称等。 I can add the data to jsp session. 我可以将数据添加到jsp会话中。 But is there a way to access it in JavaScript? 但是有没有办法用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对象来获取您需要的参数,像这样,

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

Or use EL instead. 或改用EL And don't forget to add 并且不要忘记添加

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

on your jsp file. 在您的jsp文件中。

EL will pick the parameter's value by action scope . EL将按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: 导致requestScope < sessionScope ,因此,如果requestScopesessionScope有一个名为'username'的参数,它将首先在requestScope搜索并选择值,然后在sessionScope ,然后选择...就像下面的代码:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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