Reputation: 3328
I want to call an method from an object in jsp.
I have an servlet which passes an object to a jsp page. On this page I want to execute the getHtml()
method. How do I accomplish this?
Servlet
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
...
MyClass myObject = new MyClass();
response.setAttribute(myObject, "myObject");
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
MyClass
public class MyClass {
public String getHtml() {
return "<p>Hello World</p>";
}
}
Upvotes: 0
Views: 199
Reputation: 11665
You may do:
<div>${myObject.getHtml()}</div>
As it is a property and with the get prefix you may also do:
<div>${myObject.html}</div>
Or this way to scape HTML characters to avoid cross-site scripting:
<div><c:out value="${myObject.hHtml}"/></div>
All this ways assume that those methods return a String. If you need a piece of dynamic HTML it is OK. If you are doing some business logic in JSP it would be looked as a potencial bad practice. Try to put as much logic as possible in the controller or service and get the results preprocessed as properties or use jsp tags. At some point the html of the jsp will need to change or you would have used html instead.
Upvotes: 1