SpringBoot 使用JavaWeb三大件(Servlet,Filter,Listener)

一.以war包打包运行

那就跟以前一样在web.xml注册相应的servlet等信息即可

1.注册三大件

基本结构

SpringBoot 使用JavaWeb三大件(Servlet,Filter,Listener)_第1张图片

三大件代码

HelloServlet Servlet

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 java.io.IOException;

@WebServlet(name = "HelloServlet")
public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("Hello Servlet");
    }
}

HelloFilter 过滤器

import javax.servlet.*;
import java.io.IOException;

/**
 * 配置Hello请求的过滤器
 */
public class HelloFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Hello Filter ...");
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

HelloListener 监听器

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *
 */
public class HelloListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Hello Listener init ...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Hello Listener dead ...");
    }
}

配置文件web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>demodisplay-name>

    
    <servlet>
        <servlet-name>HelloServletservlet-name>
        <servlet-class>com.fjut.springboot.servlet.HelloServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>HelloServletservlet-name>
        <url-pattern>/hellourl-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>HelloFilterfilter-name>
        <filter-class>com.fjut.springboot.servlet.HelloFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>HelloFilterfilter-name>
        <url-pattern>/hellourl-pattern>
    filter-mapping>

    
    <listener>
        <listener-class>com.fjut.springboot.servlet.HelloListenerlistener-class>
    listener>

    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>
web-app>

运行结果:

...
2018-07-15 09:11:41.172  INFO 7504 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-15 09:11:41.172  INFO 7504 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'getDataSource' has been autodetected for JMX exposure
2018-07-15 09:11:41.181  INFO 7504 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'getDataSource': registering with JMX server as MBean [com.alibaba.druid.pool:name=getDataSource,type=DruidDataSource]
2018-07-15 09:11:41.198  INFO 7504 --- [on(3)-127.0.0.1] com.fjut.springboot.ServletInitializer   : Started ServletInitializer in 4.597 seconds (JVM running for 8.654)
Hello Listener init ...
[2018-07-15 09:11:41,235] Artifact spring-boot-06-jdbc:war exploded: Artifact is deployed successfully
[2018-07-15 09:11:41,236] Artifact spring-boot-06-jdbc:war exploded: Deploy took 7,728 milliseconds
15-Jul-2018 09:11:42.463 信息 [http-nio-8080-exec-3] org.apache.tomcat.util.http.parser.Cookie.logInvalidHeader A cookie header was received [1530005427,1530030667,1530059808; JSESSIONID=29BE6A814A0C05F2E3C9650B43DC8445] that contained an invalid cookie. That cookie will be ignored.Note: further occurrences of this error will be logged at DEBUG level.
15-Jul-2018 09:11:43.330 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [D:\Program Files\Tomcat 8.5\webapps\manager]
15-Jul-2018 09:11:43.376 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\Program Files\Tomcat 8.5\webapps\manager] has finished in [46] ms
Hello Filter ...
Hello Filter ...
"D:\Program Files\Tomcat 8.5\bin\catalina.bat" stop
Using CATALINA_BASE:   "C:\Users\LGX\.IntelliJIdea2018.1\system\tomcat\Unnamed_spring-boot-06-jdbc"
Using CATALINA_HOME:   "D:\Program Files\Tomcat 8.5"
Using CATALINA_TMPDIR: "D:\Program Files\Tomcat 8.5\temp"
Using JRE_HOME:        "D:\Program Files\Java\jdk1.8.0_161"
Using CLASSPATH:       "D:\Program Files\Tomcat 8.5\bin\bootstrap.jar;D:\Program Files\Tomcat 8.5\bin\tomcat-juli.jar"
15-Jul-2018 09:12:52.726 信息 [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
15-Jul-2018 09:12:52.726 信息 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
15-Jul-2018 09:12:52.849 信息 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
15-Jul-2018 09:12:52.966 信息 [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
2018-07-15 09:12:52.972  INFO 7504 --- [ost-startStop-2] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1461314: startup date [Sun Jul 15 09:11:37 CST 2018]; root of context hierarchy
2018-07-15 09:12:52.974  INFO 7504 --- [ost-startStop-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2018-07-15 09:12:52.974  INFO 7504 --- [ost-startStop-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans
Hello Listener dead ...
15-Jul-2018 09:12:53.000 信息 [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
15-Jul-2018 09:12:53.001 信息 [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
15-Jul-2018 09:12:53.002 信息 [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
15-Jul-2018 09:12:53.003 信息 [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]
Disconnected from server

二.以jar包打包运行

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文
件。

由于没有配置文件Spring Boot使用ServletRegistrationBeanFilterRegistrationBeanServletListenerRegistrationBean分别用来注册ServletFilterListener

1.SpringBoot使用配置类注册Servlet,Filter,Listener:

对应的servlet,filter,listener跟前文的三大件一样

配置类

import com.fjut.springboot.servlet.HelloFilter;
import com.fjut.springboot.servlet.HelloListener;
import com.fjut.springboot.servlet.HelloServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class WebConfig {

    /**
     * 注册Servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean helloServletServlet(){
        ServletRegistrationBean helloServlet = new ServletRegistrationBean<>(new HelloServlet(),"/hello");
        return helloServlet;
    }

    /**
     * 注册Filter
     * @return
     */
    @Bean
    public FilterRegistrationBean helloFilter(){
        FilterRegistrationBean helloFilter = new FilterRegistrationBean<>();
        helloFilter.setFilter(new HelloFilter());
        helloFilter.setUrlPatterns(Arrays.asList("/hello"));
        return helloFilter;
    }

    /**
     * 注册Listener
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean helloListener(){
        ServletListenerRegistrationBean helloListener = new ServletListenerRegistrationBean<>(new HelloListener());
        return helloListener;
    }
}

运行结果:

SpringBoot 使用JavaWeb三大件(Servlet,Filter,Listener)_第2张图片

你可能感兴趣的:(【05】SpringBoot)