@MapperScan(basePackages = "com.example")
@SpringBootApplication(scanBasePackages = "com.example")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Component
public static class CustomSevletContainer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
/* html放在src/main/resources/static下 */
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
/* 如果配置文件中也配置了端口号,则已此处的为准 */
container.setPort(8083);
container.setSessionTimeout(1, TimeUnit.MINUTES);
}
}
}
拦截器
public class MyInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class);
private static final ThreadLocal THREAD_LOCAL = new ThreadLocal<>();
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
long startTime = THREAD_LOCAL.get();
long endTime = System.currentTimeMillis();
if (modelAndView == null) {
LOGGER.info("url: {}; 本次请求处理时间: {}", request.getRequestURI(), new Long(endTime - startTime) + "ms");
} else {
LOGGER.info("viewName: {}; 本次请求处理时间: {}", modelAndView.getViewName(), new Long(endTime - startTime) + "ms");
}
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
long startTime = System.currentTimeMillis();
THREAD_LOCAL.set(startTime);
return true;
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
LOGGER.info("URI: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m", request.getRequestURI(),
Runtime.getRuntime().maxMemory() / 1024 / 1024, Runtime.getRuntime().totalMemory() / 1024 / 1024,
Runtime.getRuntime().freeMemory() / 1024 / 1024, (Runtime.getRuntime().maxMemory()
- Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
}
}
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//都是html,放在src/main/resources/templates下
registry.addViewController("/").setViewName("/index");
registry.addViewController("/error").setViewName("/error");
}
}
得到异常信息,用于展示在页面上
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage", exception.getMessage());
return modelAndView;
}
}
springboot不推荐使用jsp,推荐Thymeleaf模版
error页面
<html xmlns:th="http://thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link th:href="@{/bootstrap/css/bootstrap.min.css}" rel="stylesheet" />
<link th:href="@{/bootstrap/css/bootstrap-theme.min.css}"
rel="stylesheet" />
<script type="text/javascript" th:src="@{/jquery-1.9.1.min.js}">script>
<script type="text/javascript"
th:src="@{/bootstrap/js/bootstrap.min.js}">script>
<title>ERRORtitle>
head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" align="center" style="font: bold">THERE
IS AN UNEXPECTED ERROR !h3>
div>
<div class="panel-body">
<span style="color: red; font-size: 20px">Error Message: span> <span
th:text="${errorMessage}">span>
div>
div>
body>
html>
@Controller
@RequestMapping("/mvc")
public class HelloMVC {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloMVC.class);
@RequestMapping("person")
public String person(Model model) {
Person single = new Person("qinwei", 25);
List people = new ArrayList<>();
people.add(new Person("a", 1));
people.add(new Person("b", 2));
people.add(new Person("c", 3));
people.add(new Person("d", 4));
model.addAttribute("singlePerson", single);
model.addAttribute("people", people);
return "html/person";
}
}
person.html
<html xmlns:th="http://thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link th:href="@{/bootstrap/css/bootstrap.min.css}" rel="stylesheet" />
<link th:href="@{/bootstrap/css/bootstrap-theme.min.css}"
rel="stylesheet" />
<script type="text/javascript" th:src="@{/jquery-1.9.1.min.js}">script>
<script type="text/javascript"
th:src="@{/bootstrap/js/bootstrap.min.js}">script>
<title>Persontitle>
head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" align="center">VISIT MODELh3>
div>
<div class="panel-body">
<h4 th:text="${singlePerson.name}" align="center">h4>
div>
div>
<div th:if="${not #lists.isEmpty(people)}">
<div class="panel-primary">
<div class="panel-heading">
<span class="panel-title">LISTspan>
div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" th:each="person:${people}"><span
th:text="${person.name}">span> <span th:text="${person.age}">span>
<button class="btn"
th:onclick="'getName(\''+${person.name}+'\');'">obtain
namebutton>li>
ul>
div>
div>
div>
<script th:inline="javascript">
//在javascript中使用变量需要放在 /*[[]]*/中,否则获取不到
var single = /*[[${singlePerson}]]*/;
alert(single.name + '/' + single.age);
function getName(name) {
alert(name);
}
script>
body>
html>