如何更好地处理@RequestParam(required = true)

时间:2016-05-07 03:05:10

标签: java spring spring-mvc

当在springmvc项目的控制器中时,代码是:

awk 'BEGIN { print "a""b" }'
awk 'BEGIN { print "a"         "b" }'
awk 'BEGIN { s = "b"; print "a"s }'
awk 'BEGIN { s = "b"; print "a"          s }'

在我的浏览器上,我输入@Controller @RequestMapping("/detail") public class FileDetailController { @RequestMapping("/add_detail") @ResponseBody public Object addDetailWithVersionId(@RequestParam(required=true)String versionId, String description) { if(hasVersion(versionId)) { FileDetail fileDetail = new FileDetail(); fileDetail.setId(UUIDUtil.getUUID()); fileDetail.setDescription(description); fileDetail.setVersionId(versionId); // detailService.insert(fileDetail); return JsonUtil.SUCCESS; } return JsonUtil.ERROR; } ,然后收到消息:http://localhost:8080/file_server/detail/add_detail。哦代码HTTP Status 400 - Required String parameter 'versionId' is not present起了作用。但是有没有合适的方法,在这种情况下将json返回到前端?

1 个答案:

答案 0 :(得分:1)

(选项1)如果您想更改返回前端,可以实现自定义org.springframework.boot.autoconfigure.web.ErrorController

例如:

@RestController
public class MyErrorController extends AbstractErrorController {

    private static final String PATH = "/error";

    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping(value = PATH)
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, false);
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

}

你现在总能得到像这样的东西:

{
  "timestamp": 1462600073772,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required String parameter 'versionId' is not present",
  "path": "/add_detail"
}
如果您愿意,

可以随意自定义。只需更改控制器中的错误方法即可。

(选项2)在控制器中使用自定义@ExceptionHandler。可以阅读此内容以获取更多信息https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

只需在FileDetailController

中添加类似内容即可
@Autowired
private ErrorAttributes errorAttributes;

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Map<String, Object>> handle(HttpServletRequest request, Exception exception) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Map body = this.errorAttributes.getErrorAttributes(requestAttributes,false);

    return new ResponseEntity<Map<String, Object>>(body, HttpStatus.BAD_REQUEST);
}