How can we get JavaScript array by JSP scriptlet

前端 未结 2 1872
迷失自我
迷失自我 2021-01-22 03:08

I need JavaScript array/multidimensional which is returned by Java class,



        
2条回答
  •  礼貌的吻别
    2021-01-22 03:43

    Just let Java/JSP print a syntactically valid JS array syntax. Keep in mind that Java/JSP and JavaScript doesn't run in sync. Java/JSP produces HTML as one large String and JS is just part of it. JS ultimately runs in the webbrowser once it has retrieved all that HTML output from Java/JSP.

    Assuming that you ultimately want the following valid JS array syntax:

    
    

    Then you should write your Java/JSP code accordingly so that it prints exactly that syntax:

    
    

    It's only terribly unreadable (and not only because of using old fashioned scriptlets instead of taglibs). Easier, however, is to grab a JSON (JavaScript Object Notation) library like Google Gson and create an additional method getOptionsAsJson() which does something like the following:

    public getOptionsAsJson(Object value) {
        return new Gson().toJson(getOptions(value));
    }
    

    And finally use it instead:

    
    

提交回复
热议问题