如何创建spring restful api

最近在研究spring框架,今天试着写了一个简单的user操作的restful api, 以下是创建的步骤:

1.创建Maven project

可以用IntelliJ IDEA来创建一个Maven project, 然后添加dependency和plugin:



 4.0.0
 com.example
 demo
 0.0.1-SNAPSHOT
 jar
 demo
 Demo project for Spring Boot
 
  org.springframework.boot
  spring-boot-starter-parent
  1.3.6.RELEASE
  
  
 
 
  UTF-8
  UTF-8
  1.8
 
 
  
     org.springframework.boot
     spring-boot-starter
  
  
     org.springframework.boot
     spring-boot-starter-test
     test
  
  
     org.springframework.boot
     spring-boot-starter-web
  
  
     org.springframework.boot
     spring-boot-devtools
     true
  
 
 
  
     
        org.springframework.boot
        spring-boot-maven-plugin
        
           true
        
     
  
 

2.创建project structure

以下是我创建的project结构:

如何创建spring restful api_第1张图片
Paste_Image.png

3.创建类文件

1)User.java

@Component
public class User {    
    private Long id;    
    private String name;    
    private int age;    
    public String getName() {        return name;    }    
    public void setName(String name) {        this.name = name;    }
    public int getAge() {        return age;    }          
    public void setAge(int age) {        this.age = age;    }    
    public Long getId() {        return id;    }    
    public void setId(Long id) {        this.id = id;    }    
}

2)UserController.java

@RestController
@RequestMapping(value = "/users")
public class UserController {    
    static Map userList = Collections.synchronizedMap(new HashMap<>());    

@RequestMapping(value = "/", method = RequestMethod.GET)
public List getUserList(){        
    List users = new ArrayList(userList.values());        
    return users;    
}    
@RequestMapping(value = "/", method = RequestMethod.POST)    
public String postUser(@ModelAttribute User newUser){
    userList.put(newUser.getId(), newUser);   
    return "successful";    
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id){
    return userList.get(id);    
}    
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String putUser(@PathVariable Long id, @ModelAttribute User user){
    User u = userList.get(id);
    u.setName(user.getName());
    u.setAge(user.getAge());
    userList.put(id,u);
    return "successful";    
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@ModelAttribute Long id){
    userList.remove(id);
    return "successful";
  }
}

3)Application.java

这是程序启动的入口

@SpringBootApplicationpublic class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

另外有些童鞋可能对文件的归类不是很明白,可以参考以下这段话:

Spring MVC中往往分为Controller(具体接口,处理相应逻辑),dao(数据库工具类),entity(实体类,对应数据库中的表),service(服务类,调用数据库工具类进行操作),其中Service和Dao部分通常通过接口和继承接口的实体类实现

你可能感兴趣的:(如何创建spring restful api)