文章主要内容:
- get请求
- post请求
- jsonp请求
- 各种请求测试
- 附录(jsonp简介,让属性或对象中属性以我们想要的参数名传给前台)
一.控制层
注意这几个注解:@PathVariable(“”)
@requestParam(value=””,defaultValue=”0”)
- get请求
第一种:不需要从请求路径这获取请求参数
@Autowired
private ItemCatService itemCatService;
@RequestMapping("/list")
@ResponseBody
public List<TreeNode> getItemCatList(@RequestParam(value="id", defaultValue="0")Long parentId) {
List<TreeNode> list = itemCatService.getItemCatList(parentId);
return list;
}
第二种:需要从请求路径获取请求参数
例子1:@PathVariable
@RequestMapping("/{page}")
public String showpage(@PathVariable String page) {
return page;
}
@Autowired
private ItemParamItemService itemParamItemService;
@RequestMapping("/item/{itemId}")
public String showItemParam(@PathVariable Long itemId, Model model) {
String string = itemParamItemService.getItemParamByItemId(itemId);
model.addAttribute("itemParam", string);
return "item";
}
二. post请求
只有一种:不需要从请求路径这获取请求参数
三.jsonp请求
接收页面传递过来的参数。参数就是方法的名称。返回一个json数据,需要把json数据包装成一句js代码。返回一个字符串。
- 参数:回调方法名称
- 返回值:字符串
方法一:
@Controller
public class ItemCatController {
@Autowired
private ItemCatService itemCatService;
@RequestMapping(value="/itemcat/list",
produces=MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
@ResponseBody
public String getItemCatList(String callback) {
CatResult catResult = itemCatService.getItemCatList();
//把pojo转换成字符串
String json = JsonUtils.objectToJson(catResult);
//拼装返回值
String result = callback + "(" + json + ");";
return result;
}
}
方法二.
@RequestMapping("/itemcat/list")
@ResponseBody
public Object getItemCatList(String callback) {
CatResult catResult = itemCatService.getItemCatList();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(catResult);
mappingJacksonValue.setJsonpFunction(callback);
return mappingJacksonValue;
}
四.测试
- 第一种方法:用网页测试(如果是post请求,就需写form,麻烦)
- 第二种:用jar包测试(post请求,不需要写form)
这里已第二种为主:
- 表单的内容:
附录
- jsonp简介:
1))跨域问题:
Js是不能跨域请求。出于安全考虑,js设计时不可以跨域。
2))什么是跨域:
1、域名不同时。
2、域名相同,端口不同。
只有域名相同、端口相同时,才可以访问。
可以使用jsonp解决跨域问题。
3))什么是jsonp?
Jsonp其实就是一个跨域解决方案。Js跨域请求数据是不可以的,但是js跨域请求js脚本是可以的。可以把数据封装成一个js语句,做一个方法的调用。跨域请求js脚本可以得到此脚本。得到js脚本之后会立即执行。可以把数据做为参数传递到方法中。就可以获得数据。从而解决跨域问题。 | |
4))jsonp的原理:
浏览器在js请求中,是允许通过script标签的src跨域请求,可以在请求的结果中添加回调方法名,在请求页面中定义方法,既可获取到跨域请求的数据。 | |
2. 想让属性或对象中属性以我们想要的参数名传给前台(以前是属性名要与前台对应,现在这里属性名不一样,但传过去会一样)
public class CatNode {
@JsonProperty("n")
private String name;
@JsonProperty("u")
private String url;
@JsonProperty("i")
private List<?> item;
}