JavaWeb操纵中得到Spring的ApplicationContext[Java编程]
本文“JavaWeb操纵中得到Spring的ApplicationContext[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
ApplicationContext是Spring的容器环境,通过ApplicationContext对象可以拜候全部配置的bean.
在Web开辟开辟中,常常需求从JSP大概Servlet大概Action中获得ApplicationContext对象,这时刻,就无法利用new关键字通过查找配置文件来实例化ApplicationContext这个对象了.Spring通过WebApplicationContextUtils可以便利实现您的需求.下面看个例子:
1、Spring2.5+Struts2环境下
1、配置web.xml,通过这个配置来获得的.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</web-app>
2、在JSP、Servlet、Action中获得ApplicationContext
<%@ page import="lavasoft.service.TestService" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Simple jsp page</title></head>
<body>
<%
// ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
TestService service = (TestService) ctx.getBean("testService");
String s = service.test();
out.print(s);
%>
</body>
</html>
以上是“JavaWeb操纵中得到Spring的ApplicationContext[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |