Before directing to your JSP, make sure to attach your class instance as a request attribute and then utilize it in the view afterwards. Additionally, avoid performing business logic within the getter method (and ensure you are returning an object when necessary).
Overall, the structure of the class code could be similar to:
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 corresponding servlet section may resemble:
BeanManager bm = new BeanManager();//customize it accordingly
request.setAttribute("bean", bm);
request.getRequestDispatcher("/WEB-INF/view.jsp").forward(request, response);
The view could include the following segment:
<script>
var json = ${bm.jsonObjectString};
</script>
By doing this, the JSON variable can be accessed within the JavaScript environment.
If you are looking to handle AJAX requests, refer to How to use Servlets and Ajax? question and its solution. In that scenario, a JSON object is sent back from the servlet and subsequently converted into an HTML document.