import java.io.File;
import java.io.IOException;
import javax.servlet.Servlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.valves.ErrorReportValve;
import org.apache.coyote.UpgradeProtocol;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.embedded.TomcatWebServerFactoryCustomizer;
import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import com.bc.core.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
@ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class, TomcatWebServerFactoryCustomizer.class })
@Component
@Slf4j
public class TomcatCustomizerBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ConfigurableTomcatWebServerFactory) {
ConfigurableTomcatWebServerFactory configurableTomcatWebServerFactory = (ConfigurableTomcatWebServerFactory) bean;
addTomcat404CodePage(configurableTomcatWebServerFactory);
}
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
private static void addTomcat404CodePage(ConfigurableTomcatWebServerFactory factory) {
factory.addContextCustomizers((context) -> {
String tomcatTempPath = context.getCatalinaBase().getPath();
log.info("tomcat目录:{}", tomcatTempPath);
String path = tomcatTempPath + "/404.html";
ClassPathResource cr = new ClassPathResource("404.html");
if (cr.exists()) {
File file404 = new File(path);
if (!file404.exists()) {
try {
FileCopyUtils.copy(cr.getInputStream(), FileUtil.openOutputStream(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);
});
}
}
上面两种办法,都就可以达到,如果项目访问带项目名,访问任意错误路径(非项目路径下的路径),指向自定义的404页面
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx