Jeecg 实现RESTful风格
生活随笔
收集整理的這篇文章主要介紹了
Jeecg 实现RESTful风格
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package org.jeecgframework.web.rest.controller;import java.net.URI;/*** TSUser的Restful API的Controller.* * @author liuht*/
@Controller
@RequestMapping(value = "/user")
public class UserRestController {@Autowiredprivate UserService userService;@Autowiredprivate Validator validator;/*** 訪問地址:http://localhost:8080/jeecg/rest/user* @return*/@RequestMapping(method = RequestMethod.GET)@ResponseBodypublic List<TSUser> list() {List<TSUser> listUsers=userService.getList(TSUser.class);return listUsers;}/*** 訪問地址:http://localhost:8080/jeecg/rest/user/{id}* @param id* @return*/@RequestMapping(value = "/{id}", method = RequestMethod.GET)@ResponseBodypublic ResponseEntity<?> get(@PathVariable("id") String id) {TSUser task = userService.get(TSUser.class, id);if (task == null) {return new ResponseEntity(HttpStatus.NOT_FOUND);}return new ResponseEntity(task, HttpStatus.OK);}@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic ResponseEntity<?> create(@RequestBody TSUser user, UriComponentsBuilder uriBuilder) {//調用JSR303 Bean Validator進行校驗,如果出錯返回含400錯誤碼及json格式的錯誤信息.Set<ConstraintViolation<TSUser>> failures = validator.validate(user);if (!failures.isEmpty()) {return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);}//保存用戶userService.save(user);//按照Restful風格約定,創建指向新任務的url, 也可以直接返回id或對象.String id = user.getId();URI uri = uriBuilder.path("/rest/user/" + id).build().toUri();HttpHeaders headers = new HttpHeaders();headers.setLocation(uri);return new ResponseEntity(headers, HttpStatus.CREATED);}@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> update(@RequestBody TSUser user) {//調用JSR303 Bean Validator進行校驗,如果出錯返回含400錯誤碼及json格式的錯誤信息.Set<ConstraintViolation<TSUser>> failures = validator.validate(user);if (!failures.isEmpty()) {return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);}//保存userService.saveOrUpdate(user);//按Restful約定,返回204狀態碼, 無內容. 也可以返回200狀態碼.return new ResponseEntity(HttpStatus.NO_CONTENT);}@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)@ResponseStatus(HttpStatus.NO_CONTENT)public void delete(@PathVariable("id") String id) {userService.deleteEntityById(TSUser.class, id);}
}
總結
以上是生活随笔為你收集整理的Jeecg 实现RESTful风格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 坐在马桶上看算法:Dijkstra最短路
- 下一篇: 小程序开发入门基础篇-张代浩-专题视频课