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

Vit*_*lii 1 java jsp servlets session-variables

我正在学习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);
    }

}
Run Code Online (Sandbox Code Playgroud)

简单的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>
Run Code Online (Sandbox Code Playgroud)

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

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

Bra*_*raj 8

如果请求不是会话,你会得到.

它应该是

session.getAttribute("MyAttribute")
Run Code Online (Sandbox Code Playgroud)

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

${sessionScope.MyAttribute}
Run Code Online (Sandbox Code Playgroud)

要么

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

<c:out value="${sessionScope.MyAttribute}" />
Run Code Online (Sandbox Code Playgroud)

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

阅读更多