springboot - 在servlet中映射Errors 脱离spring mvc
应用不用Spring MVC, 采用ErrorPageRegistrar 接口能直接映射errors。
1、概览
2、java代码
1)、MyAppServlet
package com.ebc.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 = "appServlet", urlPatterns = "/app/*")
public class MyAppServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestURI = req.getRequestURI();
if (requestURI.endsWith("test")) {
throw new RuntimeException("test exception from " + requestURI);
} else if (requestURI.endsWith("test2")) {
throw new ServletException("test servlet exception");
} else {
resp.getWriter().println("Response from appServlet at " + requestURI);
}
}
}
2)、MyErrorPageRegistrar
package com.ebc.servlet; import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; @Component
public class MyErrorPageRegistrar implements ErrorPageRegistrar { @Override
public void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(
createNotFoundErrorPage(),
createRuntimeExceptionPage(),
createOtherErrorPage());
} private ErrorPage createNotFoundErrorPage() {
return new ErrorPage(HttpStatus.NOT_FOUND, "/notFoundServlet");
} private ErrorPage createRuntimeExceptionPage() {
return new ErrorPage(RuntimeException.class, "/runtimeExceptionHandler");
} private ErrorPage createOtherErrorPage() {
return new ErrorPage(Throwable.class, "/WEB-INF/internal-error.jsp");
}
}
3)、NotFoundServlet
package com.ebc.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;
import java.io.PrintWriter; @WebServlet(name = "not-found-error-servlet", urlPatterns = "/notFoundServlet")
public class NotFoundServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write("<h2>Page not found </h2>");
String requestUri = (String) req.getAttribute("javax.servlet.error.request_uri");
writer.write("request uri: " + requestUri);
writer.write("<br>Response from " + this.getClass());
}
}
4)、RuntimeExceptionServlet
package com.ebc.servlet; import javax.servlet.RequestDispatcher;
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;
import java.io.PrintWriter; @WebServlet(name = "runtime-handler-servlet", urlPatterns = "/runtimeExceptionHandler")
public class RuntimeExceptionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write("<h2>RuntimeException</h2>"); String requestUri = (String) req.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
writer.write("request uri: " + requestUri);
Integer code = (Integer) req.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
writer.write("<br>status code: " + code);
String errorMessage = (String) req.getAttribute(RequestDispatcher.ERROR_MESSAGE);
writer.write("<br>error message: " + errorMessage);
writer.write("<br>Response from "+this.getClass());
}
}
5)、MyApplication
package com.ebc; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication
@ServletComponentScan
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
} }
3、internal-error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>Error on server side</h3>
<p>
<%= request.getAttribute("javax.servlet.error.exception") %>
</p>
<p>From jsp page.</p>
</body>
</html>
4、pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
5、执行
springboot - 在servlet中映射Errors 脱离spring mvc的更多相关文章
- Spring MVC(一)Servlet 2.x 规范在 Spring MVC 中的应用
Spring MVC(一)Servlet 2.x 规范在 Spring MVC 中的应用 Spring 系列目录(https://www.cnblogs.com/binarylei/p/1019869 ...
- springboot注册到consul中报错:Spring MVC found on classpath, which is incompatible with Spring Cloud
今天在做springboot整合成springCloud并注册到consul中时,发现若注册到consule中成功 则不能启动swagger,且不能提供任何API服务,要是能提供API服务则不能注册到 ...
- 控制层技术:Servlet+reflection、Struts2、Spring MVC三者之间的比较学习
Servlet Struts2 Spring MVC 处理用户提交的数据 基于MVC设计模式的Web应用程序 是一个框架 是MVC框架 导入servlet包,配置web.xml文件 web.xml & ...
- servlet中如何实现通过Spring实现对象的注入
@WebServlet("/BaseServlet")public class BaseServlet extends HttpServlet { private static f ...
- Spring MVC URL的映射问题 ;Spring MVC 跳转与iframe包含地址问题
/login/login.html 进行form提交,登录之后的页面位于/main/frame.jsp; 这样的controller中的地址需要映射成/main/login.do,然后在control ...
- 将前端请求中的数据绑定到Spring MVC响应方法中参数的四种方法
一.映射URL绑定的占位符到方法参数 1.方法 使用@PathVariable注解 2.代码示例 a.接收请求方法 @RequestMapping(value = "/deleteInfo/ ...
- 最近无意中看到一个讲解spring mvc的系列,从源码的角度讲解,特记录下来,供以后反复学习
SpringMVC深度探险(一) —— SpringMVC前传 SpringMVC深度探险(二) —— SpringMVC概览 SpringMVC深度探险(三) —— DispatcherServle ...
- Spring MVC 实现文件的上传和下载
前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:“用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流”.我回复他说:“使用Spring MVC框架可以做到这一点,因为Spri ...
- springboot学习笔记:5.spring mvc(含FreeMarker+layui整合)
Spring Web MVC框架(通常简称为"Spring MVC")是一个富"模型,视图,控制器"的web框架. Spring MVC允许你创建特定的@Con ...
随机推荐
- Java基础 -3.5
我觉得上一篇不是很严谨啊 我认为这个逻辑还是正确的 原码.反码.补码: (1)在Java中,所有数据的表示方式都是以补码形式来表示 如果没有特别的说明,Java 中的数据类型默认为int,int数据类 ...
- Pytorch本人疑问(2)model.train()和model.eval()的区别
我们在训练时如果使用了BN层和Dropout层,我们需要对model进行标识: model.train():在训练时使用BN层和Dropout层,对模型进行更改. model.eval():在评价时将 ...
- Linux centosVMware PHP动态扩展模块
PHP动态扩展模块 /usr/local/php/bin/php -m //查看模块 下面安装一个redis的模块 cd /usr/local/src/ wget https://codeload.g ...
- 计算xx年xx月xx日是星期几
代码: #include <iostream> #include <string> #include <vector> using namespace std; i ...
- linux搭建mysql时ifconfig命令无法使用问题
刚搭建好的Centos 最小安装模式是没有ifconfig命令的.改变步骤:一:使用语句:cd /etc/sysconfig/network-scripts/二:使用语句vi ifcfg-eno167 ...
- CS231n -Assignments 1 Q1 and Q2
前言 最近在youtube 上学习CS231n的课程,并尝试完成Assgnments,收获很多,这里记录下过程和结果以及过程中遇到的问题,我并不是只是完成需要补充的代码段,对于自己不熟悉的没用过的库函 ...
- JS中,跨域调用(本地)另一个项目的方法
IP地址,因为是本地的项目,所以我一开始写的是127.0.0.1...,但不对.应该写本机的IP地址才对!
- Day11 - O - Coin Game HDU - 3951
题目链接 思路:考虑第一个人取的方式: 1.每次能取的次数>= n, 一次取完 first win 2.每次能取1个,n是奇数 first win 3.一次取不完,这种情况下也分2种情况 1)s ...
- Java程序员常用工具类库
有人说当你开始学习Java的时候,你就走上了一条不归路,在Java世界里,包罗万象,从J2SE,J2ME,J2EE三大平台,到J2EE中的13中核心技术,再到Java世界中万紫千红的Framework ...
- 【剑指Offer面试编程题】题目1367:二叉搜索树的后序遍历序列--九度OJ
题目描述: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. 输入: 每个测试案例包括2行: 第一行为1个整数 ...