HttpServletRequest和HttpServletResponse

HttpServletRequest和HttpServletResponse

这篇文章很奇怪,并不是这个知识点有多重要,更重要的还是让我自己感受到学习一点东西,先动手搜索再去动手做,不要总是一直在搜,然后迷失在各种各样的讲解中,当感受到迷惑的时候,不如动起手来敲两行代码来的划算。就像我们在做测试的时候,很多问题是在逐渐深入测试的时候才发现的场景,测试用例是无法覆盖所有的测试场景的,只有在动手测试的时候去发散去深入,才能更好的减少bug。废话说的有点多,来,开偷,因为我在一篇博客上看到了一个很好的图。
在这里插入图片描述
HttpServletRequest,request对象时请求对象,在客户端向服务器请求一次就创建一个request对象,并且存储了请求的信息。所以在表单进行提交时,我们可以通过request对象获取用户提交的信息。HttpServletResponse,在Servlet中,当用户发出请求后,接下来就是需要响应,而响应用另一个对象Response对象。

注意:是表单请求

接下来我们实验一下

package com.newcrud.controller;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class MyRequestController {
    @RequestMapping(value = "/my3",method = RequestMethod.POST)
    public void getUserByUserName3(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
        HttpSession session=httpServletRequest.getSession();
        System.out.println(session);
        String name = httpServletRequest.getParameter("username");
        System.out.println(name);
        httpServletRequest.setCharacterEncoding("UTF-8");
        String[] name2 = httpServletRequest.getParameterValues("username");
        System.out.println(Arrays.toString(name2));
        System.out.println(httpServletRequest.getMethod());
        httpServletResponse.setHeader("hello","world");
        httpServletResponse.setStatus(500);
    }
}

使用非表单请求

在这里插入图片描述

再来看一下SpringBoot的日志,并没有获取到传递的参数

org.apache.catalina.session.StandardSessionFacade@797c73ba
null
null
POST

使用表单请求

在这里插入图片描述
再来看一下使用form-data来请求的日志,发现是可以获取到参数的。

org.apache.catalina.session.StandardSessionFacade@797c73ba
zhangsan
[zhangsan]
POST

我的粗略见解

HttpServletRequest类比成@PathVariable、@RequestBody、@RequestParam,都可以用来获取用户请求的参数的。但是却又更强大,比如说防止盗链的功能,后面的三个注解并没有办法完成。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值