开发者

access java object in javascript

开发者 https://www.devze.com 2023-03-29 04:02 出处:网络
I am using spring framework. I am passing java bean object as model attribute to JSP. On JSP I am calling a javascript function passing this java bean object. I need to access memebers of this object

I am using spring framework. I am passing java bean object as model attribute to JSP. On JSP I am calling a javascript function passing this java bean object. I need to access memebers of this object inside the javascript. below is the code snippet

Test.jsp
..
..
<form:radiobutton id="showdialog" path="nextAction" value="showdialog" label="show dialog" 
    onclick="javascript: showDiseaseGroupDialog('${dataRequestFormDTO}');"/></span></div>
..
..

Common.js
function showDiseaseGroupDialog(dataRequestFormDTO){

    alert("DG:"+dataRequestFormDTO.selectedDiseaseGroup);
 开发者_如何学运维   for(var diseaseGroupDTO in dataRequestFormDTO.availableDiseaseGroups.values){
        alert(diseaseGroupDTO.name);
    }
}

DataRequestFormDTO.java
public class DataRequestFormDTO{
    private String selectedDiseaseGroup;
    private Map<String, DiseaseGroupDTO> availableDiseaseGroups;

    public String getSelectedDiseaseGroup() {
        return selectedDiseaseGroups;
    }

    public void setSelectedDiseaseGroup(String selectedDiseaseGroup) {
        this.selectedDiseaseGroup = selectedDiseaseGroup;
    }

    public Map<String, DiseaseGroupDTO> getAvailableDiseaseGroups() {
        return availableDiseaseGroups;
    }

    public void setAvailableDiseaseGroups(
            Map<String, DiseaseGroupDTO> availableDiseaseGroups) {
        this.availableDiseaseGroups = availableDiseaseGroups;
    }
}

public class DiseaseGroupDTO {

    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Problem is I am getting error in showDiseaseGroupDialog function. First alert displays "DG:undefined" and javascript error "availableDiseaseGroups is undefined".

I want to understand

  1. Why java bean members are not accessible in javascript? Though in jsp I can print the same values.

  2. how hashmap/arraylist can access in javascript?


Javascript is poorly named, it has nothing to do with Java. You can't use a java object directly in javascript just like you can't use a C++ object in it.


You cannot pass a java object directly into javascript, because the java object is only meaningful with Java Virtual Machine while the javascript can only be interpreted by the JS engine in browser. But you can transform the java bean into a JSON format or other plain text format.

0

精彩评论

暂无评论...
验证码 换一张
取 消