工程结构:

主方法类:

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";
}
}

SpringBoot使用servletAPI与异常处理的更多相关文章

  1. SpringBoot优雅的全局异常处理

    前言 本篇文章主要介绍的是SpringBoot项目进行全局异常的处理. SpringBoot全局异常准备 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要求 JD ...

  2. SpringBoot中的全局异常处理

    SpringBoot中的全局异常处理 本篇要点 介绍SpringBoot默认的异常处理机制. 如何定义错误页面. 如何自定义异常数据. 如何自定义视图解析. 介绍@ControllerAdvice注解 ...

  3. SpringBoot系列——自定义统一异常处理

    前言 springboot内置的/error错误页面并不一定适用我们的项目,这时候就需要进行自定义统一异常处理,本文记录springboot进行自定义统一异常处理. 1.使用@ControllerAd ...

  4. springboot aop + logback + 统一异常处理 打印日志

    1.src/resources路径下新建logback.xml 控制台彩色日志打印 info日志和异常日志分不同文件存储 每天自动生成日志 结合myibatis方便日志打印(debug模式) < ...

  5. SpringBoot系列: Spring项目异常处理最佳实践

    ===================================自定义异常类===================================稍具规模的项目, 一般都要自定义一组异常类, 这 ...

  6. springboot restful接口服务异常处理

    一.spring boot中默认的错误处理机制 二.自定义的异常处理

  7. SpringBoot(七)_统一异常处理

    我感觉看了这节课,给我的思考还是很多的,感觉受益良多.废话不多说,一起学习. 统一的 外层结构返回 这样利于代码看着也规范,前端处理也统一 # 错误返回 { "code": 1, ...

  8. SpringBoot开发案例之异常处理并邮件通知

    前言 在项目开发中,对于异常处理我们通常有多种处理方式,比如:控制层手动捕获异常,拦截器统一处理异常.今天跟大家分享一种注解的方式,统一拦截异常并处理. 异常处理 在spring 3.2中,新增了@R ...

  9. 外部tomcat发布springboot项目步骤和异常处理:java.lang.NoClassDefFoundError: javax/el/ELManager

随机推荐

  1. gg_pie

    gg_pie gg_pie PeRl 今天尝试了一下用ggplot2画饼图,转换一下极坐标就可以实现,但是和以前画heatmap的时候不一样的是,我们在卷坐标的时候需要让数据集中在一个坐标轴上. 另一 ...

  2. 初识主席树_Prefix XOR

    主席树刚接触觉得超强,根本看不懂,看了几位dalao的代码后终于理解了主席树. 先看一道例题:传送门 题目大意: 假设我们预处理出了每个数满足条件的最右边界. 先考虑暴力做法,直接对x~y区间暴枚,求 ...

  3. 深圳Uber司机本周(7.13-7.19凌晨4:00)的奖励政策

    本周(7.13-7.19凌晨4:00)的奖励政策为: 佣金返还: 车费的20%适用于所有产品(不包括Tesla)无获取条件 翻倍补贴: 每周一到周四07:00-10:00/17:00-22:00:车费 ...

  4. 一个体验好的Windows 任务栏缩略图开发心得

    本文来自网易云社区 作者:孙有军 前言: 对于一个追求极致体验的软件来说,利用好系统的每一点优秀的特性,将会大大提高软件的品质. Windows vista以来任务栏缩略图,及Win + TAB的程序 ...

  5. 聊聊WS-Federation(test)

    本文来自网易云社区 单点登录(Single Sign On),简称为 SSO,目前已经被大家所熟知.简单的说, 就是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统. 举例: 我们 ...

  6. Use GitHub Desktop to get GitHub projects

    Find the project's https git file in the home page of the project. e.g. https://github.com/PrismLibr ...

  7. RabbitMQ基础教程之Spring&JavaConfig使用篇

    RabbitMQ基础教程之Spring使用篇 相关博文,推荐查看: RabbitMq基础教程之安装与测试 RabbitMq基础教程之基本概念 RabbitMQ基础教程之基本使用篇 RabbitMQ基础 ...

  8. lesson 24 A skeleton in the cupboard

    lesson 24 A skeleton in the cupboard conceal sth from sb 对某人隐藏某事 He conceals his girlfriend from his ...

  9. C 数数位 while循环

    #include <stdio.h> int main(int argc, char **argv) { //定义两个变量  x n 把n初始化 int x; int n=0; //输入x ...

  10. 【转】: 《江湖X》开发笔谈 - 热更新框架

    前言 大家好,我们这期继续借着我们工作室正在运营的在线游戏<江湖X>来谈一下热更新机制以及我们的理解和解决方案.这里先简单的介绍一下热更新的概念,熟悉这部分的朋友可以跳过,直接看我们的方案 ...