[英]How can I set a session variable in a servlet and get it in a 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
<%@ 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>
我在jsp上所做的任何操作都为null。
这个简单的代码有什么问题?
您正在从请求而不是会话中获取。
它应该是
session.getAttribute("MyAttribute")
我建议您使用JavaServer Pages标准标记库或表达式语言,而不要使用Scriplet
,因为它更易于使用,并且不易出错。
${sessionScope.MyAttribute}
要么
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
您也可以尝试${MyAttribute}
, ${sessionScope['MyAttribute']}
。
阅读更多
您在会话中设置属性。 您必须从会话中检索它:
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
中获取属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.