【问题标题】:Springboot: Type definition error when posting a new object using a REST serviceSpringboot:使用 REST 服务发布新对象时出现类型定义错误
【发布时间】:2021-04-14 18:56:07
【问题描述】:

我有一个对象通过 json POST 请求获取参数以在数据库中创建一个新条目,我收到此错误:

"类型定义错误:[简单类型,类 javax.servlet.http.HttpServletRequest];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException:不能 构造javax.servlet.http.HttpServletRequest 的实例(没有 创建者,如默认构造函数,存在):抽象类型要么需要 映射到具体类型,具有自定义反序列化器,或包含 [Source: (PushbackInputStream); 处的其他类型信息\n线: 1、栏目:1]

来自 POST 请求的请求

    {
        "email": "user@gmail.com"
    }

这是控制器

 @PostMapping("/forgot_password")
public ResponseEntity<?> processForgotPassword(@RequestBody HttpServletRequest request, Model model, User user) {
    String email = (String) request.getAttribute(user.getEmail());
    String token = RandomString.make(30);

    try {
        userService.updateResetPasswordToken(token, email);
        String resetPasswordLink = Utility.getSiteURL(request) + "/reset_password?token=" + token;
        sendEmail(email, resetPasswordLink);
        model.addAttribute("message", "We have sent a reset password link to your email. Please check.");

    } catch (ResourceNotFoundException ex) {
        model.addAttribute("error", ex.getMessage());
    } catch (UnsupportedEncodingException | MessagingException e) {
        model.addAttribute("error", "Error while sending email");
    }

    return ResponseEntity.ok("Reset link sent Successfully");
}

服务

public class UserService {

    @Autowired
    private UserRepository userRepository;


    public void updateResetPasswordToken(String token, String email) throws ResourceNotFoundException {
        User user = userRepository.findByEmail(email);
        if (user != null) {
            user.setResetPasswordToken(token);
            userRepository.save(user);
        } else {
            throw new ResourceNotFoundException("Could not find any user with the email " + email);
        }
    }

【问题讨论】:

  • 尝试删除@RequestBody
  • 请注意,您应该几乎从不实际操纵HttpServletR*; Spring 为您处理所有令人讨厌的管道。在您的情况下,您可能应该使用@ModelAttribute String email

标签: java spring rest


【解决方案1】:

这是一个exampleHttpServletRequest 注入了不需要的@RequestBody,所以只需删除该注释即可。

@PostMapping("/forgot_password")
public ResponseEntity<?> processForgotPassword(HttpServletRequest request) {
  // do something
{

@RequestBody 表示从 HTTP 请求的主体构建一个对象,但HttpServletRequest 是整个 HTTP 请求。导致错误的是不匹配。

【讨论】:

  • 错误消失了,但是当我发送请求时,消息为空{ "timestamp": "2021-01-09T05:45:02.475+00:00", "message": null, "details": "uri=/api/user/forgot_password" }
  • 当前响应是spring的默认行为。您应该正确定义您的响应格式。现在我们通常使用@RestController来控制响应格式。如果您还有其他问题,请随时创建一个新问题。如果答案解决了您的问题,请记住将此问题标记为已解决。
  • 不能给更少的点数,需要上午 15 点到 11 点
  • 对spring mvc的东西不熟悉,响应格式问题需要多研究。
  • 您仍然可以将其标记为已解决,upvote 是另一个独特的操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
  • 2018-08-06
  • 1970-01-01
相关资源
最近更新 更多