Java 如何在 servlet 中设置会话变量并在 JSP 中获取它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24222845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:54:35  来源:igfitidea点击:

How can I set a session variable in a servlet and get it in a JSP?

javajspservletssession-variables

提问by Vitalii

I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page

我正在学习 java 并尝试将一些变量从 servlet 传递到 jsp 页面。这是servlet页面的代码

@WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException
    {
        HttpSession session = request.getSession();
        session.setAttribute("MyAttribute", "test value");

        // response.sendRedirect("index.jsp");
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
    }

}

And simple jsp

和简单的jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Index page</title>
</head>
<body>
Index page
<br />
 <% 
Object sss = request.getAttribute("MyAttribute"); 
String a = "22";

%>

   <%= request.getAttribute("MyAttribute"); %>
</body>
</html>

Whatever I do attribete at jsp is null.

无论我在 jsp 上做什么 attribete 都是空的。

What is wrong at this simple code?

这个简单的代码有什么问题?

采纳答案by Braj

you are getting if from request not session.

如果来自请求而不是会话,您将得到。

It should be

它应该是

session.getAttribute("MyAttribute")


I suggest you to use JavaServer Pages Standard Tag Libraryor Expression Languageinstead of Scripletthat is more easy to use and less error prone.

我建议您使用JavaServer Pages 标准标记库表达式语言,而不是Scriplet更易于使用且不易出错的语言。

${sessionScope.MyAttribute}

or

或者

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

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

you can try ${MyAttribute}, ${sessionScope['MyAttribute']}as well.

你可以尝试${MyAttribute}${sessionScope['MyAttribute']}也是如此。

Read more

阅读更多

回答by helderdarocha

You set an attribute in a session. You have to retrieve it from a session:

您在会话中设置了一个属性。您必须从会话中检索它:

Object sss = session.getAttribute("MyAttribute");

And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:

并且由于您正在调度请求,因此您实际上不需要会话。您可以在 servlet 的请求对象中设置该属性:

request.setAttribute("MyAttribute", "test value");

Then read it as you are already doing in you JSP.

然后阅读它,就像您已经在 J​​SP 中所做的那样。

回答by Ioan

You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.

您应该避免使用 scriptlet,因为它们是 HTML 中的 Java 代码,它们破坏了 MVC 模式,它们丑陋、奇怪且已被弃用。

Simply replace :

简单地替换:

<% 
Object sss = request.getAttribute("MyAttribute"); 
String a = "22";

%>

with simply using EL${MyAttribute}

只需使用EL${MyAttribute}

But if you want to stick with scriptlets, you should get the attribute from the proper scope which is sessionin your case.

但是,如果您想坚持使用 scriptlet,则应该从适合session您的情况的适当范围中获取属性。