赞
踩
1、使用Spring InitialLizr快速搭建一个Spring Boot项目·
2 、新建一个实体类User
-
-
- /**
- * Created by Wsy on 2018-10-23 返回Json数据实体类
- */
- public class User {
- private int id;
- private String username;
- private String password;
-
- 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 int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
- }
3、编写controller类
- package cn.within.controller;
-
- import cn.within.util.User;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * Created by Wsy on 2018-10-23 Json返回数据的Controller
- */
- @RestController
- @RequestMapping("user")
- public class ReturnJsoncontroller {
-
- @RequestMapping("getUser")
- public User getUser(){
- User user = new User();
- user.setId(1);
- user.setUsername("chenwei");
- user.setPassword("1231");
- return user;
- }
- @RequestMapping("getUserList")
- public List<User> getUserList(){
- User user1 = new User();
- user1.setId(1);
- user1.setUsername("chenwei");
- user1.setPassword("123");
- User user2 = new User();
- user2.setId(2);
- user2.setUsername("xiaoyan");
- user2.setPassword("456");
- User user3 = new User();
- user3.setId(3);
- user3.setUsername("doudou");
- user3.setPassword("789");
- List<User> list = new ArrayList<>();
- list.add(user1);
- list.add(user2);
- list.add(user3);
- return list;
-
- }
- @RequestMapping("getUserMap")
- public Map<String,User> getUserMap(){
- User user1 = new User();
- user1.setId(1);
- user1.setUsername("chenwei");
- user1.setPassword("123");
- User user2 = new User();
- user2.setId(2);
- user2.setUsername("wsy");
- user2.setPassword("456");
- User user3 = new User();
- user3.setId(3);
- user3.setUsername("wei");
- user3.setPassword("789");
- Map<String,User> map = new HashMap<>();
- map.put("user1",user1);
- map.put("user2",user2);
- map.put("user3",user3);
- return map;
- }
- }
浏览器输入http://localhost:8080/user/getUser
得出结果:服务器是以json数据格式返回给浏览器
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。