为什么我不能接收字符串,它是空
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseStatus(value= HttpStatus.OK)
public void save(String str) throws IOException {
System.out.println(str);
}
所有我得到的是空:为什么我不能接收字符串,它是空
你需要告诉Spring从哪里获取str
。
如果你要发送的JSON
{ "str": "sasfasfafa" }
你需要从这个deserialises一类,并与@RequestBody
注释方法的参数。
public class StrEntity {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
public class MyController {
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseStatus(value= HttpStatus.OK)
public void save(@RequestBody StrEntity entity) throws IOException {
System.out.println(entity.getStr());
}
}
如果你只是想发送的JSON文件代替(即sasfasfafa
)的字符串作为请求的身体,你可以这样做:
public class MyController {
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseStatus(value= HttpStatus.OK)
public void save(@RequestBody String str) throws IOException {
System.out.println(str);
}
}
没有办法送JSON { "str": "sasfasfafa" }
为请求主体,并且只有一个字符串作为控制器中的方法参数。
如果我只想得到一个String参数,并通过json接收帖子,我该怎么写代码和json,(对不起,我的英文很差,你能理解我的意思吗?) –
使用@RequestParam
注释来获取参数。
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseStatus(value= HttpStatus.OK)
public void save(@RequestParam(name="str") String str) throws IOException {
System.out.println(str);
}
你的意思是(值= “str”),我sen请求json {“str”:“sasfasfafa”} Httpstatu是400,并且我使用@ RestController,它与@Controller有什么不同? –
我送一个JSON后像{“STR”:“sasfafsfafa”},但它打印空 –
这是一段时间,因为我打了Spring MVC的,但也许你需要在你的方法参数的'RequestBody'注解? http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody – NilsH
非常感谢您,我尝试添加@ RequestBody,但它的打印效果类似于{“str”:“sasfafsfafa”},我只想“sasfafsfafa” –