springboot2.2.x thymeleaf加載static出現的問題,以及ajax處理json的筆記

  • 之前我在學習秒殺項目的時候都是通過postman來測試接口的,並沒有實際去寫頁面,今天我嘗試着試了試thymeleaf+static去寫頁面,但是遇到了很多問題
  1. 首先簡單介紹一下thymeleaf 的使用(在resources下新建一個templates文件夾存放html頁面);
//首先在pom文件中加上以下依賴
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
//因爲我使用的是springboot2.2.2版本,所以如果不做以下操作的話,頁面是跳轉不成功,並且會報404,
//這個需要在<dependencies>外面加
    <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>
//接下來就需要在application.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";
    }
}
  1. 接下來是如何使用static靜態資源了,這裏我搞了很久,感覺不懂前端以及很多java配置原理不懂得話會踩很多坑。
//首先在application.properties下面配置以下信息
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("/static/*/**").addResourceLocations("classpath:/static/");
		//重寫這個方法,映射靜態資源文件
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/resources/")
				.addResourceLocations("classpath:/static/")
		;
		super.addResourceHandlers(registry);
	}
}
  1. 接下來就是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){//這裏是後臺傳回來的data,和上面那個data不一樣
	    	layer.closeAll();
	    	//重點是看這裏,切記我們在使用JSON.parse方法的時候,請先用JSON.stringify方法
			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();
	    }
	});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章