SpringBoot-(2)-Web的json接口,靜態網頁,動態頁面
阿新 • • 發佈:2018-11-18
called csharp lis amp app ref dem image dex
一, 了解註解@Controller和@RestController
@Controller:處理Http請求
@RestController:Spring4以後新增註解,相當於@Controller和@ResponseBody
@RequestMapping:url映射配置
二,Json接口開發
使用@RestController即可。該註解如果返回是一個String,就直接返回String給客戶端,如果是對象,會進行Json encode,返回對象json字符串
聲明一個賬戶信息的model
public class Account { private Integer id;private String username; private String password; private String email; private String nicename; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPassword() { return password; }public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; }public void setEmail(String email) { this.email = email; } public String getNicename() { return nicename; } public void setNicename(String nicename) { this.nicename = nicename; } }
創建一個Controller類,通過@RestController註解,創建一個api接口
package com.example.demo.controllers; import com.example.demo.domain.Account; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/getUser") public Account getUser() { Account account = new Account(); account.setUsername("yangzi"); account.setPassword("123456"); return account; } }
調用效果:
三,靜態網頁
SpringBoot靜態網頁還算簡單,直接將html文件放在src.resources.static文件夾下即可,關聯的其他頁面和資源也可以直接放進去,就可以直接訪問
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>LiteMall</title> </head> <body> Welcome to lite mall! <br> <a href="login.html">login</a> </body> </html>
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> login </body> </html>
導入項目static文件夾下:
如果名字是index,可以直接通過域名端口訪問
訪問效果:
四,動態頁面:
動態頁面需要先請求服務器,訪問後臺應用程序,然後再轉向到頁面,比如訪問JSP。spring boot建議不要使用JSP,默認使用Thymeleaf來做動態頁面。
在pom.xml 中添加Thymeleaf組件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
創建html頁面資源
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Products</title>
</head>
<body>
list
</body>
</html>
資源放在項目 templates目錄下,切記。
創建Controller,和動態頁面跳轉接口,接口中直接返回頁面名字
package com.example.demo.controllers; /** * Created by zhang_guang_yang on 2018/11/17. */ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HtmlController { @RequestMapping(value = "/ppt", method = RequestMethod.GET) public String productsList() { System.out.print("productList api called"); return "products"; } }
訪問效果:
SpringBoot-(2)-Web的json接口,靜態網頁,動態頁面