• SpringBoot 03: 常用web组件 - - - 拦截器 + Servlet + 过滤器


    常用web组件

    • 拦截器
    • Servlet
    • 过滤器

    使用思想

    • 创建自定义类
    • 实现或者继承框架里的接口或类
    • 将自定义类注册到框架中
    • 使用自定义类

    拦截器

    说明

    • 拦截器是SpringMVC中的一种对象,能拦截对Controller的请求
    • 拦截器框架中有系统的拦截器,还可以自定义拦截器,实现对请求的预先处理

    自定义拦截器

    • 创建自定义的拦截器类实现SpringMVC框架的HandlerInterceptor接口,根据对拦截时机的需求,重写接口里的对应方法
    package com.example.web.interceptor;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //实际应用中被拦截的请求在这里执行其他逻辑判断,是否放行由判断结果来定
            System.out.println("LoginInterceptor拦截器的preHandle方法执行");
            return true;
        }
    }
    
    • 注册拦截器
    package com.example.web.config;
    
    import com.example.web.interceptor.LoginInterceptor;
    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 MyAppConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //创建一个拦截器对象
            LoginInterceptor loginInterceptor = new LoginInterceptor();
            //需要拦截的url
            String[] interceptorUrl = {"/user/**"};
            //需要放行的url
            String[] excludeUrl = {"/user/login"};
            registry.addInterceptor(loginInterceptor)
                    .addPathPatterns(interceptorUrl)
                    .excludePathPatterns(excludeUrl);
        }
    }
    
    • Controller层
    package com.example.web.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class InterceptorTest {
        @RequestMapping("/user/account")
        @ResponseBody
        public String account(){
            return "访问账户页面";
        }
    
        @RequestMapping("/user/login")
        @ResponseBody
        public String login(){
            return "访问用户登录页面";
        }
    
    }
    

    Servlet

    • 创建Servlet类,继承HttpServlet
    package com.example.web.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    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 {
            //设置响应类型
            resp.setContentType("text/html;charset=utf-8");
            //获取输出流对象
            PrintWriter out = resp.getWriter();
            //向浏览器输出数据
            out.println("--- springboot的servlet被调用 ---");
            out.flush();
            out.close();
        }
    }
    
    • 注册Servlet, 让框架能找到Servlet
    package com.example.web.config;
    
    import com.example.web.servlet.MyServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyWebConfig {
        //调用方法,注册servlet
        //    @Bean
        //    public ServletRegistrationBean servletRegistrationBean(){
        //        return new ServletRegistrationBean(new MyServlet(), "/servlet.do");
        //    }
    
        //注册servlet的方式2
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
            servletRegistrationBean.setServlet(new MyServlet());
            servletRegistrationBean.addUrlMappings("/servlet1.do", "/servlet2.do");
            return servletRegistrationBean;
        }
    }
    

    过滤器

    说明

    • Filter是Servlet规范中的过滤器,可以处理请求,对请求的参数,属性进行调整。常常在过滤器中处理字符编码

    使用自定义过滤器

    • 创建自定义过滤器类
    package com.example.web.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    public class MyFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            servletResponse.setContentType("text/html;charset=utf-8");
            System.out.println("MyFilter的doFilter方法被调用");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    
    • 注册Filter过滤器对象
    package com.example.web.config;
    
    import com.example.web.filter.MyFilter;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyFilterConfig {
        //定义方法,注册过滤器
        @Bean
        public FilterRegistrationBean filterRegistrationBean(){
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(new MyFilter());
            filterRegistrationBean.addUrlPatterns("/user/*");
            return filterRegistrationBean;
        }
    }
    

    使用自定义字符集过滤器

    • 创建servlet
    package com.example.web.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    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 {
            //设置响应类型
            resp.setContentType("text/html");
            //获取输出流对象
            PrintWriter out = resp.getWriter();
            out.println("使用springboot字符过滤器");
            out.flush();
            out.close();
        }
    }
    
    • 注册servlet和配置字符集过滤器
    package com.example.web.config;
    
    import com.example.web.servlet.MyServlet;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.filter.CharacterEncodingFilter;
    
    @Configuration
    public class MyWebConfig {
        //注册servlet
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
            servletRegistrationBean.setServlet(new MyServlet());
            servletRegistrationBean.addUrlMappings("/test");
            return servletRegistrationBean;
        }
    
        //注册内置的字符过滤器
        @Bean
        public FilterRegistrationBean filterRegistrationBean(){
            //内置的字符过滤器
            CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
            //按需求定制字符过滤器
            characterEncodingFilter.setEncoding("utf-8");
            characterEncodingFilter.setForceEncoding(true);
            //注册按照个性化需求配置后的字符过滤器
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(characterEncodingFilter);
            filterRegistrationBean.addUrlPatterns("/*");
            return filterRegistrationBean;
        }
    }
    
    • 修改application.properties文件,让自定义的过滤器起作用
    #关闭springboot框架默认的字符编码格式:ISO-8859-1
    server.servlet.encoding.enabled=false
    

    使用框架内置的字符集过滤器

    • 创建servlet
    package com.example.web.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    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 {
            //设置响应类型
            resp.setContentType("text/html");
            //获取输出流对象
            PrintWriter out = resp.getWriter();
            out.println("**** 使用springboot字符过滤器 ****");
            out.flush();
            out.close();
        }
    }
    
    • 注册servlet
    package com.example.web.config;
    
    import com.example.web.servlet.MyServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyWebConfig {
        //注册servlet
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
            servletRegistrationBean.setServlet(new MyServlet());
            servletRegistrationBean.addUrlMappings("/test");
            return servletRegistrationBean;
        }
    }
    
    • 修改application.properties文件,让框架内置的字符集过滤器实现个性化定制
    #让springboot默认的字符过滤器生效
    server.servlet.encoding.enabled=true
    #将默认的字符过滤器的编码格式设置为utf-8
    server.servlet.encoding.charset=utf-8
    #将请求和响应的编码格式都按照字符过滤器中的编码格式来进行解析
    server.servlet.encoding.force=true
    
  • 相关阅读:
    亚马逊收到CPSC查验通知后卖家需要怎么弄?ASTM F963标准测试 ,CPC认证
    python基础----环境搭建-----01
    L39.linux命令每日一练 -- 第六章 文件备份与压缩命令 -- scp和rsync
    2024能源动力、机械自动化与航天航空技术国际学术会议(ICEPMAT2024)
    金仓数据库 KingbaseES V8 GIS 数据迁移方案(5. 第三方通用格式 GIS 数据迁移到 KES)
    Go语言网络编程(socket编程)TCP粘包
    仔细解读Linux中的“引导过程与服务内容”
    第四章-并发与同步思考题
    QTableWidget 的使用
    Java代码审计16之fastjson反序列化漏洞(1)
  • 原文地址:https://www.cnblogs.com/nefu-wangxun/p/16882975.html