文章内容速览
1.Spring MVC
-
服务器端的三层架构:表现层、业务层、数据层
-
MVC的三层架构:Model、View、Controller;MVC是一种设计模式,理念是将复杂的代码分为上述三个层次
-
Spring MVC的核心组件:前端控制器DispatcherServlet
-
浏览器访问服务器流程:
a.浏览器发送请求给服务器,访问Controller b.Controller调用业务层去处理浏览器请求
c.Controller将业务层返回的数据封装到Model里,再传给View
d.View利用Model中的数据生成一个HTML,返回给浏览器
2.Thymeleaf
- 一种模板引擎:用来生成动态的HTML
- 常用语法:标准表达式、判断与循环、模板的布局
3.代码示例
①在resources下的application.properties下对thymeleaf进行配置——关闭模板缓存:
#ServerProperties
server.port=8080
server.servlet.context-path=/community
# ThymeleafProperties
spring.thymeleaf.cache=false
②代码演示:在Spring MVC框架下,如何获得请求对象和响应对象?
@RequestMapping("/http")
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();
}
}
a.了解一些request基本方法
例如getMethod()和getServletPath(),输出如下:
b.了解request的消息头的若干行数据是怎样的
由request.getHeaderNames()获得,输出如下:
c.了解请求体的参数如何获得以及值如何设置的
通过request.getParameter(“code”)返回code对应的值,在网页链接里输入localhost:8080/community/alpha/http?code=123,其中?表示后面是参数,code是参数名,123是参数值,控制台会输出123
d.了解response的基本用法
response.setContentType(“text/html;charset=utf-8”)设置服务器返回给浏览器数据的类型(网页/字符串/图片…),text/html表示返回数据为网页类型的文本。
搜索网址localhost:8080/community/alpha/http,输出牛客网
4.项目中代码示例
第三小节中的代码是用来理解底层逻辑的,这一小节的代码才是项目中会用到的。
①GET请求中的2种传参方式
一是?加上参数名
二是直接把参数编排到路径中
浏览器通过GET请求向服务器传递参数,服务器对于上述的两种参数传入方式,会进行不同的处理,接下来进行详细说明。
第一种:?加上参数名
// /students?current=1&limit=20
@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";
}
输入路径http://localhost:8080/community/alpha/students,运行结果如下:
输入路径http://localhost:8080/community/alpha/students?current=3&limit=50,运行结果如下:
代码理解:
@RequestMapping(path = "/students", method = RequestMethod.GET)
- 查询路径为“/student”
- 使服务器只处理GET请求
@RequestParam(name = "current", required = false, defaultValue = "1") int current,
@RequestParam(name = "limit", required = false, defaultValue = "10") int limit
- 用注解@RequestParam对参数做更详细的说明,例如当路径中不对参数current和limit说明时,默认它们的值为1和10
第二种:直接把参数编排到路径中
// /student/123
@RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
@ResponseBody
public String getStudent(@PathVariable("id") int id) {
System.out.println(id);
return "a student";
}
输入路径http://localhost:8080/community/alpha/student/101,输出结果如下:
代码理解:
@RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
- 查询路径为"/student/{id}"
- 使服务器只处理GET请求
@PathVariable("id") int id
- 利用注解@PathVariable得到路径中的变量值
②POST请求
与GET请求不同,POST请求将数据放在请求体中,而不是URL中。因此,POST请求适用于提交敏感数据或较大数据量的场景。
a.创建带有表单的网页
在resources下的static下创建student.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>增加学生</title>
</head>
<body>
<form method="post" action="/community/alpha/student">
<p>
姓名:<input type="text" name="name">
</p>
<p>
年龄:<input type="text" name="age">
</p>
<p>
年龄:<input type="submit" name="保存">
</p>
</form>
</body>
</html>
b.创建函数接收POST传进的参数
// 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";
}
saveStudent()函数中的参数名和表单中的一致,即name和age,浏览器的参数就会被传进来:
③服务器向浏览器响应HTML数据
-
在templates下新建一个demo目录,再在下面新建一个view.html文件:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p th:text="${name}"></p> <p th:text="${age}"></p> </body> </html>
-
演示服务器向浏览器响应HTML数据的两种方法
方法一:
// 服务器向浏览器响应HTML数据 @RequestMapping(path = "/teacher", method = RequestMethod.GET) public ModelAndView getTeacher() { ModelAndView mav = new ModelAndView(); mav.addObject( "name", "张三"); mav.addObject( "age", 30); mav.setViewName("/demo/view"); return mav; }
step1:新建ModelAndView对象mav,用来存储Model数据 和View数据;
step2:添加动态参数name和age;
step3:设置视图文件的路径"/demo/view"输出结果如下:
方法二:@RequestMapping(path = "/school", method = RequestMethod.GET) public String getSchool(Model model){ model.addAttribute("name", "北京大学"); model.addAttribute("age", 80 ); return "/demo/view"; }
step1:定义Model对象model,用来存储Model数据;
step2:直接返回View值"/demo/view"给DispatcherServlet;输出结果如下:
④服务器向浏览器响应JSON数据
-
返回一个JSON数据
// 响应JSON数据(异步请求) // JAVA对象 -> JSON字符串 -> JS对象 @RequestMapping(path = "/emp", method = RequestMethod.GET) @ResponseBody public Map<String, Object> getEmp(){ Map<String, Object> emp = new HashMap<>(); emp.put("name", "张三"); emp.put("age", 23); emp.put("salary", 8000); return emp; }
输出结果如下:
-
返回一组JSON数据
@RequestMapping(path = "/emps", method = RequestMethod.GET) @ResponseBody public List<Map<String, Object>> getEmps(){ List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> emp = new HashMap<>(); emp.put("name", "张三"); emp.put("age", 23); emp.put("salary", 8000); list.add(emp); emp.put("name", "李四"); emp.put("age", 24); emp.put("salary", 9000); list.add(emp); emp.put("name", "王五"); emp.put("age", 25); emp.put("salary", 10000); list.add(emp); return list; }
输出结果如下: