0

My requirement is that i have to put some value or list into key value pair on Json object,for that i have done something like this on java class but not able to figure out how to retrieve that same Json object used in java class through java script on jsp page.Please help me out with problem

import org.json.simple.JSONObject;
class BeanManager{
    private JSONObject jsonObject;
    public JSONObject getJson()
    {
        jsonObject=new JSONObject();
        jsonObject.put("name","jack Daniel");
        jsonObject.put("age","3");
    }
}
cweiske
  • 30,033
  • 14
  • 133
  • 194
user1527637
  • 51
  • 1
  • 6

2 Answers2

0

In JSP attach JSON content to html node and then in JavaScript read node content and evaluate them as JS Object.

Such solution might be usefull as temporal only. Consider to use another way

Aleks F
  • 11
  • 1
0

Attach your class instance as request attribute before forwarding to your JSP and use it in the view afterwards. Also, be sure not to do business job in the getter (and return an object if you claim to).

All in all, the class code could look like:

class BeanManager{

private JSONObject jsonObject;
private String jsonObjectString;

public BeanManager() {
    jsonObject=new JSONObject();
    jsonObject.put("name","jack Daniel");
    jsonObject.put("age","3");
    jsonObjectString = jsonObject.toString();
}

public JSONObject getJsonObjectString() {
    return jsonObjectString;
}

}

The relevant servlet part could look like:

BeanManager bm = new BeanManager();//manipulate it the way you want
request.setAttribute("bean", bm);
request.getRequestDispatcher("/WEB-INF/view.jsp").forward(request, response);

The view could contain the following part:

<script>
    var json = ${bm.jsonObjectString};
</script>

This way, json variable will be available in JavaScript context.

In case you'd like to deal with AJAX requests, take a look at How to use Servlets and Ajax? question and its answer. There, JSON object is returned from servlet and later parsed into HTML document.

Community
  • 1
  • 1
skuntsel
  • 11,624
  • 11
  • 44
  • 67
  • i am trying to do same think in jsf application can u please let me know how to retrieve the same json object using jquery – henrycharles Jul 23 '13 at 10:42
  • In JSF it's not typically done that way, though it is possible. For more information you can see my answer to [How to pass a List to javascript in JSF](http://stackoverflow.com/a/16563361/1820286). – skuntsel Jul 23 '13 at 10:51
  • yeah its working one more thing i need to ask how to add the value in gson as a key value pair cause i need the value in json format on webpage – henrycharles Jul 23 '13 at 12:23