我有一个关于 servlet 和 jsp 的问题。
小服务程序:
public class Servlet extends javax.servlet.http.HttpServlet {
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
Integer i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
JSP 页面:
<html>
<head>
<title></title>
</head>
<body>
<form id="id" method="get" action="servlet">
<%= (request.getAttribute("var")) %>
</form>
</body>
</html>
因此,我希望看到 15,但我看到的是空值。为什么会这样?
最佳答案
请求参数从 View 发送到 Controller ,请求属性用于在当前请求中传递数据以帮助构建新的响应。所以,你should not use scriplets并使用 Expression Language 访问请求属性:
<body>
<!-- No need to use a form for this page -->
The request attribute: ${var}
</body>
请注意,根据您当前的请求,您应该对您的 servlet 执行 GET 请求。由于您的 servlet 名称是 servlet(我建议您立即更改它),您应该访问此 URL:http://yourServerName/yourApplicationName/servlet
关于java - 将变量从 Servlet 发送到 JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21992539/