Spring MVC 基础

RFC documentation

https://ietf.org https://developer.mozilla.ortg/zh-CN

1 Spring MVC 三层架构

  • 服务端三层架构: 表现层、业务层、数据访问层
  • MVC: 模型层,视图层、控制层

上边两个部分,三者之间不是一一对应的。 控制层负责处理浏览器请求,视图层负责展现,模型层是两者的纽带。

核心组件:Dispatcher Servlet
模板引擎:Thymeleaf(www.thymeleaf.org)倡导自然模板,即以HTML文件为模板,生成动态的HTML,常用语法: 标准表达式、判断与循环、模板布局

application.properties 的介绍

  1. (#)表示注释
  2. 在Spring Boot的官方手册中有示例,可以看到如何设置属性
  3. 实际上这个文件就是在给Bean注入值(给配置类注入数据),用@EnableConfigurationProperties或者@ConfigurationProperties实现

实验中,关掉thymeleaf的缓存(避免延迟),上线时,要开启缓存

2.演示

项目是SpringbootInitailizr自动生成的。
项目结构
defaultTmpMvn

|-- Project
    |-- src
    |   |-- main
    |   |   |-- java
    |   |   |   |-- com
    |   |   |       |-- example
    |   |   |           |-- demo
    |   |   |               |-- DefaultTmpMvnApplication.java
    |   |   |               |-- config
    |   |   |               |   |-- AlphaConfig.java
    |   |   |               |-- controller
    |   |   |               |   |-- MyController.java
    |   |   |               |-- dao
    |   |   |               |   |-- AlphaDao.java
    |   |   |               |   |-- AlphaDaoHibernateImpl.java
    |   |   |               |   |-- AlphaDaoMyBatisImpl.java
    |   |   |               |-- service
    |   |   |                   |-- AlphaService.java
    |   |   |-- resources
    |   |       |-- application.properties
    |   |       |-- static
    |   |       |   |-- html
    |   |       |       |-- student.html
    |   |       |-- templates
    |   |           |-- demo
    |   |               |-- view.html
    |   |-- test
    |       |-- java
    |           |-- com
    |               |-- example
    |                   |-- demo
    |                       |-- DefaultTmpMvnApplicationTests.java

后边介绍的方法添加到MyController.java中,原内容如下

@Controller
@RequestMapping("/my")
public class MyController {

    private String ans = null;
    @Autowired
    private AlphaService alphaService;

    public String getData() {
        return alphaService.find();
    }

    @RequestMapping("/data")
    @ResponseBody
    public String data() {
        return getData();
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }
}

2.1利用HttpServletRequest和HttpServletResponse参数

    @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("name"));
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write("<h1>Function http</h1>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

不用写返回值,可以向浏览器输出任何数据,不依赖返回值
参数自动传入

2.2利用path中的参数

 @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents( int current, int limit) {
        return "Some Students" + current + " " + limit;
    }
    // http://blahblahbah/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 = "20") int limit) {
        return "Some Students" + current + " " + limit;
    }
    
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        return "a student" + id;

    }

其中,下边的方法可以批量指定参数
加与不加@RequestParam,有自动的赋值

2.3Post请求的处理

将静态页面放在resources/static/xxx/xxx.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add student</title>
    <form method="post" action="/my/student">
        <p>
            name: <input type="text" name="name">
        </p>
        <p>
            age: <input type="text" name="age">
        </p>
        <p>
            <input type="submit" value="Add">
        </p>
    </form>
</head>
<body>

</body>
</html>

对应的POST请求处理,自动对应。

    //POST
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age) {
        return "post student" + name + age;
    }

2.4 使用ModelAndView和templates回复HTML

不用@ResponseBody,无参数,返回ModelAndView,在里边设定Model的数据和View的路径

    //Response HTML
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "Tom");
        mav.addObject("age", 30);
        mav.setViewName("/demo/view");
        return mav;
    }

在resources/templates/demo/view.html中

<!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>

2.5 只用Model作为参数,返回View路径

不加@ResponseBody,传入参数是Model,向里边添加数据,返回的是View的路径

    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String school(Model model) {
        model.addAttribute("name", "Stanford");
        model.addAttribute("age", 200);
        return "/demo/view";
    }

2.6回复Json数据

   //Response Json data (async request)
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getemp() {
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "Tom");
        emp.put("age", 30);
        emp.put("salary", 20000);
        return emp;
    }
    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object> > getemps() {
        List<Map<String,Object> > emps = new ArrayList<>();
        Map<String,Object> emp = new HashMap<>();
        emp.put("name", "Tom");
        emp.put("age", 30);
        emp.put("salary", 20000);
        emps.add(emp);
        emp = new HashMap<>();
        emp.put("name", "Jerry");
        emp.put("age", 25);
        emp.put("salary", 8000);
        emps.add(emp);
        emp = new HashMap<>();
        emp.put("name", "Jason");
        emp.put("age", 20);
        emp.put("salary", 40000);
        emps.add(emp);
        return emps;
    }

{“name”:“Tom”,“salary”:20000,“age”:30}
[{“name”:“Tom”,“salary”:20000,“age”:30},{“name”:“Jerry”,“salary”:8000,“age”:25},{“name”:“Jason”,“salary”:40000,“age”:20}]

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