如何在Servlet中设置会话变量并在JSP中获取它? [英] How can I set a session variable in a servlet and get it in a JSP?
本文介绍了如何在Servlet中设置会话变量并在JSP中获取它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Java,并尝试将一些变量从servlet传递到jsp页面.这是servlet页面中的代码
I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page
@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.
Whatever I do attribete at jsp is null.
这个简单的代码有什么问题?
What is wrong at this simple code?
推荐答案
如果从请求而不是会话中获取,则得到了
you are getting if from request not session.
应该是
session.getAttribute("MyAttribute")
我建议您使用 JavaServer Pages标准标记库或表达语言(而不是Scriplet
)更容易使用且不易出错.
I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet
that is more easy to use and less error prone.
${sessionScope.MyAttribute}
或
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
您也可以尝试${MyAttribute}
,${sessionScope['MyAttribute']}
.
了解更多
这篇关于如何在Servlet中设置会话变量并在JSP中获取它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文