Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 395|回复: 0

SpringBoot使用servletAPI与异常处理

[复制链接]
  • TA的每日心情
    奋斗
    昨天 22:10
  • 签到天数: 756 天

    [LV.10]以坛为家III

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    707560
    发表于 2021-8-30 14:01:49 | 显示全部楼层 |阅读模式

    工程结构:

    主方法类:

    package com.boot.servlet.api.bootservlet;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
    
    // @ServletComponentScan //扫描的方式使用servlet
    @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class)
    public class BootServletApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(BootServletApplication.class, args);
        }
    }

    Setvlet

    package com.boot.servlet.api.bootservlet.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 = "MyServlet",urlPatterns = "/my")
    public class MyServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("执行了servlet请求");
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }

    过滤器

    package com.boot.servlet.api.bootservlet.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    
    @WebFilter(filterName = "MyFilter", urlPatterns = "/*")
    public class MyFilter implements Filter {
        public void destroy() {
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            System.out.println("执行filter");
            chain.doFilter(req, resp);
        }
    
        public void init(FilterConfig config) throws ServletException {
    
        }
    
    }

    监听器

    package com.boot.servlet.api.bootservlet.listener;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    
    @WebListener
    public class Listener implements ServletContextListener,
            HttpSessionListener, HttpSessionAttributeListener {
    
        // Public constructor is required by servlet spec
        public Listener() {
        }
    
        // -------------------------------------------------------
        // ServletContextListener implementation
        // -------------------------------------------------------
        public void contextInitialized(ServletContextEvent sce) {
          /* This method is called when the servlet context is
             initialized(when the Web application is deployed). 
             You can initialize servlet context related data here.
          */
            System.out.println("servlet容器启动");
        }
    
        public void contextDestroyed(ServletContextEvent sce) {
          /* This method is invoked when the Servlet Context 
             (the Web application) is undeployed or 
             Application Server shuts down.
          */
        }
    
        // -------------------------------------------------------
        // HttpSessionListener implementation
        // -------------------------------------------------------
        public void sessionCreated(HttpSessionEvent se) {
            /* Session is created. */
        }
    
        public void sessionDestroyed(HttpSessionEvent se) {
            /* Session is destroyed. */
        }
    
        // -------------------------------------------------------
        // HttpSessionAttributeListener implementation
        // -------------------------------------------------------
    
        public void attributeAdded(HttpSessionBindingEvent sbe) {
          /* This method is called when an attribute 
             is added to a session.
          */
        }
    
        public void attributeRemoved(HttpSessionBindingEvent sbe) {
          /* This method is called when an attribute
             is removed from a session.
          */
        }
    
        public void attributeReplaced(HttpSessionBindingEvent sbe) {
          /* This method is invoked when an attibute
             is replaced in a session.
          */
        }
    }

    除了使用注解外还可以使用配置类的方式实现:

    package com.boot.servlet.api.bootservlet.config;
    
    import com.boot.servlet.api.bootservlet.filter.MyFilter;
    import com.boot.servlet.api.bootservlet.listener.Listener;
    import com.boot.servlet.api.bootservlet.servlet.MyServlet;
    import org.springframework.boot.SpringBootConfiguration;
    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 java.util.Arrays;
    
    /**
     * 通过配置类的方式引入servlet
     */
    @SpringBootConfiguration
    public class ServletConfiguration {
    
        @Bean
        public ServletRegistrationBean<MyServlet> registrationBean() {
            ServletRegistrationBean<MyServlet> bean = new ServletRegistrationBean<>();
            bean.setServlet(new MyServlet());
            bean.setUrlMappings(Arrays.asList("/my"));
            return  bean;
        }
    
        @Bean
        public FilterRegistrationBean<MyFilter> filterFilterRegistrationBean() {
            FilterRegistrationBean<MyFilter> bean = new FilterRegistrationBean<>();
            bean.setFilter(new MyFilter());
            bean.setUrlPatterns(Arrays.asList("/*"));
    
            return bean;
        }
    
        @Bean
        public ServletListenerRegistrationBean<Listener> servletListenerRegistrationBean() {
            ServletListenerRegistrationBean<Listener> listener = new ServletListenerRegistrationBean<>();
            listener.setListener(new Listener());
    
            return listener;
        }
    }

    拦截器

    package com.boot.servlet.api.bootservlet.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 MyInteceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion");
        }
    }

    拦截器配置类

    package com.boot.servlet.api.bootservlet.config;
    
    import com.boot.servlet.api.bootservlet.interceptor.MyInteceptor;
    import org.springframework.boot.SpringBootConfiguration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    /**
     * 拦截器配置类
     */
    @SpringBootConfiguration
    public class MyWebMvcConfiguration extends WebMvcConfigurationSupport {
        @Override
        protected void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInteceptor());
        }
    }

     

    springBoot自定义错误页面处理

    默认读取的静态资源位置:"classpath:/META-INF/resources/", "classpath:/resources/",
    "classpath:/static/", "classpath:/public/"

    非模板: public/error/xxx.html

    ​模板的: templates/errror/xxx.html

    ​ 异常处理:

    ​ 局部@ExceptionHandler

    ​ 全局@ControllerAdvice+@ExceptionHandler

     

    程序演示

    结构:

     

     

    package com.example.bootex.exception;
    
    /**
     * 自定义业务异常类
     */
    public class BizException extends RuntimeException { public BizException() { super(); } public BizException(String message) { super(message); } public BizException(String message, Throwable cause) { super(message, cause); } public BizException(Throwable cause) { super(cause); } protected BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }

     

     

    package com.example.bootex.controller;
    
    import com.example.bootex.exception.BizException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; @Controller public class PageController { /** * 局部异常处理 * @param ex * @param model * @return */ @ExceptionHandler(BizException.class) public String exPage1(Exception ex, Model model) { model.addAttribute("ex", ex); return "/error/biz.html"; } @GetMapping("/e500") public String e500() { throw new RuntimeException("runtime-exception"); } @GetMapping("/add") public String add() { throw new BizException("添加出现异常"); } }

     

     

    package com.example.bootex.exception;
    
    import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; /** * 全局业务处理 */ @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseStatus(code = HttpStatus.NOT_FOUND) public String e404() { return "error/404.html"; } @ExceptionHandler(RuntimeException.class) @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) public String e500() { return "error/500.html"; } }

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-6-28 18:22 , Processed in 0.071372 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表