将变量从Servlet发送到JSP [英] Sending a variable from Servlet to JSP

查看:69
本文介绍了将变量从Servlet发送到JSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于servlet和jsp的问题.

I got a question about servlets and 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,但我看到为空.为什么会发生?

As a result I expect to see 15, but I see null. Why does it happen?

推荐答案

请求参数从视图发送到控制器,请求属性用于在当前请求中传递数据,以帮助构建新的响应.因此,您 不应使用Scriplet ,而应使用表达语言:

Request parameters are sent from the view to the controller, request attributes are used to pass data in the current request to help build the new response. So, you should not use scriplets and access to the request attributes by using 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

Note that by your current request, you should perform a GET request on your servlet. Since your servlet name is servlet (which I suggest your to change it immediately), you should access to this URL: http://yourServerName/yourApplicationName/servlet

这篇关于将变量从Servlet发送到JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