0

I'm making a dynamic web project in Eclipse and cannot figure out how to send the result of the query to a jsp file.

This is the servlet doGet:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession();
        String name = session.getAttribute("user").toString();
        String query = "SELECT DISTINCT t.text, t.user, t.date"
                + " FROM users u, tweets t, follows f" 
                + " Where t.parent is null"
                + " AND u.id ='"+name + "'"
                + " AND ( f.follower = u.id"
                + " AND f.followed = t.user"
                + " OR t.user = u.id)"
                + " ORDER BY t.date DESC;";
        try {
            ResultSet rs = Dao.executeQuerySQL(query);
            while (rs.next()){
                //Get all tweets -> THIS IS THE INFO I WANT TO RETRIEVE 
                rs.getString(1);

            }

}

and this is the timeline.jsp:

<script>
$(document).ready(function(){


});
</script>
This is the timeline!

How I can retrieve here in the jsp the information?

Thanks in advance.

Cheknov
  • 1,892
  • 6
  • 28
  • 55
  • In servlet `request.setAttribute("foo", yourvalue)` and in JSP `` (requires JSTL).... you can write `${foo}` (without the c:out tag), but that will not do HTML escaping. Also I am guessing you are doing FORWARD to the JSP and we are not talking about AJAX. – Pavel Horal Jun 17 '16 at 15:29
  • @PavelHoral Can I do it using Ajax? – Cheknov Jun 17 '16 at 15:37

2 Answers2

2

For Servlet section for doGet()

@WebServlet("/products")
public class ProductsServlet extends HttpServlet {

    @EJB
    private ProductService productService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productService.list();
        request.setAttribute("products", products); // Will be available as ${products} in JSP
        request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
    }

}

For JSP:

<table>
    <c:forEach items="${products}" var="product">
        <tr>
            <td>${product.name}</td>
            <td><a href="product?id=${product.id}">detail</a></td>
        </tr>
    </c:forEach>
</table>

Resource Link:

doGet and doPost in Servlets


UPDATE1 for AJAX:

Returning Map as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Resource Link:

How to use Servlets and Ajax?

Community
  • 1
  • 1
SkyWalker
  • 28,384
  • 14
  • 74
  • 132
0

Use one of the jquery ajax functions like .ajax or .get to call the servlet. Refer to below link for API.

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/jquery.get/

something like this,

$.get( "servlet url here", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

In your servlet convert your data to json or html snippet and write to response.

Santo
  • 362
  • 1
  • 4
  • 18