我有一个关于servlet和jsp的问题。
Servlet:
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,但是看到null。为什么会发生?
请求参数从视图发送到控制器,请求属性用于在当前请求中传递数据,以帮助构建新的响应。因此,您不应该使用scriplet并通过使用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
http://yourServerName/yourApplicationName/servlet