如何在servlet中设置会话变量并在JSP中获取它?
我正在学习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); } }
而简单的jsp
My Index page Index page
无论我在jsp上做什么都是空的。
这个简单的代码有什么问题?
如果请求不是会话,你会得到。
它应该是
session.getAttribute("MyAttribute")
我建议您使用JavaServer Pages标准标记库或表达式语言而不是Scriplet
,它更易于使用且不易出错。
${sessionScope.MyAttribute}
要么
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
您也可以尝试${MyAttribute}
, ${sessionScope['MyAttribute']}
。
阅读更多
-
Oracle教程 – 使用JSTL
-
Oracle教程 – 表达式语言
您在会话中设置属性。 您必须从会话中检索它:
Object sss = session.getAttribute("MyAttribute");
因为您要分派请求,所以实际上您不需要会话。 您可以在servlet中的请求对象中设置该属性:
request.setAttribute("MyAttribute", "test value");
然后阅读它,因为你已经在JSP中做了。
你应该避免使用scriptlet,因为它们是HTML中的java代码,它们破坏MVC模式,它们很丑,很奇怪并且已经弃用了。
简单地替换:
<% Object sss = request.getAttribute("MyAttribute"); String a = "22"; %>
只需使用EL ${MyAttribute}
但是如果你想坚持使用scriptlet,你应该从适当的范围获取属性,这是你的情况下的session
。