简体   繁体   中英

Get data from servlet to JSP without forward?

I need a double value from my servlet to markup in my JSP. My doGet() is sending back formatted HTML tables with values from an ArrayList, so after I got that working I decided to tackle this part.

Servlet:

//Code getting the tables I need

    //Send back the result, this all works good
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(returnAsHTML.toString());

What I added to try and get the double value

    //Send back the result

    double test = 20;
    request.setAttribute("Test",test);

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(returnAsHTML.toString());

    getServletContext().getRequestDispatcher("index.jsp").forward(request,response);

In JSP:

  <!-- This variable is unresolved -->
  <small>Test : ${Test}</small>

The forwarding seems to crash the whole party. I am new to JSP, I'm sure I am missing something small. I need to keep the response.getWriter() stuff there, it gets a lot of the information I need. Now I just don't know how to get my double values I need as well, because they will be displayed on a whole different part of the page.

You cannot write output to the servletOutputStream and redirect at the same time.

What do you expect from the browser: to display content or to navigate to another page? If the first, don't redirect. If the second, don't display HTML content.

Try using httpsession. Encapsulate whatever object you have using session.setAttribiute(). Then forward it using the sendRedirect() method.

Might be of this kind

HttpSession session=request.getSession();
double test = 20;
session.setAttribute("Test",test);
response.sendRedirect("Index.jsp");

On the JSP page

String s=(String)session.getAttribite("Test");
double d=Double.parseDouble(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM