package com.exa.de.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @RestController注解,相当于@Controller+@ResponseBody两个注解的结合 * 返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面 */ @RestController @RequestMapping("rest") public class RestFullController { @GetMapping("get")//url://http://localhost:8080/rest/get public String get(){ return "我在这里"; } }

查询数据,没有带参数
@RestController @RequestMapping("rest") public class RestFullController { @GetMapping("get")//url://http://localhost:8080/rest/get public User get(){ User user = new User(1,"lin","男",25); return user; } }
package com.exa.de.entity; public class User { int id; String name; String sex; int age; //===Alt+Insert快捷键 public User() {//无参 } public User(int id, String name, String sex, int age) {//有参 this.id = id; this.name = name; this.sex = sex; this.age = age; } public int getId() {//构造 return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() {//输出 return "User{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } }

查询数据,带来参数
@GetMapping("{id}")//url://http://localhost:8080/rest/id(一个int类型)
public User getById(@PathVariable("id")int id){//URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中。
User user = new User(id,"huang","nv",18);
System.out.println("getById user"+user);
return user;
}

@PostMapping public User addUser(@RequestBody User user){//URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中。 System.out.println(user); return user; }

本文来自博客园,作者:阿霖找BUG,转载请注明原文链接:https://www.cnblogs.com/lin-07/articles/16194575.html
浙公网安备 33010602011771号