上一节 学习完了 原始 java web项目 无web.xml怎么配置servlet

这节学习 java web项目 无web.xml怎么集成spring框架

使用过web.xml集成spring框架的同学应该对下面2个web.xml的配置都熟悉

spring的ContextLoaderListener监听器实现了ServletContextListener监听器

在web应用启动时会自动执行contextInitialized方法,寻找spring的配置文件application.xml,完成spring容器的启动工作

web.xml配置springmvc DispatcherServlet 如下,去除web.xml后  都需要有对应的解决方案

好了,下面开始学习去除web.xml的集成spring的方法

1. 新建一个maven web项目

上一节普通java web项目保留 ,新建一个maven web项目,建好后先删除web.xml文件

2.pom.xml引入spring依赖

pom.xml如下 使用的是spring  4.3.12 正式版本

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wying</groupId><artifactId>JavaSpringWebNoWebxmlDemo</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>JavaSpringWebNoWebxmlDemo Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target><spring.version>4.3.12.RELEASE</spring.version></properties><dependencies><!-- 引入 servlet-api.jar scope设置为provided不会打包到项目lib,项目在tomcat运行时 tomcat lib下已经有servlet-api.jar--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency></dependencies><build><finalName>JavaSpringWebNoWebxmlDemo</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build>
</project>

3.spring 去除web.xml原理

普通java web项目META-INF/service我们配置的javax.servlet.ServletContainerInitializer是指向的自己写的实现类

使用spring框架,spring已经提供了实现类,并且spring-web  META-INF/service 配置好了javax.servlet.ServletContainerInitializer,指向了spring的实现类,这样tomcat启动时就会执行spring实现类的onStartup方法

spring实现类位于  spring-web-4.3.12.RELEASE.jar  org.springframework.web.SpringServletContainerInitializer

查看spring源码,该类org.springframework.web.SpringServletContainerInitializer实现了servlet-api的ServletContainerInitializer接口

并且class上有一个@HandlesTypes({WebApplicationInitializer.class})注解,是servlet提供的javax.servlet.annotation.HandlesTypes,它配置的value为WebApplicationInitializer.class}

查看源码可以发现onStart会寻找HandlesTypes配置的class的子类,并执行WebApplicationInitializer子类的onStartup方法

这其实也很好理解 META-INF/service javax.servlet.ServletContainerInitializer是指向的spring的实现类,这个是编译成class的,我们无法修改,但是我们肯定是要写自己的逻辑的,所以通过HandlesTypes扩展

比如加载spring配置文件,启动spring容器,配置spring mvc DispatcherServlet, 配置普通的servlet 监听器等,

4.查看spring-web自带配置META-INF/service  javax.servlet.ServletContainerInitializer文件

有个警告,idea还是比较智能的,因为SpringServletContainerInitializer实现了ServletContainerInitializer.class,不引入servlet-api.jar找不到ServletContainerInitializer.class

pom.xml引入servlet-api.jar ,警告消失

  <!-- 引入 servlet-api.jar scope设置为provided不会打包到项目lib,项目在tomcat运行时 tomcat lib下已经有servlet-api.jar--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency>

5.先启动tomcat测试一波

因为我们还没编写实现WebApplicationInitializer的类, initializers.isEmpty()执行为true,将输入以下日志

但是我idea debug class进入了,server没打印出这个log,因为servletContext.log是打印在Tomcat Localhost Log中

6.一步一步来,接下来编写 class 实现WebApplicationInitializer.class

MySpringInitializer.class

package com.wying.web;import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;/*** description:编写实现类 实现WebApplicationInitializer* 这样tomcat启动时 先执行SpringServletContainerInitializer.class的onStartup方法* 在通过HandlesTypes配置 执行该class的onStartup方法* date: 2021/3/19* author: gaom* version: 1.0*/public class MySpringInitializer  implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {System.out.println("=========MySpringInitializer onStartup============");System.out.println("=========MySpringInitializer 启动spring容器============");// 代替 web.xml 中的 listener 初始化//<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>AnnotationConfigWebApplicationContext ac_spring = new AnnotationConfigWebApplicationContext();// listener中的加载spring.xml的配置文件内容 MySpringXml.class代替 spring.xmlac_spring.register(MySpringXml.class);//用于初始化spring配置文件 web项目可用可不用servletContext.addListener(new ContextLoaderListener(ac_spring));System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");AnnotationConfigWebApplicationContext ac_mvc = new AnnotationConfigWebApplicationContext();//MySpringMvcXml.class代替 spring-mvc.xmlac_mvc.register(MySpringMvcXml.class);//用于初始化spring配置文件 web项目可用可不用//配置spring dispatcherServlet  代替web.xml// <servlet-name>springDispatcher</servlet-name>//<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>DispatcherServlet dispatcherServlet = new DispatcherServlet(ac_mvc);//创建前端控制器去名字为dispatcherServlet  <servlet>标签ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);//启动顺序设置为1 tomcat启动时就初始化该servletregistration.setLoadOnStartup(1);//<servlet-mapping>里面的url-pattenregistration.addMapping("*.do");System.out.println("=========MySpringInitializer onStartup 运行完毕============");}
}

