java web 获取spring 通过配置web.xml 监听器加载的spring IoC容器

[转载自](https://www.cnblogs.com/zhangshitong/p/5387058.html)

java web中如何获取spring容器中定义的bean—-WebApplicationContext的使用

本文简单编写一个servlet来获取spring容器中管理的<bean  id=”dateBean” class=”java.util.Date” singleton=”false”/>本文只是简单举例,当然可以获取任意你想获取的bean

lib中放入spring所必须的jar包

1.首先看web.xml文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans-config.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>time</servlet-name>
        <servlet-class> com.ssh.action.TimeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>time</servlet-name>
        <url-pattern>/time.do</url-pattern>
    </servlet-mapping>
</web-app>
复制代码

2.看beans-config.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC 
 "-//SPRING/DTD BEAN/EN" 
 "http://www.springframework.org/dtd/spring-beans.dtd">
 <beans>
     <bean id="dateBean" class="java.util.Date" singleton="false"/>
 </beans>
复制代码

3.TimeServlet.java

复制代码
package com.ssh.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class TimeServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        WebApplicationContext ctx=WebApplicationContextUtils.
                getRequiredWebApplicationContext(this.getServletContext());
        PrintWriter out=resp.getWriter();
        out.println(ctx.getBean("dateBean"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(req, resp);
    }

}
复制代码

4.效果图:

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页