Spring简单的REST例子

  • 控制器处理 HTTP 的4个主要方法 GET,POST,PUT,DELETE
  • 使用@PathVariable注解获取URL中的参数
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.habuma.spitter.domain.Spittle;
import com.habuma.spitter.service.SpitterService;

@Controller
@RequestMapping("/spittles") //<co id="co_spittlesRequestMapping"/> 
public class SpittleController {
  private SpitterService spitterService;
  
  @Inject
  public SpittleController(SpitterService spitterService) {
    this.spitterService = spitterService;
  }
  
  @RequestMapping(value="/{id}", method=RequestMethod.GET)
//  @ResponseStatus(HttpStatus.CREATED)  HTTP返回状态码
  public String getSpittle(@PathVariable("id") long id,
          Model model) {
    model.addAttribute(spitterService.getSpittleById(id));
    return "spittles/view";
  }
  /**
  * @ResponseBody 把返回结果自动封装成json
  * @RequestBody  把请求到服务器的json自动封装成对象
  */
  @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
  public @ResponseBody  
    Person login(@RequestBody Person person) {  
        return person;  
    }  
}

 参考:

  [1] 《Spring实战》,人民邮电出版社, Craig Walls

posted @ 2017-12-11 14:07  寻找风口的猪  阅读(1202)  评论(0编辑  收藏  举报