RESTful学习笔记(二)---简单网页前后端springboot项目搭建
新建项目:
项目结构
Pom.xml中添加依赖:
要有用于启动的父进程,有启动依赖,有lombok用于自动构建getter和setter方法等
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>
代码:
User类中
package com.example.demo.demos.web;import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}
}
controller类中
package com.example.demo.Controller;import com.example.demo.demos.web.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.Arrays;
import java.util.List;import static jdk.nashorn.internal.runtime.PropertyDescriptor.GET;@Controller
/*** 员工对外接口(请求路径规定)声明类* 员工控制层*/
public class EmployeeController { @RequestMapping(value= "/employees",method = RequestMethod.GET)@ResponseBodypublic List<User> list(){List<User> list= Arrays.asList(new User(1L,"小七",18),new User(2l,"圆心",19));return list;}
}
启动springboot项目,默认端口号8080
@RequestMapping(value= "/employees",method = RequestMethod.GET)
路径/employees(符号restful风格对于资源名称采用复数形式),GET请求代表获取所有的员工,响应码200响应成功,content-type为Json代表返回的数据是json格式的
请求路径:http://localhost:8080/employees
如下图即前后端连接成功