如何调用一个在JSP文件中返回列表的Java方法?

tag5nh1u  于 2022-12-07  发布在  Java
关注(0)|答案(1)|浏览(133)

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];
f87krz0w

f87krz0w1#

如果我没理解错你的问题,你想把返回/显示列表转换成JSP,那么这就是我的想法--

<%@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>

相关问题