I have the following class.
class Bar {
public Bar(String fooVal) {
this.foo = fooVal;
}
private String foo;
public String getFoo() {
return this.foo;
}
@Override
public String toString() {
return this.foo;
}
}
The following controller
class Controller {
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public ModelAndView() {
return new ModelAndView("barJSP", "barModel", new Bar("testFooVal"));
}
}
And now I am trying to access in jsp the value of foo.
I have the following two variants of JSP in the barJSP trying to print the foo Vals.
<% System.out.println(pageContext.findAttribute("barModel.foo")); %>
This prints null. However
<% System.out.println(pageContext.findAttribute("barModel")); %>
This prints testFooVal as expected (it actually prints the thing that toString() returns).
My understanding of jsp syntax is that . is used to access members and should work as long as getters are defined for it. Am I missing something?
You can use JSP EL
for easily accessing objects:
${barModel.foo}
Otherwise, you have to import model class and cast for converting:
<%@ page import="com.example.model.Bar"%>
<% Bar b = (Bar)(pageContext.findAttribute("barModel"));
out.println(b.getFoo());
%>