牛客社区项目笔记(二)SpringMVC入门

学习http可以在HTTP概述 - HTTP | MDN (mozilla.org)中学习

Get请求

    // GET 请求

    // /student?current=1&limit=20
    @RequestMapping(path = "/students",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@RequestParam(value = "current", required = false,defaultValue = "11") int current,
                             @RequestParam(value = "limit", required = false,defaultValue = "10") int limit){
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

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

两种不同的方式传参,

第一种是/student?  问号传参

第二种是/sutdent/   Restful风格

Get传参会在明面上传,而且长度有限

响应HTML数据

    // 响应HTML数据

    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name","张三");
        modelAndView.addObject("age","30");
        modelAndView.setViewName("/demo/view"); // view 指的是 view.html
        return modelAndView;
    }

    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model){
        model.addAttribute("name","华南理工大学");
        model.addAttribute("age","92");
        return "/demo/view";
    }

响应html数据有两种方式

第一种是new一个ModelAndView对象,将数据传入里面,然后通过setViewName方法跳转页面,然后返回。

第二种是通过Model来传递数据,然后返回页面的路径

响应JSON数据

    // 响应JSON数据 一般会在异步请求(当前网页不刷新,但是后台在访问服务器)
    // JAVA对象 -> JSON字符串 -> JS对象

    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map getEmp(){
        Map emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        return emp;
    }

    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List> getEmps(){
        List> list = new ArrayList<>();
        Map emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 56);
        emp.put("salary", 2000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 90);
        emp.put("salary", 100.00);
        list.add(emp);

        return list;
    }

通过JSON字符串来转化到JS

[{"name":"张三","salary":8000.0,"age":23},
{"name":"李四","salary":2000.0,"age":56},
{"name":"王五","salary":100.0,"age":90}]

其中以List返回的时候,[ ] 括号在外包裹, { }来包含每个Map, 每个键值对用 , 隔开

你可能感兴趣的:(java,springmvc)