Home  >  Q&A  >  body text

java - 为什么spring的提交格式有些不一样?

比如后端用的是x-www-form-urlencoded格式的.
js对象是:

{
  "id":1,
  "user":{"id":1}
}

后端正确的接收格式 id=1&user.id=1这的. 而query-string 生成的是id=1&user[id]=1这样的

这样直接用jq的ajax 设置为x-www-form-urlencoded 提交对象生成的是id=1&user[id]=1 所以后端就接收不到了.

所以提交起来挺麻烦的.

x-www-form-urlencodedquery-string 的关系是怎么样的?

怪我咯怪我咯2742 days ago407

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:57:31

    If the format required by the backend must be id=1&user.id=1, then the JSON provided by the frontend should be:

    {
      "id":1,
      "user.id":1
    }
    

    If the front end cannot be changed and must be passed id=1&user[id]=1, then the back end can only adapt to it. I don’t know if Spring MVC supports parameters with square brackets. If it is a Servlet, it is very simple:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String id = Integer.parseInt(req.getParameter("id"));
            String userId = Integer.parseInt(req.getParameter("user[id]"));
        } catch (NullPointerException | NumberFormatException e) {
            // response Bad Request
        }
    }

    reply
    0
  • Cancelreply