首页 > 解决方案 > Springboot:使用 REST 服务发布新对象时出现类型定义错误

问题描述

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

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

来自 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);
        }
    }

标签: javaspringrest

解决方案


这是一个示例HttpServletRequest注入了@RequestBody不需要的内容,因此只需删除该注释即可。

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

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


推荐阅读