简体   繁体   中英

Access java object from JSP inside javascript

I have a jsp page which contains an object Person. I need to access the Person object inside javascript.

My JSP code

<%
 Person person = new Person();
 person.setName("Towhid");
 person.setAddress("BD");
%>
<script>
    var person;
</script>

The code between within the JSP tags only exists on the server. It it not available in the HTML sent to the client.

To access the Person data in the Vue object, you need to "print" the Person data into the script tag. For example:

<%
 Person person = new Person();
 person.setName("Towhid");
 person.setAddress("BD");
%>
<script>
    new Vue({
        el: '#app',
        data: {
          personName: '<%=person.getName()%>'
          personAddress: '<%=person.getAddress%>'
        }
    });
</script>

Note that this approach is a demonstration of how it can be done, but not how it should be done. The approach above is vulnerable to XSS attacks because the hand-crafted JSON data is not properly escaped. To do this properly, you need to either use a JSP tag to escape the person content to JSON, or use a serialization technique that can provide the person data as JSON.

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