一, 了解注解@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"; } }
访问效果: