spring boot 配置 server.servlet.context-path 后,不带 context-path 访问报 404 错误处理
·
通过以下类对tomcat进行配置
org.apache.catalina.valves.ErrorReportValve
org.apache.catalina.valves.JsonErrorReportValve
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer
org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor
org.springframework.boot.web.server.WebServerFactoryCustomizer
package config;
import org.apache.catalina.valves.ErrorReportValve;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.IOException;
@Configuration
public class TomcatConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Bean
public TomcatContextCustomizer myTomcatContextCustomizer() {
return context -> {
String tomcatTempPath = context.getCatalinaBase().getPath();
logger.info("tomcat目录:{}", tomcatTempPath);
String path = tomcatTempPath + "/404.html";
ClassPathResource cr = new ClassPathResource("static/error/t404.html");
if (cr.exists()) {
File file404 = new File(path);
if (!file404.exists()) {
try {
FileCopyUtils.copy(cr.getFile(), file404);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ErrorReportValve valve = new ErrorReportValve();
valve.setProperty("errorCode.404", path);
valve.setShowServerInfo(false);
valve.setShowReport(false);
valve.setAsyncSupported(true);
context.getParent().getPipeline().addValve(valve);
context.getPipeline().addValve(valve);
};
}
}
参考链接:
https://www.cnblogs.com/nizuimeiabc1/p/12492397.html
https://www.cnblogs.com/rinack/p/11239495.html
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)