我有一个关于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。为什么会这样?
答案 0 :(得分:5)
请求参数从视图发送到控制器,请求属性用于传递当前请求中的数据以帮助构建新响应。因此,您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
答案 1 :(得分:0)
使用request.getAttribute(“var”);
答案 2 :(得分:0)
我不知道在servlet中但是在struts 2中你需要getter和setter方法来从jsp发送数据,你试试这个:
public class Servlet extends javax.servlet.http.HttpServlet
{
private Integer i;
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
public Integer getI()
{
return i;
}
public void setI(Integer i)
{
this.i = i;
}
}//also lacked this