上一节 学习完了 原始 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 {
@Override
public 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.xml
ac_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.xml
ac_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启动时就初始化该servlet
registration.setLoadOnStartup(1);
//<servlet-mapping>里面的url-patten
registration.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
*/
@Bean
public 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配置文件也去除的方式
/* @Override
public 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.xml
ac_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.xml
ac_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启动时就初始化该servlet
registration.setLoadOnStartup(1);
//<servlet-mapping>里面的url-patten
registration.addMapping("*.do");
System.out.println("=========MySpringInitializer onStartup 运行完毕============");
}*/
//读取spring.xml 配置文件的方式
@Override
public 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/beans
http://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/beans
http://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