gpt4 book ai didi

json - Spring MVC中HandlerExceptionResolver的resolveException方法如何返回JSON对象?

转载 作者:行者123 更新时间:2023-12-01 11:41:08 28 4
gpt4 key购买 nike

在 Spring MVC 中实现文件 uploader Controller 时,我遇到了一个问题。我的代码快照如下。


@Controller
public class FileUploader extends AbstractBaseController implements HandlerExceptionResolver
{
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public JSONObject handleFileUpload(@RequestParam("file") MultipartFile file)
{
JSONObject returnObj = new JSONObject();
if (file.isEmpty())
{
returnObj.put("success", "false");
returnObj.put("message", "File is empty");
}
else
{
try
{
//my file upload logic goes here
}
catch (Exception e)
{
returnObj.put("success", "false");
returnObj.put("message", "File not uploaded.");
}
}

return returnObj;
}

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception)
{
ModelAndView model = new ModelAndView();
Map map = new HashMap();
if (exception instanceof MaxUploadSizeExceededException)
{
// I want to return JSONObject from here like given below.
/**
* { "message":"File size exceeded", "success":"false" }
* */
map.put("message", "File size exceeded");
map.put("success", "false");
model.addObject(map);
}
return model;
}
}


我的 spring 配置看起来像

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize" value="300000"/>
</bean>

现在在我的 Controller 中,我想在我的 Controller 的 resolveException 方法中返回 JSONObject 而不是 ModelAndView,如代码快照中给出的那样,因为我正在开发一些类似 REST 的方法来上传文件。

有什么想法吗?谢谢

最佳答案

如果你使用上面的Spring 3.2,我推荐这种方式。

  1. 首先,声明ControllerAdvice。

    @Controller
    @ControllerAdvice
    public class JAttachfileApi extends BaseApi
  2. 并使异常处理程序响应如下 JSON 对象。

        @ExceptionHandler(MaxUploadSizeExceededException.class)
    public @ResponseBody Map<String,Object> handleMaxUploadSizeExceededException(
    MaxUploadSizeExceededException ex)
    {

    Map<String,Object> result = getResult();

    JFileUploadJsonResponse errorResult = new JFileUploadJsonResponse();
    errorResult.setError("Maximum upload size of "+ex.getMaxUploadSize()+" bytes exceeded.");
    List<JFileUploadJsonResponse> resultData = new ArrayList<JFileUploadJsonResponse>();
    resultData.add(errorResult);
    result.put("files", resultData);

    return result;
    }

关于json - Spring MVC中HandlerExceptionResolver的resolveException方法如何返回JSON对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20682195/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com