将变量从servlet传递给jsp

Dev*_*per 51 jsp servlets

如何将变量从servlet传递给jsp? setAttributegetAttribute没有为我工作:-(

Bal*_*usC 83

在以下情况下它将无法工作:

  1. 您将会重定向到一个响应新的请求通过response.sendRedirect("page.jsp").新创建的请求对象当然不再包含属性,并且在重定向的JSP中无法访问它们.您需要转发而不是重定向.例如

    request.setAttribute("name", "value");
    request.getRequestDispatcher("page.jsp").forward(request, response);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您正以错误的方式访问它或使用错误的名称.假设您已使用名称设置它"name",那么您应该能够在转发的 JSP页面中访问它,如下所示:

    ${name}
    
    Run Code Online (Sandbox Code Playgroud)


小智 25

我找到的简单方法是,

在servlet中:

您可以设置值并将其转发到JSP,如下所示

req.setAttribute("myname",login);
req.getRequestDispatcher("welcome.jsp").forward(req, resp); 
Run Code Online (Sandbox Code Playgroud)

在Welcome.jsp中,您可以获取值

.<%String name = (String)request.getAttribute("myname"); %>
<%= name%>
Run Code Online (Sandbox Code Playgroud)

(或)直接你可以打电话

<%= request.getAttribute("myname") %>.
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 15

使用

了request.setAttribute( "的attributeName");

然后

.getServletContext()方法的getRequestDispatcher( "/ file.jsp")向前();

然后它将在JSP中可访问.

作为旁注 - 在你的jsp中避免使用java代码.使用JSTL.


Mar*_*lze 13

在将请求转发给jsp之前,您可以将所有值设置到响应对象中.或者,您可以将值放入会话bean并在jsp中访问它.


Tee*_*sti 13

除了使用属性将信息从servlet传递到JSP页面之外,还可以传递参数.这只需通过重定向到指定相关JSP页面的URL,并添加常规参数传递URL机制来完成.

一个例子.servlet代码的相关部分:

protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
    response.setContentType( "text/html" );
    // processing the request not shown...
    //
    // here we decide to send the value "bar" in parameter
    // "foo" to the JSP page example.jsp:
    response.sendRedirect( "example.jsp?foo=bar" );
}
Run Code Online (Sandbox Code Playgroud)

和JSP页面的相关部分example.jsp:

<%
    String fooParameter = request.getParameter( "foo" );
    if ( fooParameter == null )
    {
%>
    <p>No parameter foo given to this page.</p>
<%
    }
    else
    {
%>
    <p>The value of parameter foo is <%= fooParameter.toString() %>.</p>
<%
    }
%>
Run Code Online (Sandbox Code Playgroud)


小智 10

这是一个包含字符串变量a的servlet代码.a的值来自带有表单的html页面.然后将变量设置为请求对象.然后使用forwardrequestdispatcher方法将它传递给jsp .

String a=req.getParameter("username");
req.setAttribute("name", a);
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.forward(req, resp);
Run Code Online (Sandbox Code Playgroud)

在jsp中按照以下步骤执行程序

<%String name=(String)request.getAttribute("name");
out.print("your name"+name);%>
Run Code Online (Sandbox Code Playgroud)