千家信息网

Springboot中如何整合Servlet

发表于:2025-01-25 作者:千家信息网编辑
千家信息网最后更新 2025年01月25日,这篇文章将为大家详细讲解有关Springboot中如何整合Servlet,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、springboot入门•
千家信息网最后更新 2025年01月25日Springboot中如何整合Servlet

这篇文章将为大家详细讲解有关Springboot中如何整合Servlet,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、springboot入门

•  Spring Boot设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。 •  嵌入的 Tomcat,无需部署 WAR 文件 •  Spring Boot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式。

POM.xml

                    org.springframework.boot        spring-boot-starter-parent        2.1.9.RELEASE                                     org.springframework.boot        spring-boot-starter-web        
springBoot启动器其实就是一些jar包的集合。SprigBoot一共提供44启动器。    1 spring-boot-starter-web    支持全栈式的web开发,包括了romcat和springMVC等jar    2 spring-boot-starter-jdbc    支持spring以jdbc方式操作数据库的jar包的集合    3 spring-boot-starter-redis    支持redis键值存储的数据库操作

Controller

package com.lee.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestControllerpublic class HelloWorld {    @RequestMapping("/hello")    public Map hello(){        Map resultMap = new HashMap<>();        resultMap.put("msg","hello world");        return resultMap;    }}

启动类

package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringbootApplication {    public static void main(String[] args) {        SpringApplication.run(SpringbootApplication.class, args);    }}
@SpringBootApplication包含:        @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan、@Configuration等注解,它是一个配置类,扫描了当前包和当前包下所有子包下的所有文件

结果:http://localhost:8080/hello

{"msg":"hello world"}

二、Springboot整合Servlet

两种方式完成组件的注册:

1、通过注解扫描完成组件的注册

FirstServlet

package com.lee.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;/** * springboot整合servlet的第一种方式: *   原来 *       *          firstServlet *          com.lee.FirstServlet *       *       *          firstServlet *          /firstServlet *       */@WebServlet(name="firstServlet",urlPatterns = "/firstServlet")public class FirstServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doPost(req,resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("firstServlet............");    }}

启动类:

package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;//该注解会扫描当前包和其子包下的 @WebServlet,//并在启动类启动的时候将其实例化@ServletComponentScan@SpringBootApplicationpublic class SpringbootApplicationServlet1 {    public static void main(String[] args) {        SpringApplication.run(SpringbootApplicationServlet1.class,args);    }}

结果:http://localhost:8080/firstServlet

firstServlet............

2、通过方法完成组件的注册

SecondServlet

package com.lee.servlet;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 SecondServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doPost(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("secondServlet....");    }}

启动类

package com.lee;import com.lee.servlet.SecondServlet;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class SpringbootApplicationServlet2 {    public static void main(String[] args) {        SpringApplication.run(SpringbootApplicationServlet2.class,args);    }    //将scondServlet注册到servletRegistrationBean中    @Bean    public ServletRegistrationBean secondServlet(){        ServletRegistrationBean bean = new ServletRegistrationBean();        bean.setServlet(new SecondServlet());        bean.addUrlMappings("/secondServlet");        return bean;    }}

结果:http://localhost:8080/secondServlet

secondServlet....

三、Springboot整合Filter

两种方式完成组件的注册

1、通过注解扫描完成组件的注册

FirstFilter

package com.lee.filter;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;/** *  *     FirstFilter *     com.lee.filter.FirstFilter *  *  *     FirstFilter *     /firstServlet *  *///@WebFilter(filterName = "firstFilter",urlPatterns = {"*.do","*.action"})@WebFilter(filterName = "firstFilter",urlPatterns = "/firstServlet")public class FirstFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {        System.out.println(" first filter init");    }    @Override    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {        System.out.println("enter first filter");        filterChain.doFilter(servletRequest, servletResponse);        System.out.println("leave first filter");    }    @Override    public void destroy() {        System.out.println(" first filter destroy");    }}

启动类

package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;//该注解会扫描当前包和其子包下的 @WebServlet @WebFilter等,//并在启动类启动的时候将其实例化@ServletComponentScan@SpringBootApplicationpublic class SpringbootApplicationFilter1 {    public static void main(String[] args) {        SpringApplication.run(SpringbootApplicationFilter1.class,args);    }}

结果:http://localhost:8080/firstServlet

first filter initenter first filterfirstServlet............leave first filter

2、通过方法完成组件的注册

SecondFilter

package com.lee.filter;import javax.servlet.*;import java.io.IOException;public class SecondFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {        System.out.println(" second filter init");    }    @Override    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {        System.out.println("enter second filter");        filterChain.doFilter(servletRequest, servletResponse);        System.out.println("leave second filter");    }    @Override    public void destroy() {        System.out.println(" second filter destroy");    }}

启动类

package com.lee;import com.lee.filter.SecondFilter;import com.lee.servlet.SecondServlet;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class SpringbootApplicationFilter2 {    public static void main(String[] args) {        SpringApplication.run(SpringbootApplicationFilter2.class,args);    }    //将scondServlet注册到servletRegistrationBean中    @Bean    public ServletRegistrationBean secondServlet(){        ServletRegistrationBean bean = new ServletRegistrationBean();        bean.setServlet(new SecondServlet());        bean.addUrlMappings("/secondServlet");        return bean;    }    @Bean    public FilterRegistrationBean secondFilter(){        FilterRegistrationBean bean = new FilterRegistrationBean();        bean.setFilter(new SecondFilter());        bean.addUrlPatterns("/secondServlet");        return bean;    }}

结果:

second filter initenter second filtersecondServlet....leave second filter

四、SpringBoot整合Interceptor

之前在 《springboot使用redis和ThreadLocal做单点登录 》中,已经使用过拦截器,有兴趣的可以看一下。

1、POM

    org.springframework.boot    spring-boot-starter-web

2、自定义拦截器

public class MyInterceptor implements HandlerInterceptor {     private final Logger logger = LoggerFactory.getLogger(this.getClass().getCanonicalName());     @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {        logger.info("{}:在请求处理之前进行调用(Controller方法调用之前)", this.getClass().getSimpleName());        return true;//只有返回true才会继续向下执行,返回false取消当前请求    }     @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {        logger.info("{}:请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)", this.getClass().getSimpleName());    }     @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {        logger.info("{}:在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)", this.getClass().getSimpleName());    }}

3、添加拦截器

@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter{     @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");//用于添加拦截规则        // 多个拦截器组成一个拦截器链        // excludePathPatterns 用户排除拦截    }}

关于Springboot中如何整合Servlet就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

0