- 之前我在學習秒殺項目的時候都是通過postman來測試接口的,並沒有實際去寫頁面,今天我嘗試着試了試thymeleaf+static去寫頁面,但是遇到了很多問題
- 首先簡單介紹一下thymeleaf 的使用(在resources下新建一個templates文件夾存放html頁面);
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
- 做完以上配置後,我們可以寫一個測試看看;首先在templates下寫一個hello.html頁面;
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'hello:'+${name}" ></p>
</body>
</html>
- 然後寫一個controller,如果能夠在頁面正常顯示name:xxc ,那麼完成thymeleaf的入門案例了~
@Controller
@RequestMapping("/test")
public class SampleController extends BaseController{
@RequestMapping("/thymeleaf")
public String thymeleaf(Model model){
model.addAttribute("name","xxc");
return "hello";
}
}
- 接下來是如何使用static靜態資源了,這裏我搞了很久,感覺不懂前端以及很多java配置原理不懂得話會踩很多坑。
spring.resources.add-mappings=true
spring.resources.cache.period=3600
spring.resources.chain.cache=true
spring.resources.chain.enabled=true
spring.resources.chain.compressed=true
spring.resources.chain.html-application-cache=true
spring.resources.static-locations=classpath:/static/
- 重點來了,之前我是看網上秒殺項目使用的是webconfig,在這裏的話我們如果繼承已經被淘汰的WebMvcConfigurerAdapter方法的話是可以直接訪問css/js的
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
}
- 但是既然這個方法已經被淘汰了,那麼我們就最好使用推薦的新方法,WebMvcConfigurationSupport
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/")
;
super.addResourceHandlers(registry);
}
}
- 接下來就是ajax處理後臺返回的json的數據
- 因爲我後臺傳過來的數據是一個字符串{“status”:“sccess”,“data”:“ok”};所以需要先將其轉成json格式;一開始處理不當,總是報錯:Uncaught SyntaxError: Unexpected token o in JSON at position 1;
- 切記我們在使用JSON.parse方法的時候,請先用JSON.stringify方法
$.ajax({
url: "/user/login",
type: "POST",
data:{
telphone:$("#telphone").val(),
password:$("#password").val()
},
success:function(data){
layer.closeAll();
var dataJson = JSON.parse(JSON.stringify(data));
console.log(dataJson);
if(dataJson.status == "success"){
window.location.href="/test/thymeleaf";
}else{
layer.msg(data.msg);
}
},
error:function(){
layer.closeAll();
}
});