Restful Api CRUD 標準示例 (Swagger2+validator)

atliwen發表於2017-07-03

為什麼要寫這篇貼?

  要寫一個最簡單的CRUD 符合 Restful Api    規範的  一個Controller, 想百度搜尋一下 直接複製拷貝 簡單修改一下 方法內程式碼。

  然而, 搜尋結果讓我無語到家。 沒一個是正在符合 Restful Api 規範的例項。 最無語的是 你呀直接 JSP 頁面了,還說什麼  Restful Api 啊!!!

  為方便以後自己複製拷貝使用,我把自己剛寫的貼出來。

  

Swagger2:
@Configuration
@EnableSwagger2
public class Swagger2
{
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.dj.edi.web"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("EID 使用者 CRUD")
                .description("EID 使用者 CRUD")
                .version("1.0")
                .build();
    }

}
Application:
@SpringBootApplication
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
public class ComEdiOrderUserApplication
{
    public static void main(String[] args) {SpringApplication.run(ComEdiOrderUserApplication.class, args);}

}
UserApiController:

@RestController
@RequestMapping("/v1/user")
public class UserApiController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);

    @Autowired
    private ClientUsersRepository repository;

    @ApiOperation(value = "獲取所有使用者資料")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<List<ClientUsers>> getClientUsersList() {
        try {
            return ResponseEntity.ok(repository.findAll());
        } catch (Exception e) {
            LOGGER.info(" 獲取所有使用者資料異常 " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "獲取使用者資料")
    @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ClientUsers> getClientUsers(@PathVariable String id) {
        try {
            return ResponseEntity.ok(repository.findOne(id));
        } catch (Exception e) {
            LOGGER.info(" 獲取使用者資料  " + id + "  資料異常 " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "建立使用者", notes = "根據User物件建立使用者")
    @ApiImplicitParam(name = "users", value = "使用者詳細實體user", required = true, dataType = "ClientUsers", paramType = "body")
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<ClientUsers> createUser(@Valid @RequestBody ClientUsers users) {
        try {

            users.setId(ObjectId.get().toString());
            return ResponseEntity.ok(repository.save(users));

        } catch (Exception e) {
            LOGGER.info(" 建立使用者  " + users + "  資料異常 " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "更新使用者詳細資訊", notes = "根據url的id來指定更新物件,並根據傳過來的user資訊來更新使用者詳細資訊")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "user", value = "使用者詳細實體user", required = true, dataType = "ClientUsers", paramType = "body")
    })
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public ResponseEntity<ClientUsers> updateUser(@PathVariable("id") String id,@Valid @RequestBody ClientUsers user) {
        try {
            user.setId(id);
            return ResponseEntity.ok(repository.save(user));
        } catch (Exception e) {
            LOGGER.info(" 更新使用者  " + user + "  資料異常 " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "刪除使用者", notes = "根據url的id來指定刪除物件")
    @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteUser(@PathVariable String id) {
        try {
            repository.delete(id);
            return ResponseEntity.ok("ok");
        } catch (Exception e) {
            LOGGER.info(" 刪除使用者  " + id + "  資料異常 " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }
}

ClientUsersRepository:
@Component
public interface ClientUsersRepository extends MongoRepository<ClientUsers, String>
{
    ClientUsers findByips(String ip);
    ClientUsers findByclientFlag(String clientFlag);
}
ClientUsers:
@Data
public class ClientUsers implements Serializable
{

    @Id
    private String id;

    /**
     * 使用者名稱稱
     */
    @NotBlank(message = "使用者名稱稱 不能為空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")
    private String userName;

    /**
     * ip
     */
    @NotNull(message = "ip 至少需要個")
    private List<String> ips;

    /**
     * 標識
     */
    @NotBlank(message = " 標識 不能為空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")
    private String clientFlag;

    /**
     * 客戶服務ID
     */
    @NotBlank(message = "客戶服務ID 不能為空")
    @Pattern(regexp = "^(?!string)",message = "不能是 stirng")
    private String checkID;
}

 

有哪裡不好的希望指正
 

 

相關文章