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");
    }
}

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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 <SCRIPT type="text/javascript"> $(document) .ready( function() { var myJson = jQuery.parseJSON(jsonObject); console.log(myJson); }); </SCRIPT>
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.