Spring mvc-从PostMapping URL返回JSON(Froala编辑器)

时间:2018-03-24 03:48:07

标签: java spring-mvc

<script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.7.6/js/froala_editor.pkgd.min.js"></script>
        <script>
        $(function() {
            $('#edit').froalaEditor({
              // Set the image upload URL.
              imageUploadURL: 'upload_image',
              imageUploadParams: {
                id: 'my_editor'
              }
            })
          });
        </script>

<body>
<textarea id="edit" name="content"></textarea>
</body>

@PostMapping(&#34; / upload_image&#34)     public void process(HttpServletRequest请求,             HttpServletResponse响应)抛出异常{

    Map<Object, Object> responseData = null;

    String linkName = "http://link";

    responseData = new HashMap < Object, Object > ();
    responseData.put("link", linkName);

    // Send response data.
    String jsonResponseData = new Gson().toJson(responseData);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(jsonResponseData);
}

这不会将JSON返回给Froala编辑器。请帮忙。

1 个答案:

答案 0 :(得分:1)

Spring MVC让这很简单。您只需要在方法上使用@ResponseBody注释来指示您将返回将由框架序列化并发送的正文。由于框架执行它,标头和状态设置适当。另外,我删除了未使用的参数并正确设置了Map的类型。

@PostMapping("/upload_image")
@ResponseBody 
public Map<String, String> process() throws Exception{
    Map<String, String> responseData = new HashMap<>();
    String linkName = "http://link";
    responseData.put("link", linkName);

    // Send response data.
    return responseData;
}