spring boot——请求与参数校验——request获取请求体数据示例

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

代码:

package org.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

@RestController
public class ParamController
{
    @RequestMapping(value = "/test1")                     //获取请求行数据
    public void test1(HttpServletRequest request)
    {
        System.out.println(request.getMethod());   //获取请求方式;

        System.out.println(request.getContextPath());  //获取虚拟目录

        System.out.println(request.getServletPath());  //获取servlet路径

        System.out.println(request.getQueryString());   //获取请求参数

        System.out.println(request.getRequestURI());   //获取请求URI,部分

        System.out.println(request.getRequestURL());   //获取请求URI,全部


    }


    @RequestMapping(value = "/test2")                   //获取请求头方法一
    public void test2(HttpServletRequest request)
    {
        System.out.println(request.getHeader("accept"));



    }


    @RequestMapping(value = "/test3")                   //获取请求头方法二
    public void test3(HttpServletRequest request)
    {

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements())             //读取请求消息头
        {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);

            System.out.println(name + "        "+value);
        }


    }


    @RequestMapping(value = "/test4")                   //获取请求体数据
    public void test4(HttpServletRequest request) throws IOException {

        BufferedReader rd = request.getReader();

        String line = null;

        while ((line = rd.readLine()) != null)
        {
            System.out.println(line);
        }




    }
}

 

posted @ 2023-01-08 15:01  小白龙白龙马  阅读(410)  评论(0编辑  收藏  举报