• Spring的web集成 (Spring监听器)


    如何在IDEA中用maven启动Tomcat

    Maven项目-jar包冲突:MyServlet is not a Servlet解决方法

    Spring访问传统的Servlet

    在这里插入图片描述
    web.xml

    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>HelloServletservlet-name>
            <servlet-class>cn.itcast.spring.servlet.HelloServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>HelloServletservlet-name>
            <url-pattern>/helloservleturl-pattern>
        servlet-mapping>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    HelloService.java

    package cn.itcast.spring.service;
    
    public class HelloService {
        public void sayHello(){
            System.out.println("嘿,传智播客。。。。");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    HelloServlet.java

    package cn.itcast.spring.servlet;
    
    import cn.itcast.spring.service.HelloService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class HelloServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            //传统方式:
            //new service
            //HelloService helloService = new HelloService();
            //spring方式:只要看到new,你就想到spring容器中的
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            HelloService helloService=(HelloService)applicationContext.getBean("helloService");
            System.out.println("helloService = " + helloService);
            helloService.sayHello();
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doGet(request, response);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    applicationContext.xml

    
    <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.xsd
    						   http://www.springframework.org/schema/context
    						   http://www.springframework.org/schema/context/spring-context.xsd">
    
        
        <bean id="helloService" class="cn.itcast.spring.service.HelloService"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    log4j.properties

    log4j.rootLogger=INFO,A1
    log4j.logger.org.apache=INFO
    log4j.appender.A1.Target=System.err
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    pom.xml(itcast-parent)

    <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.0modelVersion>
    
    	<groupId>cn.itcast.parentgroupId>
    	<artifactId>itcast-parentartifactId>
    	<version>0.0.1-SNAPSHOTversion>
    	<modules>
    		<module>mybatismodule>
    		<module>spring4module>
    	modules>
    	<packaging>pompackaging>
    
    	
    	<properties>
    		
    		<junit.version>4.12junit.version>
    		<spring.version>4.3.13.RELEASEspring.version>
    		<mybatis.version>3.2.8mybatis.version>
    		<mybatis.spring.version>1.2.2mybatis.spring.version>
    		<mybatis.paginator.version>1.2.15mybatis.paginator.version>
    		<mysql.version>5.1.32mysql.version>
    		<slf4j.version>1.6.4slf4j.version>
    		<jackson.version>2.9.0jackson.version>
    		<druid.version>1.0.9druid.version>
    		<httpclient.version>4.3.5httpclient.version>
    		<jstl.version>1.2jstl.version>
    		<servlet-api.version>2.5servlet-api.version>
    		<jsp-api.version>2.0jsp-api.version>
    		<joda-time.version>2.5joda-time.version>
    		<commons-lang3.version>3.3.2commons-lang3.version>
    		<commons-io.version>1.3.2commons-io.version>
    	properties>
    
    	<dependencies>
    
    		
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    			<scope>testscope>
    		dependency>
    
    
    	dependencies>
    
    
    	
    	<dependencyManagement>
    		<dependencies>
    			
    			<dependency>
    				<groupId>junitgroupId>
    				<artifactId>junitartifactId>
    				<version>${junit.version}version>
    				<scope>testscope>
    			dependency>
    
    			
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-testartifactId>
    				<version>${spring.version}version>
    				<scope>testscope>
    			dependency>
    
    			
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-contextartifactId>
    				<version>${spring.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-beansartifactId>
    				<version>${spring.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-webmvcartifactId>
    				<version>${spring.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-jdbcartifactId>
    				<version>${spring.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.springframeworkgroupId>
    				<artifactId>spring-aspectsartifactId>
    				<version>${spring.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>org.mybatisgroupId>
    				<artifactId>mybatisartifactId>
    				<version>${mybatis.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.mybatisgroupId>
    				<artifactId>mybatis-springartifactId>
    				<version>${mybatis.spring.version}version>
    			dependency>
    			<dependency>
    				<groupId>com.github.miemiedevgroupId>
    				<artifactId>mybatis-paginatorartifactId>
    				<version>${mybatis.paginator.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>mysqlgroupId>
    				<artifactId>mysql-connector-javaartifactId>
    				<version>${mysql.version}version>
    			dependency>
    
    			<dependency>
    				<groupId>org.slf4jgroupId>
    				<artifactId>slf4j-log4j12artifactId>
    				<version>${slf4j.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>com.fasterxml.jackson.coregroupId>
    				<artifactId>jackson-databindartifactId>
    				<version>${jackson.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>com.alibabagroupId>
    				<artifactId>druidartifactId>
    				<version>${druid.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>org.apache.httpcomponentsgroupId>
    				<artifactId>httpclientartifactId>
    				<version>${httpclient.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>jstlgroupId>
    				<artifactId>jstlartifactId>
    				<version>${jstl.version}version>
    			dependency>
    			<dependency>
    				<groupId>javax.servletgroupId>
    				<artifactId>servlet-apiartifactId>
    				<version>${servlet-api.version}version>
    				<scope>providedscope>
    			dependency>
    			<dependency>
    				<groupId>javax.servletgroupId>
    				<artifactId>jsp-apiartifactId>
    				<version>${jsp-api.version}version>
    				<scope>providedscope>
    			dependency>
    
    			
    			<dependency>
    				<groupId>joda-timegroupId>
    				<artifactId>joda-timeartifactId>
    				<version>${joda-time.version}version>
    			dependency>
    
    			
    			<dependency>
    				<groupId>org.apache.commonsgroupId>
    				<artifactId>commons-lang3artifactId>
    				<version>${commons-lang3.version}version>
    			dependency>
    			<dependency>
    				<groupId>org.apache.commonsgroupId>
    				<artifactId>commons-ioartifactId>
    				<version>${commons-io.version}version>
    			dependency>
    
    		dependencies>
    	dependencyManagement>
    
    	<build>
    		<finalName>${project.artifactId}finalName>
    		<plugins>
    			
    			<plugin>
    				<groupId>org.apache.maven.pluginsgroupId>
    				<artifactId>maven-resources-pluginartifactId>
    				<version>2.7version>
    				<configuration>
    					<encoding>UTF-8encoding>
    				configuration>
    			plugin>
    			
    			<plugin>
    				<groupId>org.apache.maven.pluginsgroupId>
    				<artifactId>maven-compiler-pluginartifactId>
    				<version>3.2version>
    				<configuration>
    					<source>1.8source>
    					<target>1.8target>
    					<encoding>UTF-8encoding>
    				configuration>
    			plugin>
    		plugins>
    		<pluginManagement>
    			<plugins>
    				
    				<plugin>
    					<groupId>org.apache.tomcat.mavengroupId>
    					<artifactId>tomcat7-maven-pluginartifactId>
    					<version>2.2version>
    				plugin>
    			plugins>
    		pluginManagement>
    	build>
    
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223

    pom.xml(spring4)

    
    <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">
        <parent>
            <artifactId>itcast-parentartifactId>
            <groupId>cn.itcast.parentgroupId>
            <version>0.0.1-SNAPSHOTversion>
        parent>
        <modelVersion>4.0.0modelVersion>
        <packaging>warpackaging>
        <artifactId>spring4artifactId>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>${spring.version}version>
            dependency>
    
            
            <dependency>
                <groupId>jstlgroupId>
                <artifactId>jstlartifactId>
                <version>${jstl.version}version>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>servlet-apiartifactId>
                <version>${servlet-api.version}version>
                <scope>providedscope>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>jsp-apiartifactId>
                <version>${jsp-api.version}version>
                <scope>providedscope>
            dependency>
    
            <dependency>
                <groupId>org.slf4jgroupId>
                <artifactId>slf4j-log4j12artifactId>
            dependency>
    
        dependencies>
    
        <build>
            <plugins>
                
                <plugin>
                    <groupId>org.apache.tomcat.mavengroupId>
                    <artifactId>tomcat7-maven-pluginartifactId>
                    <version>2.2version>
                    <configuration>
                        
                        <port>8088port>
                        
                        <path>/path>
                    configuration>
                plugin>
            plugins>
    
        build>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70

    用maven启动Tomcat

    在这里插入图片描述

    访问

    http://localhost:8088/helloservlet
    在这里插入图片描述

    在这里插入图片描述

    Spring的web集成 (Spring监听器)

    【思考、阅读】直接new ClassPathXmlApplicationContext()有什么缺点?
    缺点
    在创建Spring容器同时,需要对容器中对象初始化。而每次初始化容器的时候,都创建了新的容器对象,消耗了资源,降低了性能。
    解决思路:保证容器对象只有一个。
    解决方案:将Spring容器绑定到Web Servlet容器上,让Web容器来管理Spring容器的创建和销毁。
    分析
    ServletContext在Web服务运行过程中是唯一的, 其初始化的时候,会自动执行ServletContextListener 监听器 (用来监听上下文的创建和销毁),具体步骤为:
    编写一个ServletContextListener监听器,在监听ServletContext到创建的时候,创建Spring容器,并将其放到ServletContext的属性中保存(setAttribute(Spring容器名字,Spring容器对象) )。
    我们无需手动创建该监听器,因为Spring提供了一个叫ContextLoaderListener的监听器,它位于spring-web-4.3.13.RELEASE.jar中。

    开发步骤:

    第一步:引入spring-web的依赖

    pom.xml(spring4)

            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webartifactId>
                <version>4.3.13.RELEASEversion>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    第二步:在web.xml 配置Spring的核心监听器

    web.xml

    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>HelloServletservlet-name>
            <servlet-class>cn.itcast.spring.servlet.HelloServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>HelloServletservlet-name>
            <url-pattern>/helloservleturl-pattern>
        servlet-mapping>
        
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
        listener>
        
        <context-param>
            <param-name>contextConfigLocationparam-name>
            
            <param-value>classpath:applicationContext.xmlparam-value>
        context-param>
    
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    第三步:启动tomcat服务器,结果发现异常,因为默认会加载

    在这里插入图片描述
    根据异常提示:发现spring的BeanFactory没有初始化,说明没有找到spring容器,即applicationContext.xml文件

    第四步:在web容器中配置spring文件路径

    为什么没有找到applicationContext.xml文件呢?因为此时加载的是WEB-INF/applicationContext.xml,而不是src下的applicationContext.xml文件

    原因:找到ContextLoaderListener.class,再找到ContextLoader.class,发现默认加载的WEB-INF/applicationContext.xml

    在这里插入图片描述
    解决方案:
    需要在web.xml中配置,加载spring容器applicationContext.xml文件的路径

    web.xml

      
      <listener>
      	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
      listener>
      
      <context-param>
      	<param-name>contextConfigLocationparam-name>
      	
      	<param-value>classpath:applicationContext.xmlparam-value>
      context-param>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    重新启动tomcat服务器,没有异常,问题解决。

    第五步:修改Servlet代码。在Servlet 中通过ServletContext 获取Spring容器对象

    第一种方式: 使用getAttribute

    //每次获取的都是一个spring容器
    ApplicationContext applicationContext = 
    (ApplicationContext)this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    
    • 1
    • 2
    • 3

    第二种方式:使用WebApplicationContextUtils (推荐)

    //工具类
    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    
    • 1
    • 2

    HelloServlet.java

    package cn.itcast.spring.servlet;
    
    import cn.itcast.spring.service.HelloService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class HelloServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            //1.传统方式:
            //new service
            //HelloService helloService = new HelloService();
            //spring方式:只要看到new,你就想到spring容器中的
            //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            //2.每次获取的都是一个spring容器
           // ApplicationContext applicationContext = (ApplicationContext)this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    
            //3.工具类
            WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    
            HelloService helloService=(HelloService)applicationContext.getBean("helloService");
            System.out.println("helloService = " + helloService);
            helloService.sayHello();
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doGet(request, response);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    在这里插入图片描述

  • 相关阅读:
    网络黑客入门级工具:netwox
    配置Hive使用Spark执行引擎
    信钰证券:6G概念强势拉升,通宇通讯、世嘉科技涨停,硕贝德等走高
    Python语言
    Python-爬虫(基础概念、常见请求模块(urllib、requests))
    「微服务 | Nginx」upstream 模块负载均衡算法详解
    【解决方案】浅谈基于边缘计算的智慧工地解决方案
    如何快速构建研发效能度量的指标体系?
    【JVM基础】类加载机制
    【算法刷题日记之本手篇】计算日期到天数转换与幸运的袋子
  • 原文地址:https://blog.csdn.net/djydjy3333/article/details/126853419