2014-02-24 52 views
1

我有一个关于servlets和jsp的问题。从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,但我看空。为什么会发生?

+0

固定它。结果是一样的:( –

+0

同一个应用程序(WAR,项目...)中包含的servlet和JSP? –

+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

+0

好的建议所有的。 –

0

使用request.getAttribute( “VAR”);

+0

我修好了。我仍然看到“null” –

+0

可能是围绕括号是问题...现在不能检查。顺便说一句,我宁愿Luiggi解决方案;) – AzAh

0

我不知道在servlet但在Struts 2中你需要从JSP发送的数据的getter和setter方法,你试试这个:

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