0

I am new to Java servlets and JSP...

I have created a Java servlet. Actually this is my first servlet I am working on!

Inside of my servlet code, I have a loop. For each iteration of this loop, there are variables that will be set to different values. After each iteration of this loop ends, I want to be able to print out my variables (these variables will change with each iteration of the loop) in a HTML table as a row....

After doing some research, it seems that I need to use a JSP page to output the variables in HTML. However, how can I send my data to the JSP page after each iteration of my loop?

pseudocode example:

--servlet logic

   forloop{
       var1 = "somedata";
       var2 = "somemoredata";
    }

--jsp logic

 //this part should only output once   
<table>
    <thead><tr><th></th></tr></thead>

    //this part needs to output everytime the JSP is called. And each time, different values of var1 and var2 will be passed 
    <tr>
    <td>${var1}</td>
    <td>${var2}</td>
    </tr>

    </table>

Does anyone know the best method to do this? If I am going about this the wrong way, is there another approach I should take? Should I use AJAX to continue feeding information to update my page?

Thank you for any advice and insights!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
tt2244
  • 71
  • 11

2 Answers2

1

You need to construct a data structure which will hold the results from your servlet and have to be passed to JSP. In your JSP you can loop through the data and construct table rows.

One thing to remember is, JSP even though might seem like HTML files but eventually they are same as Java Servlet which basically is nothing but Java Class. You can't load jsp everytime you perform a loop in your Servlet. The idea is Java Servlet prepares the data and passed to JSP for presentation.

Servlet

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

  private String message;

  public void init() throws ServletException
  {
      // Do required initialization
      message = "Hello World";
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    List<String> data = null;
    // do you loop here
    //pass the data to jsp
    String jsp = ""; //jsp path
    ServletContext sc = getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher(jsp);

    request.setAttribute("data", data );
    rd.forward(request, response);
  }

  public void destroy()
  {
      // do nothing.
  }
}

JSP

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach items="${data}" var="d">
    <tr>      
        <td>${d}</td>
    </tr>
</c:forEach>
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • Thanks for your advice. I have tried this but when I try to implement the jstl, the I get an error The method proprietaryEvaluate(String, Class, PageContext, null) is undefined for the type PageContextImpl – tt2244 Mar 03 '16 at 05:09
0

You can use my solution but It will only work it you know exactly how many variables you are going to use. Instead of adding them using JSP code use AJAX requests and JQuery

Sample JSP:

<html>
<head>...</head>
<body>
    <table>
       <thead><tr><th></th></tr></thead>
       <tbody id="text"> 
       </tbody>
    </table>
    <button id="submit" onClick="addData()">Click me</button>
</body>
... import Jquery....
<script> 
    function addData(){
        $.ajax({
            type:'POST',
            url: ./MyServlet,
            data:{//data name://value},
            success: function(response){
            $("#text").append(response);
        });
    } 
</script>
</html>

Sample Servlet:

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

          String text="";
          String values[][]={{"1","2"},{"4","5"},{"6","7"},{"8","9"}} //your values it really can be anything

          for(int i=0;i<values.length;i++){
              text=text+"<tr>\n";
              text=text+"<td>"+values[i][0]+"</td>\n";
              text=text+"<td>"+values[i][1]+"</td>\n";
              text=text+"</tr>\n";
          }

          out.print(text);
    }
}

Hope it can help you. Good Luck

HFR1994
  • 536
  • 1
  • 5
  • 16