- 之前我在学习秒杀项目的时候都是通过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();
}
});