What is the cleanest way to autowire Spring Beans in a JSP?
autowired, java, jsp, spring
Solution
You can use Spring's ContextExposingHttpServletRequest:
HttpServletRequest decorator that makes all Spring beans in a given WebApplicationContext accessible as request attributes, through lazy checking once an attribute gets accessed.
This would require your controller code to wrap the original `HttpServletRequest` in a `ContextExposingHttpServletRequest`, and then forward that to the JSP. It can either expose specific named beans, or every bean in the context.
Of course, this just shifts the problem from your JSPs to your controller code, but that's perhaps a more manageable problem.
Problem
We're currently adding some new features to an old webapp which was using only JSP without any framework for the front. We have added Spring recently, and we would like to autowire our beans in our modified JSP, while not rewriting everything to use SpringMVC, Struts2 or Tapestry5. We're using autowiring by type, so it leads to get some code like this in the JSP, while previously getting the web application context ( as "wap") : ``` MyDao myDao = (MyDao) wap.getBeansOfType(MyDao.class).values().toArray()[0]; ``` We would like not to use such a code but rather automagically inject our beans directly in our JSPs as we would in a business bean using @Autowired annotation. In fact we're looking to the cleanest ways to inject our beans in our JSPs. What do you use ?