MySpringXml.class

package com.wying.web;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;/*** 相当于spring.xml文件* description:spring提供了使用代码去除 spring.xml配置文件的方式* 、。。既然servlet3.0 开始都去除web.xml了 spring也提供了一套去除自家xml配置的方法* 该class通过代码配置xml的内容* date: 2021/3/19* author: gaom* version: 1.0*/@Configuration
@ComponentScan(basePackages = "com.wying")
public class MySpringXml {//目前测试效果 不连接数据库// 配置datasource sessionFactory 也一样 通过@Bean注解 规则都差不多 xml的配置 都有对应的class method对应
}

MySpringMvcXml.class

package com.wying.web;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;/**相当于spring-mvc.xml文件* description:spring提供了使用代码去除 spring-mvc.xml配置文件的方式* 、。。既然servlet3.0 开始都去除web.xml了 spring也提供了一套去除自家xml配置的方法* 该class通过代码配置spring-mvc.xml的内容* date: 2021/3/19* author: gaom* version: 1.0*/@Configuration
@EnableWebMvc  //开启支持mvc
@ComponentScan(basePackages = "com.wying")
public class MySpringMvcXml {/*** 代替spring-mvc.xml* <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolve">* @return*/@Beanpublic InternalResourceViewResolver internalResourceViewResolver() {InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/views/");viewResolver.setSuffix(".jsp");return viewResolver;}}
TestController.class

新建一个controller,用于测试spring-mvc DispatcherServlet是否配置成功

package com.wying.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;/*** description:测试controller* date: 2021/3/19* author: gaom* version: 1.0*/
@Controller
public class TestController {@RequestMapping(value="test.do")public String testjsp(){return  "test";}
}

7.tomcat启动项目

成功打印出spring初始化日志

浏览器测试效果

http://localhost:8082/JavaSpringWebNoWebxmlDemo_war_exploded/访问项目根目录成功读取默认的index.jsp文件

http://localhost:8082/JavaSpringWebNoWebxmlDemo_war_exploded/test.do 测试controller,成功读取到jsp页面

8.使用spring.xml文件

目前已经实现去除web.xml和spring的所有配置文件,但是实际项目中我并不这么用,

使用java文件配置spring xml不方便,编译成class不好改动,虽然可以建立一个properties配置文件,java配置读取properties配置,但是有时xml也是需要改动的,

所以下面记录下使用spring.xml文件的方法

修改MySpringInitializer.class onStartup方法 改成读取spring.xml配置文件的方式

package com.wying.web;import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;/*** description:编写实现类 实现WebApplicationInitializer* 这样tomcat启动时 先执行SpringServletContainerInitializer.class的onStartup方法* 在通过HandlesTypes配置 执行该class的onStartup方法* date: 2021/3/19* author: gaom* version: 1.0*/public class MySpringInitializer  implements WebApplicationInitializer {//spring配置文件也去除的方式/*  @Overridepublic void onStartup(ServletContext servletContext) throws ServletException {System.out.println("=========MySpringInitializer onStartup============");System.out.println("=========MySpringInitializer 启动spring容器============");// 代替 web.xml 中的 listener 初始化//<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>AnnotationConfigWebApplicationContext ac_spring = new AnnotationConfigWebApplicationContext();// listener中的加载spring.xml的配置文件内容 MySpringXml.class代替 spring.xmlac_spring.register(MySpringXml.class);//用于初始化spring配置文件 web项目可用可不用servletContext.addListener(new ContextLoaderListener(ac_spring));System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");AnnotationConfigWebApplicationContext ac_mvc = new AnnotationConfigWebApplicationContext();//MySpringMvcXml.class代替 spring-mvc.xmlac_mvc.register(MySpringMvcXml.class);//用于初始化spring配置文件 web项目可用可不用//配置spring dispatcherServlet  代替web.xml// <servlet-name>springDispatcher</servlet-name>//<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>DispatcherServlet dispatcherServlet = new DispatcherServlet(ac_mvc);//创建前端控制器去名字为dispatcherServlet  <servlet>标签ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);//启动顺序设置为1 tomcat启动时就初始化该servletregistration.setLoadOnStartup(1);//<servlet-mapping>里面的url-pattenregistration.addMapping("*.do");System.out.println("=========MySpringInitializer onStartup 运行完毕============");}*///读取spring.xml 配置文件的方式@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {System.out.println("保留spring.xml方式=========MySpringInitializer onStartup============");System.out.println("=========MySpringInitializer 启动spring容器============");servletContext.setInitParameter("contextConfigLocation","classpath:spring.xml");//springMVC的servlet//添加监听servletContext.addListener(new ContextLoaderListener());System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet());dispatcher.setLoadOnStartup(1);dispatcher.addMapping("*.do");dispatcher.setInitParameter("contextConfigLocation","classpath:spring-mvc.xml");System.out.println("=========MySpringInitializer onStartup 运行完毕============");}
}

spring.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:annotation-config/><context:component-scan base-package="com.wying"/></beans>

spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:annotation-config/><context:component-scan base-package="com.wying"/><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean></beans>

启动项目

启动成功,并打印出读取spring.xml的方式

测试效果

和java文件代替xml效果一样,完成

项目源码已上传github,需要的同学可以下载

https://github.com/gaomeng6319/JavaSpringWebNoWebxmlDemo

03)java spi应用 java spring web项目 去除web.xml相关推荐

