我正在学习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']}
也是如此。
阅读更多
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句