0

how do I retrieve the values of a context in a jsp file? this tutorial is perfect for what I need but I need to retrieve the property values in the jsp file.

http://www.mkyong.com/spring/spring-listfactorybean-example/

is there a specific interceptor that I can use?

chip
  • 3,039
  • 5
  • 35
  • 59

2 Answers2

1

Inject your bean (or source) of userContext into your controller, so you have access to it in a local variable.

So taking the example maybe this is:

@Autowired
private CustomerBean customerBean;

@RequestMapping(value="/foobar/index.jsp")
public String (HttpServletRequest request) {
Object userContext = customerBean.getLists();
request.setAttribute("userContext", userContext);
return "/foobar/index.jsp";  // expecting JstlView viewResolver to map to JSP file
}

In the CONTROLLER simply add data to the HttpServletRequest (which you just add as argument to the method to introduce it).

Then use request.setAttribute("userContext", userContext); then in JSP simply access it using Expression Language like ${userContext}. There are other ways using Spring model paradigm but they effectively do the above.

Ensure you have your JstlView setup to https://dzone.com/articles/exploring-spring-controller

More info about how to use EL in JSPs to retrieve data attached to request: How to obtain request / session / servletcontext attribute in JSP using EL?

Community
  • 1
  • 1
Darryl Miles
  • 4,576
  • 1
  • 21
  • 20
1

You're referring to spring context right?

In general, JSPs should be a template of a page only, so the only interaction with the back-end should be accessing the values of the scoped attributes. This means that whichever bean value you need you should instead store in the model.

This being said, there are a few ways you can expose spring beans to view. Depends on which View resolver you're using, the ones that extend UrlBasedViewResolver have the setExposeContextBeansAsAttributes property

Set whether to make all Spring beans in the application context accessible as request attributes, through lazy checking once an attribute gets accessed. This will make all such beans accessible in plain ${...} expressions in a JSP 2.0 page, as well as in JSTL's c:out value expressions.

Default is "false".

You would configure it like

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
    <property name="exposeContextBeansAsAttributes" value="true" />
</bean>
Master Slave
  • 27,771
  • 4
  • 57
  • 55