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

2018-06-18 00:48:40来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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>

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java获取IP地址

下一篇:mysql保存不了4字节的问题(也就是表情)