spring整合普通Servlet web项目 在web.xml文件中配置spring容器启动

web.xml文件中配置如下:

  • 可以通过<param-value>classpath:application.xml</param-value>显式指定spring配置文件的位置;
  • 如果不指定的话,spring的配置文件名必须是applicationContext.xml,且必须放在WEB-INF
  • <param-value>中可以配置多个配置文件,每个配置文件路径使用,分开,也可以使用*通配符对相同前缀或者相同后缀的xml配置文件进行加载
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
</web-app>

在Servlet类中通过WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()获取spring容器实例:

@WebServlet(name = "QueryStudentServlet",urlPatterns = {"/queryStudent"})
public class QueryStudentServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    private WebApplicationContext getContext(){
        return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值