SpringBoot学习笔记八:Servlet三大组件以及拦截器

三大组件的注册可以通过配置类或者注解(servlet3.0及以上版本)的方式实现。下面以注解的方式为例附上实现代码:

1.Servlet

package com.mjj.springinitializrdemo.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;

/**
 * servlet逻辑处理类
 */

@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");//获取请求参数
        resp.getWriter().write("welcome:"+userName);  //请求的响应
    }

    //可以实现http的其他类型请求,如 delete,put等
}

2.过滤器

package com.mjj.springinitializrdemo.filter;

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


@WebFilter(urlPatterns = "/needFilter")  //需要被过滤的访问路径
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器诞生了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("myFilter is working ...");
        filterChain.doFilter(servletRequest, servletResponse);  //放行操作
    }

    @Override
    public void destroy() {
        System.out.println("过滤器的销毁");
    }
}

3.监听器

package com.mjj.springinitializrdemo.listener;

import javax.servlet.Servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;

@WebListener //监听器的类型有多种,可以分别实现对ServletContext, session ,application等的监听
// 可以根据使用场景按需选择
public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("容器上下文创建了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("容器上下文销毁了");
    }
}

注意:
使用注解的方式声明时,需要在启动类上添加@ServletComponentScan(basePackages = “包名”),示例代码如下:

@ServletComponentScan(basePackages = "ccom.mjj.springinitializrdemo.*")
@SpringBootApplication
public class SpringinitializrdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringinitializrdemoApplication.class, args);
    }

}

三大组件配置类的使用代码示例:

package com.mjj.springinitializrdemo.config;

import com.mjj.springinitializrdemo.filter.MyFilter;
import com.mjj.springinitializrdemo.listener.MyListener;
import com.mjj.springinitializrdemo.servlet.MyServlet;
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;

/**
 * 三大组件配置类
 */
@Configuration
public class MyWebConfig {

    @Bean
    public ServletRegistrationBean<MyServlet> servletRegistrationBean(){
        return new ServletRegistrationBean<>(new MyServlet(),
                "/myServlet");   // urlMappping参数表示请求路径
    }

    @Bean
    public FilterRegistrationBean<MyFilter> FilterRegistration(){
        FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/needFilter");  //对needFilter请求进行过滤
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean(){
        ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
        servletListenerRegistrationBean.setListener(new MyListener());
        return servletListenerRegistrationBean;
    }
}

4.拦截器(参考来源:https://blog.csdn.net/wmq_fly/article/details/82634287)

package com.mjj.springinitializrdemo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 预处理回调方法,实现处理器的预处理
     * 返回值:true表示继续流程;false表示流程中断,不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("开始拦截.........");
        return true;
    }

    /**
     * 后处理回调方法,实现处理器(controller)的后处理,但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("处理器处理完成之后,视图被渲染之前回调");
    }
    /**
     * 整个请求处理完毕回调方法,即在视图渲染完毕时回调,
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("请求完成后回调(可用于计算响应时间,检测性能)");
    }

}

使用配置类将拦截器注册到SpringBoot容器中

package com.mjj.springinitializrdemo.config;

import com.mjj.springinitializrdemo.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyInterceptorConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/user")
        .excludePathPatterns("/MyServlet");  //excludePathPatterns为排除拦截

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值