java spring restful_spring RESTful

1. 可以这么去理解RESTful:其实就是web对外提供的一种基于URL、URI的资源供给服务。不是一个原理性知识点。是一个方法论和规范标准!

2. 利用HTTP的四个方法请求:POST/GET/DELETE/PUT。

完全可以使用RESTful对系统进行增删改查的操作!

3. springREST API:利用spring的几个特点

在接收URL请求的时候,在@RequestMapping里可以用一个变量占位来接收请求的URL值!这个可以使得URL中可以携带一些需要查询的变量值向后台请求。如:http:///user/23u59t4。

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8")

public ResponseEntity deleteUser(@PathVariable Long id)

{

User user = userService.findById(id);

if (user == null)

{

return new ResponseEntity(HttpStatus.NOT_FOUND);

}

userService.deleteUser(id);

return new ResponseEntity(HttpStatus.NO_CONTENT);

}

当然,一定可以解析类似GET请求的表单查询方式的:http:/www.baidu.com?user=23u59t4

如下来自spring官方文档的一个基于spring的java RESTful后台例子:

package hello;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class GreetingController {

private static final String template = "Hello, %s!";

private final AtomicLong counter = new AtomicLong();

@RequestMapping("/greeting")

public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {

return new Greeting(counter.incrementAndGet(),

String.format(template, name));

}

}

其中@RestController的作用(官方文档原文):

This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @ResponseBody rolled together.

意思是,在这个声明一个类为REST controller类,然后这个类里的所有响应方法的response返回都不是view(不需要进行视图解析!)只返回实体数据如:json、xml之类的...

而不像普通的@Controller注解声明的类,它的响应方法需要加上@ResponseBody才能表明这个响应是返回主体!

4. 前端可以使用AJAX发送请求。也可以直接在浏览器的地址栏中加载这个RESTful URL!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值