posts - 66, comments - 12, trackbacks - 0, articles - 0

jsp中使用spring aop (转帖)

Posted on 2008-08-05 11:11 cyantide 阅读(685) 评论(0)  编辑  收藏 所属分类: spring

在JSP中使用Spring其实很容易,主要用到Spring的WebApplicationContextUtils.getWebApplicationContext函数。

要再JSP里面得到ApplicationContext需要这么做,首先import="org.springframework.web.context.support.*,org.springframework.context.*"

然后可以通过如何做法:

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

这样就得到了ApplicationContext,就可以操作Spring了。

JSP本来就可以认为是一个Servlet,所以使用getServletContext()就是理所应当了。

一:web.xml配置

<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

 


二:在JSP

<%@ page import="org.springframework.context.ApplicationContext"%>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page import="com.yourcompany.service.CategoryService"%>

<%
//上面的CategoryService引用是我自己的东西
//applicationContext.xml中一定要有完整的依赖链,从dataSource到CategoryService

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
CategoryService cs = (CategoryService) ctx.getBean("CategoryService");
List list =cs.getCategoryDAO().findAll();
%>


只有注册用户登录后才能发表评论。


网站导航: