• 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内存管理(二十五):slub 分配器之kmem_cache_destroy
    14:00面试,14:06就出来了,问的问题有点变态。。。
    华为OD技术面试案例3-2024年
    vue相关面试题:MVC,MVP,MVVP三种设计模式的区别
    数据库安全性管理
    【设计模式】六、建造者模式
    golang 泛型详解
    阿里云服务 安装 Docker
    【Linux】锁|死锁|生产者消费者模型
    golang roadrunner中文文档(一)基础介绍
  • 原文地址:https://blog.csdn.net/hanq2016/article/details/133302061