简体   繁体   中英

How do I invoke a Java method which returns a list in JSP file?

I've looked into invoking a Java method but I am stuck trying to call a Java method which returns a list so that I can use that list in JSP.

JSP:

<%@ page import="mainPack.ShoppingService"%>
<%@ page import="java.util.List" %>

     $('#mainCheckbox').on( "change",function () {
            <%
             ShoppingService s = new ShoppingService();
            %>
            <%
            List<String> storesList = s.getStoresList();
            %>
            //unresolved variable error
            console.log(storesList.contains("Macys"));

        });

Java:

 public List<String> getStoresList() {
        return storeDao.getStoresList();
 }

I've also tried going into the controller and making it an attribute.

JSP:

 $('#mainCheckbox').on( "change",function () {
                //I get a Uncaught Reference Error: Macys Not Defined
                var jsArray = ${storesList};
    
            });

Java:

model.addAttribute("storesList", ShoppingService.getStoresList());

I am not sure the second attempt isn't working. When I open up debugger I see that it seems to translate the list into:

var jsArray = [Macys, JcPenny, Kohls, Target];

If I understand your question correctly, you want to return / display list into JSP, then this is what I am thinking --

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.List"%>
<html>
<%List<String> str=new ArrayList(); 
str.add(0, "testing");
str.add(1, "testing1");
str.add(2, "testing2");
%>
<tr><%=str%></tr>


</html>

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