spring集成web环境

也就是说, 以前的分析不用手动实现, Spring提供了一个监听器, 叫做ContextLoaderListener就是对上述功能的封装, 该监听器内部加载Spring配置文件, 创建应用上下文对象, 并存放到ServletContext域中, 提供了一个客户端工具, 叫做WebApplicationContextUtils供使用者获得上下文对象

我们要做两件事:
在web.xml中配置ContextLoaderListener(导入spring-web的jar包)
使用WebApplicationContextUtils获取app对象

		<dependency>
          <!--spring集成web环境的jar包-->
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>5.0.5.RELEASE</version>
      </dependency>
<!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>
  <display-name>Archetype Created Web Application</display-name>

  <!--全局初始化变量-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--配置监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>



</web-app>

很明显, 在web.xml中的这个操作是使用spring-web这个jar包的关键(使用spring集成的监听器)
记得两个词
一个是ContextLoaderListener, 监听器的名称
一个是contextConfigLocation, 监听器使用的变量名称

@WebServlet("/saveUserServlet")
public class SaveUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = req.getServletContext();
        //ApplicationContext app = (ApplicationContext)servletContext.getAttribute("app");
        //使用这个工具类就可以完全忽略域中app的键名
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = (UserService)app.getBean("userService");
        userService.save();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

为了隐藏键名写了一个getWebApplicationContext(servletContext)方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值