Spring 框架配置web.xml 整合web struts

package cn.itcast.e_web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebServlet("/Demo1Servlet")
public class Demo1Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //如何获得spring容器
        //1 获得servletContext域
        ServletContext sc = this.getServletContext();
        //2 调用工具从域取出容器
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
    
        System.out.println(ac.getBean("user"));
        
    }

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

}

 用监听器listener 监听servletContext(8大监听器之一)的创建 把Spring框架的applicationContext容器(就是applicationContext.xml文件)放到application域中

说白了就是web项目启动时能够扫描spring框架的配置文件applicationContext.xml

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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>spring-day02</display-name>

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

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

查看源代码ContextLoaderListener类中的父类

 

Spring 已经把ServletContextListener这个监听器写好,直接用就可以了

 




 

 

过滤Action,生效struts2要配置过滤器,配置文件中增加代码

  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

 

posted @ 2018-05-24 20:12  Advancing-Swift  阅读(243)  评论(0编辑  收藏  举报