Pages

25/09/2013

[Java] Spring use DAO in JSP page

So you're happily coding your webapp with Spring, and have all your DAOs correctly defined as beans; you know they work because you are constantly injecting them around, but now you need to access one of them from a JSP.. how?

You may find this code fragment useful:

 <%@page import="com.groglogs.mydaos.MyDao"%>  
 <%@page import="org.springframework.web.context.WebApplicationContext"%>  
 <%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>  
   
 <%  
 MyDao myDao = null;  
   
 WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());  
 if (context != null) {  
   myDao = (MyDao) context.getBean("myDao");  
 }  
 %>  

You import your DAO, and request it directly from the JSP. Note that this example relies on the fact that somewhere you have correctly defined a bean named "myDao".

No comments:

Post a Comment

With great power comes great responsibility