美文网首页
5、SpringBoot Web组件

5、SpringBoot Web组件

作者: ravenLu | 来源:发表于2024-01-14 23:09 被阅读0次

SpringBoot注册Web组件: Servlet、Filter、Listener

由于SpringBoot没web.xml文件,无法在web.xml注册web组件,可用SpringBoot的方式注册。

一、Servlet

Servlet注册方式一:

新建项目 选择Spring Web 新建类Servlet1

package com.example.demo.servlet;import jakarta.servlet.annotation.WebServlet;import jakarta.servlet.http.HttpServlet;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/first")public class Servlet1 extends HttpServlet {

@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp){

System.out.println("这是Servlet1");

}

}

在启动类加上注解 @ServletComponentScan

运行程序,在浏览器输入 http://127.0.0.1:8080/first 

可看到控制台打印日志

Servlet注册方式二:

通过配置类注册的方式

创建类 Servlet2 创建配置文件

package com.example.demo;import com.example.demo.servlet.Servlet2;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;

@Configurationpublic class ServletConfig {

// ServletRegistrationBean注册Servlet组件,放入Spring容器即可

@Bean

public ServletRegistrationBean getServletRRegistrationBean (){

// 注册Servlet组件 ServletRegistrationBean bean= new ServletRegistrationBean(new Servlet2());

// 添加Servlet访问路径

bean.addUrlMappings("/second");

return bean;

}}

运行代码,在浏览器输入  http://127.0.0.1:8080/second

可看到日志输出

二、Filter

新建类filterDemo

三、Listener

方式一:

创建类listener1

编写代码

package com.example.demo.Listener;import jakarta.servlet.ServletContextEvent;import jakarta.servlet.ServletContextListener;import jakarta.servlet.annotation.WebListener;

@WebListenerpublic class listener1 implements ServletContextListener { @Override

public void contextInitialized(ServletContextEvent sce){

System.out.println("调用listener1 contextInitialized ");

}

@Override

public void contextDestroyed(ServletContextEvent sce){

}

}

编译运行,效果如下图:

方式二:

参考方式一写上listener2类 去掉注解 创建ListenerConfig

写上代码:

package com.example.demo;import com.example.demo.Listener.listener2;

import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configurationpublic class ListenerConfig {

@Bean public ServletListenerRegistrationBean getServletListenerRegistrationBean(){

ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new listener2());

return bean;

}

}

运行代码,效果(控制台打印)如下:

相关文章

网友评论

      本文标题:5、SpringBoot Web组件

      本文链接:https://www.haomeiwen.com/subject/naecodtx.html