  1. IntelliJ idea 创建Web项目后web文件夹下没有WEB-INF的解决方法

    IntelliJ idea 创建Web项目后web文件夹下没有WEB-INF的解决方法 参考文章: (1)IntelliJ idea 创建Web项目后web文件夹下没有WEB-INF的解决方法 (2) ...

  2. apache目录 vscode_VsCode搭建Java开发环境(Spring Boot项目创建、运行、调试)

    VsCode搭建Java开发环境(Spring Boot项目创建.运行.调试) 安装如下两个主要扩展即可,这两个扩展已关联java项目开发主要使用的maven.springboot等所需要的扩展. 开 ...

  3. VsCode搭建Java开发环境(Spring Boot项目创建、运行、调试)

    本文转载自:https://www.cnblogs.com/miskis/p/9816135.html 安装如下两个主要扩展即可,这两个扩展已关联java项目开发主要使用的maven.springbo ...

  4. 【java】四步法:spring boot项目部署在CentOS 8(后端篇)

    四步法:spring boot项目部署在CentOS 8(后端篇) 一.使用IDEA打包项目为jar包(构建) 1. IDEA版本 2. maven版本 3. pom.xml 设置 4. 构建jar包 ...

  5. java动态工程_eclipse 创建maven 项目 动态web工程完整示例

    转自:https://www.cnblogs.com/noteless/p/5213075.html 此处只是使用maven 注意,以下所有需要建立在你的eclipse等已经集成配置好了maven了, ...

  6. java spi技术,Java SPI机制

    Java组件一个更为人熟知的名词"服务",与流行的微服务有所区别. 以往加载JDBC驱动使用如下方式:Class.forName() Java 1.6引入SPI机制,使用Drive ...

  7. 一个web项目中web.xmlcontext-param的作用

    转 <context-param>的作用: web.xml的配置中<context-param>配置作用 1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置 ...

  8. 如何把Spring Boot 项目变成一个XML配置的Spring项目

    现在大家都追赶新的技术潮流,我来逆行一下. 其实Spring Boot 隐藏了大量的细节,有大量的默认配置,其实通过xml配置的方式也可以达到和Spring Boot一样的效果. Profile 在S ...

  9. idea创建maven web项目,pom.xml文件一直显示红色

    想在idea里面用maven创建一个web项目 要配置maven, 刚开始使用的是maven的3.8.5的版本 (首先你的maven要先配置好,可以在终端输入mvn -v查看maven安装情况, 然后 ...

最新文章

  1. 寄存器位查看小工具.exe
  2. sqlmap常用操作命令
  3. 关于Class之深入Class
  4. .Net平台开发的技术规范与实践精华总结 (转)
  5. 代理的JavaOne 2016观察
  6. IM、RTC技术两生花,看融云如何打造“IM+RTC+Push”一站式通信云服务
  7. sublime生产力提升利器
  8. CMU 15-213 Introduction to Computer Systems学习笔记(3) Floating Point
  9. Enolsoft PDF Converter with OCR激活版
  10. ad20中如何在pcb里查找器件,AD中原理图如何查找相应的元件?
  11. 自然语言处理结合金融专业应用,主要在于资料搜集和处理。
  12. 网页设计中有效的配色
  13. Jenkins企业应用进阶详解
  14. 创新移动互联,阿凡题学习神器引领搜索新体验
  15. Frp配置——stcp及p2p模式
  16. 从零开始搭建公司域环境(二):服务器安装域控并实现客户端加域登陆
  17. 全能成熟稳定开源分布式存储Ceph破冰之旅-上
  18. select2搜索内容显示搜索词
  19. kali 中 嗅探工具 如何分类
  20. 混得再得意,憋在心里也别说这3种话,败事有余,背后挨刀子

热门文章

  1. “BIM+智慧工地”精准“数字化”变身智慧工程“管家”
  2. Anaconda安装以及pytorch cpu版本安装配置
  3. 基于JSP的大学生健康管理系统
  4. win10 / ubuntu 双系统安装
  5. USB Camera Driver issue
  6. 建筑八大员培训湖北质量员培训古建筑施工中的质量控制要点
  7. html 网页公式编辑软件,网页公式编辑系统
  8. 电脑开机卡在android,如何修复它:Android卡在引导屏幕上-万兴恢复专家
  9. iframe无边框(隐藏边框)
  10. LCD的Cell制程