【Spring】Spring MVC入门
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
Spring MVC
Spring MVC
- 三层架构 表现层、业务层、数据访问层
- MVC
- Model 模型层
- View 视图层
- Controller 控制层
- 核心组件
- 前端控制器 DispatcherServlet
- Web Server (MVC与三层架构的关系
Thymeleaf 模板引擎生成动态 html
- 官网
- 常用语法 标准表达式 、 判断与循环 、模板的布局
Spring MVC 入门示例
配置关闭 Thymeleaf 模板引擎缓存
#关闭 Thymeleaf 的 模板引擎缓存 —— 调试时关闭 上线时打开 spring.thymeleaf.cache=false
偏底层的 接收请求 + 返回响应 的方式
/**
* 主要方法
* request.getMethod() —— 获取请求方法
* request.getServletPath() —— 获取请求的 url
* request.getHeaderNames() —— 获取 请求 的 Header name
* request.getHeader(name) —— 根据 header name 获取 header 值
* request.getParameter("query_name") —— 用于 /xxx?query_name=xxx 的 查询项获取 值
*/
@RequestMapping("/http")
// 不依赖 返回值 借助 Response 对象 直接返回
public void http(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request.getMethod());
System.out.println(request.getServletPath());
Enumeration<String> enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
String value = request.getHeader(name);
System.out.println(name + ": " + value);
}
System.out.println(request.getParameter("code"));
// 返回响应数据
response.setContentType("text/html;charset=utf-8");
try (
PrintWriter writer = response.getWriter();
) {
writer.write("<h1>牛客网</h1>");
} catch (IOException e) {
e.printStackTrace();
}
}
Spring Boot 封装后的 处理方式
GET
-
带查询参数的 url /students?current=1&limit=20
// /students?current=1&limit=20 /** * 注解说明 * @RequestParam() —— 指定 /xxx?query_name=xxx&query_name2=xxx 中 query_name 的属性 * 参数 name 指定 query_name ; * required 表明 该 query_name 是否必须填写 到 url 中 * defaultValue 设置默认值 * GET 请求 查询的 query_name 最好与 其处理方法本例中 getStudents 中的参数名一致 * 可简写为 public String getStudents(int current, int limit) * 这种默认 查询 url 必须是 /students?current=xx&limit=xx 查询参数缺一不可 */ @RequestMapping(path = "/students", method = RequestMethod.GET) @ResponseBody public String getStudents( @RequestParam(name = "current", required = false, defaultValue = "1") int current, @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) { System.out.println(current); System.out.println(limit); return "some students"; }
-
可变 url /student/{id}
// /student/{id} /** * 注解说明 * @PathVariable("xxx") int id —— 参数 id 绑定的是 /student/{id} 中传递过来的 id 值 */ @RequestMapping(path = "/student/{id}", method = RequestMethod.GET) @ResponseBody public String getStudent( @PathVariable("id") int id ) { System.out.println(id); return "a student."; }
POST
// postman 模拟 表单数据项 name 和 age ; url : /alpha/student method: POST
@RequestMapping(path = "/student", method = RequestMethod.POST)
@ResponseBody
public String saveStudent(String name, int age) {
System.out.println(name);
System.out.println(age);
return "success";
}
响应 HTML 数据 、 JSON 数据
不带 @ResponseBody 注解 默认响应 HTML 数据
带 @ResponseBody 注解可返回文本数据 和 JSON 数据等
响应 HTML 数据
ModelAndView 同时包含 Model 和 View 也就是 数据 + 模板 --> HTML 数据
// 写法一 ModelAndView
/**
* modelAndView.addObject() —— 向模板中添加数据
* modelAndView.setViewName() —— 指定模板文件 不需要添加 .html 后缀
* —— 所有模板文件 要位于 templates/ 目录下
*/
@RequestMapping(path = "/teacher", method = RequestMethod.GET)
// 默认 返回 HTML
public ModelAndView getTeacher() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", "张三");
modelAndView.addObject("age", 30);
modelAndView.setViewName("/demo/view"); // 默认 后缀 .html 不用手动加
return modelAndView;
}
<!-- /demo/view.html -->
<!--声明当前 html 是个 模板 模板来自于 https://www.thymeleaf.org-->
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>...</head>
<body>
<p th:text="${name}"></p> <!-- Thymeleaf 模板引擎语法 -->
<p th:text="${age}"></p>
</body>
// 写法二 Thymeleaf 同时持有 Model 和 View 可自行组装大概就是这个意思
@RequestMapping(path = "/school", method = RequestMethod.GET)
public String getSchool(Model model) {
model.addAttribute("name", "北京大学");
model.addAttribute("age", 20);
return "/demo/view";
}
响应 JSON 数据
响应 JSON 数据 异步请求 当前网页 不刷新但后台自己向服务器发送请求获取结果
场景 注册 昵称 不刷新但显示昵称已注册
JAVA 对象 —> JSON 字符串 —> JS 对象
-
{xx:xx, xx:xx}
@RequestMapping(path = "/emp", method = RequestMethod.GET) @ResponseBody // 可返回 JSON public Map<String, Object> getEmp() { Map<String, Object> emp = new HashMap<>(); emp.put("name", "张三"); emp.put("age", 56); emp.put("salary", 67777); return emp; }
-
[{xx:xx, xx:xx}, {xx:xx, xx:xx}, …]
@RequestMapping(path = "/emps", method = RequestMethod.GET) @ResponseBody // 可返回 JSON public List<Map<String, Object>> getEmps() { List<Map<String, Object>> mapList = new ArrayList<>(); Map<String, Object> emp = new HashMap<>(); emp.put("name", "张三"); emp.put("age", 56); emp.put("salary", 67777); mapList.add(emp); emp = new HashMap<>(); emp.put("name", "里斯"); emp.put("age", 33); emp.put("salary", 34666); mapList.add(emp); emp = new HashMap<>(); emp.put("name", "王五"); emp.put("age", 88); emp.put("salary", 23234); mapList.add(emp); return mapList; }