Restful 一个简单的Demo

时间:2025-04-21 10:05:30
  • package ;  
  •   
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  •   
  • import ;  
  • import ;  
  •   
  • @RequestMapping("restful/user")  
  • @Controller  
  • public class RestUserController {  
  •   
  •     @Autowired  
  •     private NewUserService newUserService;  
  •   
  •     /** 
  •      * 根据用户id查询用户数据 
  •      *  
  •      * @param id 
  •      * @return 
  •      */  
  •     @RequestMapping(value = "{id}", method = )  
  •     @ResponseBody  
  •     public ResponseEntity<User> queryUserById(@PathVariable("id") Long id) {  
  •         try {  
  •             User user = this.(id);  
  •             if (null == user) {  
  •                 // 资源不存在,响应404  
  •                 return (HttpStatus.NOT_FOUND).body(null);  
  •             }  
  •             // 200  
  •             // return ().body(user);  
  •             return (user);  
  •         } catch (Exception e) {  
  •             ();  
  •         }  
  •         // 500  
  •         return (HttpStatus.INTERNAL_SERVER_ERROR).body(null);  
  •     }  
  •   
  •     /** 
  •      * 新增用户 
  •      *  
  •      * @param user 
  •      * @return 
  •      */  
  •     @RequestMapping(method = )  
  •     public ResponseEntity<Void> saveUser(User user) {  
  •         try {  
  •             this.(user);  
  •             return ().build();  
  •         } catch (Exception e) {  
  •             // TODO Auto-generated catch block  
  •             ();  
  •         }  
  •         // 500  
  •         return (HttpStatus.INTERNAL_SERVER_ERROR).body(null);  
  •     }  
  •   
  •     /** 
  •      * 更新用户资源 
  •      *  
  •      * @param user 
  •      * @return 
  •      */  
  •     @RequestMapping(method = )  
  •     public ResponseEntity<Void> updateUser(User user) {  
  •         try {  
  •             this.(user);  
  •             return (HttpStatus.NO_CONTENT).build();  
  •         } catch (Exception e) {  
  •             ();  
  •         }  
  •         // 500  
  •         return (HttpStatus.INTERNAL_SERVER_ERROR).body(null);  
  •     }  
  •   
  •     /** 
  •      * 删除用户资源 
  •      *  
  •      * @param user 
  •      * @return 
  •      */  
  •     @RequestMapping(method = )  
  •     public ResponseEntity<Void> deleteUser(@RequestParam(value = "id", defaultValue = "0") Long id) {  
  •         try {  
  •             if (() == 0) {  
  •                 // 请求参数有误  
  •                 return (HttpStatus.BAD_REQUEST).build();  
  •             }  
  •             this.(id);  
  •             // 204  
  •             return (HttpStatus.NO_CONTENT).build();  
  •         } catch (Exception e) {  
  •             ();  
  •         }  
  •         // 500  
  •         return (HttpStatus.INTERNAL_SERVER_ERROR).body(null);  
  •     }  
  • }