@ResponseBody
@RequestMapping(value = "/addStudent",method = RequestMethod.GET)
public String addStudent(Student student){
if (ssi.addStudent(student)) {
return "<script>alert('添加成功');location.href='/sc/list'</script>";
}
return "<script>alert('添加失敗');location.href='addStudent'</script>";
}
運行結果
解決方式 加上 produces 屬性
@ResponseBody
@RequestMapping(value = "/addStudent",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
public String addStudent(Student student){
if (ssi.addStudent(student)) {
return "<script>alert('添加成功');location.href='/sc/list'</script>";
}
return "<script>alert('添加失敗');location.href='addStudent'</script>";
}
produces可能不算一個注解,因為什么呢,它是注解@requestMapping注解里面的屬性項,
它的作用是指定返回值類型,不但可以設置返回值類型還可以設定返回值的字符編碼;
還有一個屬性與其對應,就是consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;
他們的使用方法如下:
一、produces的例子
produces第一種使用,返回json數據,下邊的代碼可以省略produces屬性,因為我們已經使用了注解@responseBody就是返回值是json數據:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
produces第二種使用,返回json數據的字符編碼為utf-8.:
@Controller
@RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
二、consumes的例子( 方法僅處理request Content-Type為“application/json”類型的請求。)
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}