springboot-控制器

后端 / 笔记 / 2021-10-16

什么是控制器

在springboot中控制器controller负责由DispatcherServlet接收并分发过来的请求,把用户请求的数据通过业务处理层封装成一个model,然后再把model返回给对应的view展示。

如何使用

@Controller注解用来标注一个控制器,然后使用@RequestMapping定义URL请求和@Controller方法之间的映射,这样当请求到特定URL,就会执行对应的方法。

常用注解

  • @Controller 标记在类上表示该类是一个控制器
  • @RestController REST风格的控制器
  • @RequestMapping 把请求URL和类方法绑定到一起
    • value : 请求地址
    • method: 请求方式
    • consumes: 消费信息,指定处理请求提交内容类型
    • produces: 生产消息,指定返回内容类型
    • params: 指定request中必须包含某些参数值才能让该方法处理请求
    • headers: 指定request中包含特定header值才能处理该请求
package com.lu.springboot.bootdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

// 表示这是一个控制器
@Controller
// 请求地址映射
@RequestMapping("/api/test")
public class TestController {
    // GET请求方法映射
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
    // post 请求方法映射
    @PostMapping("/post")
    @ResponseBody
    public String postTest(){
        return "post success!";
    }

    // rest 风格API
    @RequestMapping(method = RequestMethod.POST,value = "/restPost")
    @ResponseBody
    public String restPostTest(){
        return "rest api";
    }
}

@PathVariable

将URL请求中,模板变量映射到功能处理方法的参数上获取URL中变量作为参数

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
// restcontroller = controller + responsebody
public class PathVariableTestController {
    @GetMapping("/path/get/{id}")
    public String get(@PathVariable String id){
        return id;
    }
}


除了 RequestMapping
还有

  • @GetMapping 处理GET请求
  • @PostMapping 处理POST请求
  • @DeleteMapping 处理DELETE请求
  • @PutMapping 处理修改请求

处理 HTTP请求的方法

  • GET GET请求
  • POST POST请求
  • DELETE DELETE请求,用于删除资源
  • PUT PUT请求,用于更新数据
  • PATCH 是一个新引入的方法,对PUT方法进行补充,对局部资源进行刷新
  • OPTIONS 用于获取当前URL
  • TRACE 显示服务器请求,用于测试/诊断

处理内容类型

Content-Type

在http请求中,Content-Type用来表示具体请求中媒体类型信息。

  • pc 常用 text/html
  • 手机app 常用 application/json

常见媒体格式

  • text/html html格式
  • text/plain 纯文本格式
  • text/xml XML格式
  • image/gif GIF图片格式
  • image/jpeg JPG图片格式
  • image/png PNG图片格式

application

  • application/xhtml+xml XHTML+XML格式
  • application/xml XML数据格式
  • application/atom+xml ATOM XML聚合格式
  • application/json JSON数据格式
  • application/pdf PDF格式
  • application/msword word文档格式
  • appplication/octet-stream 二进制数据流
  • application/x-www-form-urlencoded 表单时数据编码方式
  • multipart/form-data 表单文件上传

produces 和 consumes

produces

指定返回 Content—Type类型

返回一个JOSN数据

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonTestController {

    @GetMapping(value = "/api/json",produces = "application/json")
    public String test(){
        return "{'name':'jack'}";
    }

}

consumes

consumes是消费者,用于获取消费者数据类型限定请求Content-Type

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonTestController {

    @GetMapping(value = "/api/json",produces = "application/json")
    public String test(){
        return "{'name':'jack'}";
    }

    @GetMapping(value = "/api/json/consume",consumes = "text/plain")
    public String consumes(){
        return "success";
    }

}

方法中使用参数

获取路径中的值

使用 @PathVariable 用来获取路径中的参数。

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
// restcontroller = controller + responsebody
public class PathVariableTestController {
    @GetMapping("/path/get/{id}")
    public String get(@PathVariable String id){
        return id;
    }
}

获取路径中的参数

用来处理get请求参数,只需要get请求中参数名和,和方法参数名一致即可实现捆绑

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetTestController {
    @GetMapping("/get")
    public String get(String username){
        return username;
    }
}

http://localhost:8080/get?username=tom

@ModelAttribute

用于获取 model form url 中参数的值

package com.lu.springboot.bootdemo.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

class UserInfo{
    private String name;
    private String addr;

    public void setName(String name) {
        this.name = name;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "name='" + name + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

@RestController
public class PostTestController {

    // 前端请求转换成bean
    @PostMapping("/post/params")
    public String post(@ModelAttribute UserInfo userInfo){
        return userInfo.toString();
    }

    // 获取 url中参数
    @GetMapping("/get/params")
    public String get(@ModelAttribute("name")String name){
        return name;
    }

}

HttpServletRequest

当然也可以通过 servlet 来处理数据万能

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class HttpServletTestController {

    @GetMapping("/get/servlet")
    public String servletGet(HttpServletRequest req){
        return req.getParameter("name");
    }
}

@RequestParam

用来绑定参数,如果参数不存在会抛出异常

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamTestController {

    @GetMapping("/get/req")
    public String get(@RequestParam String name,@RequestParam Integer age){
        return name+"--"+age.toString();
    }
}

  • required: 强制要求 如果参数不存在则抛出异常

@RequestBody

对于json数据可用 @RequestBody来接收

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class RequestBodyTestController {
    @PostMapping("/json/parse")
    public int jsonParser(@RequestBody List<String>list){
        return list.size();
    }
}

[
    "Jack",
    "Tom",
    "Alice"
]


3

上传文件

上传文件可用 MultipartFile解决

package com.lu.springboot.bootdemo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class MulitPartTestController {
    private static final  String UPLOAD_FILDER = "src/main/resources/file/";
    @PostMapping("/upload/file")
    public String upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) return "file is empty";

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FILDER + file.getOriginalFilename());
            Files.write(path,bytes);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "unknow";
    }
}

小结

  • 路径参数处理
    • @PathVariable
  • get请求参数处理
    • 直接方法参数名字一致
    • @ModelAttribute
    • HttpServletRequest
    • @RequestParam
  • post请求参数处理
    • @ModelAttribute
    • HttpServletRequest
    • @RequestParam
  • json请求处理
    • @RequestBody
  • 文件/图片上传
    • @MultipartFile