欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP获取spring 的容器ApplicationContext 博客分类: Java WebJava spring容器JSP获取beanJSP获取容器WebApplicationContextUtils 

程序员文章站 2024-02-24 19:50:46
...

Jsp 中如何获取spring的bean呢?

方式一:通过上下文

 

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<%
ServletContext context = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
Object supermarketDao= ctx.getBean("supermarketDao");
System.out.println("jsp:"+supermarketDao);
%>
</body>
</html>

 问题:JSP页面中获取的bean与spring 容器中的bean是同一个吗?

 

是的

 

方式二:通过类路径加载bean文件,得到bean工厂

 

<?xml version="1.0" encoding="UTF-8" ?>
<%@page import="org.springframework.beans.factory.BeanFactory"%>
<%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<%
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml","user_beans.xml","goods_beans.xml","supermarket_beans.xml","aop.xml","upload_beans.xml"); 
BeanFactory factory = (BeanFactory) appContext; 
Object obj=factory.getBean("supermarketDao");
System.out.println("jsp2:"+obj);

%>
</body>
</html>

  问题:JSP页面中获取的bean与spring 容器中的bean是同一个吗?

 

是的

 

总结:(1)通过WebApplicationContextUtils 获取bean是直接从spring容器中拿的;

(2)通过ClassPathXmlApplicationContext,实际上又解析了一遍xml,即又创建了一个新的spring容器,所有获取的bean与web上下文中是不同的。