1.controller开发步骤
1.定义请求分发
2.接受请求参数
3.处理业务数据
4.绑定数据模型和视图,并返回
2.代码例子
2.1.模型
package com.zyf.springMVC.mvcpara;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1682049189405672046L;
private int id;
private String name;
private int sex;
private String note;
......
}
2.2.模板
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>hello spring mvc vp1</p>
<span>用户名:</span><span th:text="${userModel.name}"></span>
<br/>
<span>用户id:</span><span th:text="${userModel.id}"></span>
</body>
</html>
2.3.controller开发
package com.zyf.springMVC.mvcpara;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/mvcparam") // 1.定义请求分发-1
public class MvcParamController {
@RequestMapping("/vp1") // 1.定义请求分发-2
public ModelAndView mvc1(
@RequestParam int id,// 2.接受请求参数
@RequestParam(value = "name", required = false) String userName) {
ModelAndView modelAndView = new ModelAndView();
// 3.处理业务数据
User user = new User();
user.setId(id);
user.setName(userName == null ? "无名氏" : userName);
// 4.绑定数据模型和视图
modelAndView.addObject("userModel", user);
modelAndView.setViewName("mvcparam/vp1");
return modelAndView;
}
}
- 类和方法上的@RequestMapping组成请求分发。
- @RequestParam int id,浏览器输入地址必须带id,且参数不能为空,否则报错。
- @RequestParam(value = "name", required = false) String userName,浏览器输入地址中参数name不是必须的,且方法内变量使用userName,而不是name。
- 模板中使用模型变量“userModel”要和ModelAndView绑定的Object一致,字段也要一致。
3.测试
访问http://localhost:8080/mvcparam/vp1?id=99&name=zhangsan
github:https://github.com/zhangyangfei/SpringBootLearn.git中的springMVC工程。