日期:2014-05-20  浏览次数:20713 次

用spring,在jsp中怎么得到一个bean啊?
初学spring

web.xml配置如下

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>

applicationContext.xml配置如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="greetingService"
class="mypackage.GreetingServiceImpl">
<property name="greeting" value="Buenos Dias!" />
</bean>
</beans>

然后就是两个文件,一个

package mypackage;

public interface GreetingService {
void sayGreeting();
}

另外一个

package mypackage;

public class GreetingServiceImpl implements GreetingService {
private String greeting;

public GreetingServiceImpl() {
}

public GreetingServiceImpl(String greeting) {
this.greeting = greeting;
}

public void sayGreeting() {
System.out.println(greeting);
}

public void setGreeting(String greeting) {
this.greeting = greeting;
}
}

然后就是一个jsp页面

<%@ page import="mypackage.*" %>
<%@ page import="org.springframework.context.ApplicationContext;*">
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils*" %>
<%
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
system.out.println("haha");
//GreetingService greetingService =(GreetingService) ctx.getBean("greetingService");
greetingService.sayGreeting();


%>

每次访问这个页面,tomcat都死掉,报什么dias的,是什么原因啊?一般使用什么方法得到bean呢?



------解决方案--------------------
//这样写看看
 ApplicationContext context = new FileSystemXmlApplicationContext("E:/workspace/TestSpring/src/applicationContext.xml");
GreetingServiceImplg = (GreetingServiceImpl)context.getBean("greetingService");
------解决方案--------------------
要看你配置文件放在哪里了

//放在src目录下的使用
ConfigMajor config = new ConfigMajor();
BeanFactory benfactory = new ClassPathXmlApplicationContext("applicationContext.xml");
benfactory.getBean("bean的id");

//放在WEB-INF目录下的使用
ConfigMajor config = new ConfigMajor();
BeanFactory benfactory = new FileSystemXmlApplicationContext("Webroot/WEB-INF/applicationContext.xml");
benfactory.getBean("bean的id");