0%

SpringMVC入门

  • 三层架构
    • 表现层,业务层,数据访问层
  • MVC
    • Model:模型层
    • View:视图层
    • Controller:控制层
  • 核心组件
    • 前端控制器:DispatcherServlet

接受HTTPget请求传参的两种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Controller
@RequestMapping("/alpha")
public class AlphaController{

//方式1
@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";
}

//方式2
@RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
@ResponseBody
public String getStudent(@PathVariable("id") int id){
System.out.println(id);
return "a student";
}
}

接受HTTPpost请求提交数据

1
2
3
4
5
6
7
@RequestMapping(path = "/student", method = RequestMethod.POST)
@ResponseBody
public String saveStudent(String name, int age){
System.out.println(name);
System.out.println(age);
return "success";
}

利用thymeleaf向浏览器显示动态数据

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Teacher</title>
</head>
<body>
<p th:text="${name}"></p>
<p th:text="${age}"></p>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
方式1
@RequestMapping(path = "/teacher", method = RequestMethod.GET)
public ModelAndView getTeacher(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", "张三");
modelAndView.addObject("age", 30);
modelAndView.setViewName("/demo/view");
return modelAndView;
}

方式2
@RequestMapping(path = "/school", method = RequestMethod.GET)
public String getSchool(Model model){
model.addAttribute("name", "寄大学");
model.addAttribute("age", 7);
return "/demo/view";
}

向浏览器返回Json格式数据举例

1
2
3
4
5
6
7
8
9
@RequestMapping(path = "/emp", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getEmp(){
Map<String, Object> emp = new HashMap<>();
emp.put("name", "张三");
emp.put("age", 30);
emp.put("salary", 9000);
return emp;
}
------ THEEND ------

欢迎关注我的其它发布渠道