開發前的準備:https://blog.csdn.net/netbar4/article/details/104124914
四、Web開發
1.引入靜態資源
“/**”訪問當前項目的任何資源(靜態資源文件夾)
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”,
去訪問8080/asserts/js/Chart.min.js
歡迎頁:靜態資源文件夾中下index.html;被/**映射
所有的**/favicon.ico都是在靜態資源文件下找
2.模版引擎Thymeleaf
引入Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-Thymeleaf</artifactId>
</dependency>
這樣導入的版本過低,以下辦法修改默認的版本
<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
源代碼:
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
只要把html頁面放在classpath:/templates/,Thymeleaf就能自動渲染
@Controller
public class HelloController {
@RequestMapping("/success")
public String success() {
//classpath:/templates/success.html
return "success";
}
}
classpath:/templates/success.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功了</h1>
</body>
</html>
3.語法規則
1)th:text;改變當前元素裏面的文本內容
見圖
2)表達式
見圖
登錄和攔截器
設置login爲默認頁面
MyMvcConfig:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//添加視圖映射
registry.addViewController("/").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
LoginController:
@Controller
public class LoginController {
//@RequestMapping(value = "/user/login" , method = RequestMethod.POST)
@PostMapping(value = "/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map) {
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
//防止表單重複提交,於是重定向
return "redirect:/main.html";
} else {
map.put("msg", "用戶名密碼錯誤");
return "login";
}
}
}
攔截處理器
LoginHandlerInterceptor類:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null) {
request.setAttribute("msg", "沒有權限請登錄");
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
} else {
return true;
}
註冊攔截
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/static/**","/webjars/**","/login","/asserts/**");
}
公共頁面抽取
57行<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">