jsp技术已经不再推荐,现在更加流行前后端分离,即静态html+ rest接口(json格式),具体原因本篇不讨论,本博客只讲html+rest模式。
用spring mvc可以很容易的实现json格式的rest接口,以下是spring老版本的用法,在spring boot中已经自动配置了jackson
//注册一个spring控制层bean
@Controller
public class HelloController {
//配置方法的post请求url
@RequestMapping(value= "/url",method=RequestMethod.POST)
//@ResponseBody是将这个方法的返回值转换成特定格式,默认是json
@ResponseBody
//user用来接收前端请求的相关传参,比如form表单中的参数
public String hello(User user){
return "hello world"; //这个返回值就是前端ajax请求rest的返回值
}
}
//@Controller+@ResponseBody组合,相当于在每个方法都加上@ResponseBody。
@RestController
public class HelloController {
//直接指定Post请求,同样也有@GetMapping
@PostMapping("/url")
//@RequestBody是指请求来的参数是json请求体,以json格式来转换到uer
public String hello(@RequestBody User user){
return "hello world";
}
}
如果要请求上面的rest接口,只需要在请求时指定url为http://localhost:8080/url,请求方法为post,传入相应的参数,上面的方法就会向AJAX请求返回一个字符串"hello world",返回值 也可以是一个java复合类型,@ResponseBody注解会自动将其转换成json格式。