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.效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值