1. 程式人生 > 其它 >Spring——整合Web環境()

Spring——整合Web環境()

簡介

  Spring集合Web環境:通過Listener自動建立ApplicationContext,並放入ServletContext中。通過這樣不用每次都new ApplicationContext()

操作

  1. web.xml中配置ContextLoaderListener監聽器,監聽Web啟動

  

<!-- 全域性初始化引數:讓監聽器從配置的路徑中取得applicationContext.xml  -->
<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>

  2.使用WebApplicationContextUtils獲得應用上下文物件ApplicationContext

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

 使用

  <!-- 全域性初始化引數:讓監聽器從配置的路徑中取得applicationContext.xml  -->
  <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
>
@WebServlet(value = "/userController")
public class UserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
    }
}