本文基于已经会使用SpringMVC,但是未用过Rest风格的前提。
未使用Rest风格的Controller
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/result", method = RequestMethod.GET)
public String resultDisplay(@RequestParam(value = "resultId", required = true) Long resultId, Model model) {
model.addAttribute("hello", "Hello");
model.addAttribute("world", "World");
return "test/resultDisplay";
}
@RequestMapping(value = "/testPage", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public User testPage(@RequestParam(value = "userId") Long userId) {
System.out.println("\n---Nomal---" + userId);
User user = new User();
user.setName("Alex");
user.setAge(1);
return user;
}
}
使用Rest风格后的Controller
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/result/resultId/{resultId}", method = RequestMethod.GET)
public ModelAndView resultDisplay(@PathVariable("resultId") Long testInfoId) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test/resultDisplay");
modelAndView.addObject("hello", "Hello");
modelAndView.addObject("world", "World");
return modelAndView;
}
@RequestMapping(value = "/restTestPage/{userId}", method = RequestMethod.POST)
public User restTestPage(@PathVariable("userId") Long userId) {
System.out.println("\n----Rest----" + userId);
User user = new User();
user.setName("Alex");
user.setAge(1);
return user;
}
}
get请求方式的URL
未使用Rest风格:
http://127.0.0.1:8080/test/result?resultId=7
使用Rest风格后:
http://127.0.0.1:8080/test/result/resultId/7
css与js引入路径问题
webapp目录结构:
|- webapp
| |- css
| | |- bootstrap.css
| |- js
| | |- jquery-2.1.3.min.js
未使用Rest风格时:
<link rel="stylesheet" href="css/bootstrap.css" type="text/css"/>
<script src="js/jquery-2.1.3.min.js"/>
上面引入css与js文件的路径是可以正确引入的。但是使用Rest风格后,就不能正常引入了。
使用Rest风格时:
<link rel="stylesheet" href="/css/bootstrap.css" type="text/css"/>
<script src="/js/jquery-2.1.3.min.js"/>