南开小巷

导航

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

posted on 2016-04-13 14:34  南开小巷  阅读(2540)  评论(0编辑  收藏  举报