• servlet如何获取PUT和DELETE请求的参数


    1. servlet为何不能获取PUT和DELETE请求的参数

    Servlet的规范是POST的数据需要转给request.getParameter*()方法,没有规定PUT和DELETE请求也这么做

    The Servlet spec requires form data to be available for HTTP POST but not for HTTP PUT or PATCH requests. This filter intercepts HTTP PUT and PATCH requests where content type is 'application/x-www-form-urlencoded', reads form encoded content from the body of the request, and wraps the ServletRequest in order to make the form data available as request parameters just like it is for HTTP POST requests.

    2. 解决方案

            2-1  前端使用ajax请求时,发送json类型的参数

            2-2  后端使用字符流读取前端传递的参数

    3. 具体的实现

            3-1 前端部分

    1. $(function () {
    2. // 1. 请求参数
    3. let params = {
    4. id: 51,
    5. phone: '17911113333',
    6. userCode: 'barrss',
    7. userName: 'barrss',
    8. address: '不详',
    9. userRole: 1,
    10. gender: 1,
    11. birthday: '1998-10-12',
    12. }
    13. // 2. 使用jQuery的$.ajax()发送put类型请求进行用户修改
    14. $.ajax({
    15. url: 'http://localhost/day81/updateUser',
    16. // 请求类型是put
    17. type: 'put',
    18. dataType: 'json',
    19. // 通过请求头告诉服务端,发送的数据是json类型
    20. contentType: 'application/json',
    21. // 前端必须传递json字符串,否则后端无法解析
    22. data: JSON.stringify(params),
    23. headers: { token: '***.***zAyMjYwfQ.***' },
    24. success(res) {
    25. console.log(res)
    26. },
    27. error(e) {
    28. console.log(e)
    29. },
    30. })
    31. })

            3-2 后端MyUtil工具类中定义方法 getJSONParams

    1. /**
    2. * 获得前端发送的json类型参数
    3. *
    4. * @param req 封装客户端请求信息的对象
    5. * @return 包含请求参数的Map集合
    6. */
    7. public static Map getJSONParams(HttpServletRequest req) throws ServletException, IOException {
    8. // 1. 打开输入流读取客户端写入的json字符串
    9. InputStream in = req.getInputStream();
    10. // 2. 使用BufferedReader包装流,指定字符串
    11. BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    12. String str = null;
    13. StringBuilder builder = new StringBuilder();
    14. // 3. 读取客户端传递的json字符串参数,拼接到StringBuilder中
    15. while ((str = reader.readLine()) != null) {
    16. builder.append(str);
    17. }
    18. String params = builder.toString();
    19. // 4. 去除json字符串中的{}
    20. params = params.substring(1, params.length() - 1);
    21. // 5. 去除json字符串中的 "
    22. params = params.replace("\"", "");
    23. Map map = new HashMap<>();
    24. // 6. 拆分字符串,把key=value键值对, 存放到map中
    25. String[] arr = params.split(",");
    26. for (String item : arr) {
    27. String[] code = item.split(":");
    28. map.put(code[0], code[1]);
    29. }
    30. return map;
    31. }

          3-3 servlet中的doPut方法中使用getJSONParams即可

    1. @Override
    2. protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    3. Map map = MyUtil.getJSONParams(req);
    4. req.setAttribute("params", map);
    5. doPost(req, res);
    6. }

    4. 总结

            使用此种方法获取客户端的put和delete请求方法,要规定客户端必须传递json字符串,后端需要自己开发方法来进行获取,使用起来并不方便,也不灵活。可以考虑使用POST代替PUT或DELETE请求,方便获取参数,不仅安全,而且高效!不妥之处还请指正。

  • 相关阅读:
    【Linux】深入理解进程的优先级(Linux 2.6版本O(1)调度算法)
    Django干货:自定义过滤器和标签
    2022腾讯全球数字生态大会【存储专场】它来了|预约有礼
    寄售抢画字画拍卖-数字藏品竞拍-拍溢价系统古玩文物寄售源码系统
    CocosCreator 面试题(十三)说说Cocos Creator常驻节点
    机器学习-神经网络
    [免费专栏] 车联网基础理论之车联网安全车端知识科普
    Docker部署
    MyBatis源码基础-常用类-Configuration
    Yolov5 + 界面PyQt5 +.exe文件部署运行
  • 原文地址:https://blog.csdn.net/hanq2016/article/details/133302061