Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupported...

@Controller 注解类中,方法使用 @RequestBody 注解接收表单提交的参数抛出异常。

    @PostMapping(value = "/user/search")
    public ModelAndView searchUser(@RequestBody UserQueryDTO queryDTO) {
        log.info("Search User Request : {}", queryDTO);
        if (queryDTO == null) throw new RequestParamException();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/list");
        Page<UserDTO> dataPage = userServiceImpl.searchUser(queryDTO, 0, 10);    
        modelAndView.addObject("queryDTO", queryDTO);
        modelAndView.addObject("dataPage", dataPage);
        return modelAndView;
    }

服务器抛出如下异常:

2018-10-10 11:04:58.203  WARN 3092 --- [nio-8081-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 

界面显示异常:

There was an unexpected error (type=Unsupported Media Type, status=415).
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 

原来 @RequestBody 注解常用来处理 content-type 是 application/json 编码的内容,而不能用来处理 application/x-www-form-urlcoded 编码的内容。这里可以选择不添加注解或者使用 @ModelAttribute 注解代替两种解决方式。

    @PostMapping(value = "/user/search")
    public ModelAndView searchUser(UserQueryDTO queryDTO) {
    }

或者

    @PostMapping(value = "/user/search")
    public ModelAndView searchUser(@ModelAttribute UserQueryDTO queryDTO) {
    }

参考文章:

stackoverflow : Resolved exception caused by Handler execution

你可能感兴趣的:(springboot)