Jsp调用Spring中的Bean

来源:互联网 发布:动态规划算法的边界 编辑:程序博客网 时间:2024/05/17 06:46

Jsp调用Spring中的Bean

 (2012-01-27 16:45:45)
转载
标签: 

webapp

 
想做一个最简单的Web应用程序,就包含一个Jsp页面,演示如何直接调用Spring中的Bean,后台数据库访问由Spring+Hibernate解决。使用JUnit做后台的添加、查询测试很简单,但是Jsp直接调用Spring中的Bean难住了。下面是一步步解决问题,
    1) 如何从Jsp中得到Spring中的Bean?
    首先直接使用jsp:useBean是不行的,
<jsp:useBean id="demoService" class="geda.qa.SpringDemoWeb.DemoService" scope="request">
    需要使用下面的WebApplicationConext,
<%
 WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
 IDemoService ds = (IDemoService)wac.getBean("demoService");
%>
    详细的解释请看,webintegration
    当然Jsp页面最开始,需要引用相应的类,
<%@page import="org.springframework.web.context.WebApplicationContext" %>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils" %>

    2) 在获得bean以后,紧接着就遇到Exception java.lang.ClassCastException: $Proxy13 cannot be cast to DemoService问题。Google,百度一顿找啊,在百度知道里面有回答,请使用接口。一直不解。为什么不使用接口,直接使用类就会出现ClassCastException?
    因此,我将原来的类,
public class DemoService extends BaseServiceForHibernate<Demo>
    改成同时继承一个接口,
public class DemoService extends BaseServiceForHibernate<Demo> implements IDemoService
    在Jsp中使用该接口,
IDemoService ds = (IDemoService)wac.getBean("demoService");
0 0