java - 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);
}
}
解决方案
这是一个示例,HttpServletRequest
注入了@RequestBody
不需要的内容,因此只需删除该注释即可。
@PostMapping("/forgot_password")
public ResponseEntity<?> processForgotPassword(HttpServletRequest request) {
// do something
{
表示从 HTTP 请求的@RequestBody
主体构建一个对象,但是HttpServletRequest
是整个 HTTP 请求。导致错误的是不匹配。
推荐阅读
- android - 如何将按钮的位置设置为屏幕上的随机点?
- r - R将用户定义的函数应用于数据框的选定列
- amazon-web-services - 如何从 Spark 作业获取在 AWS Glue 数据目录中注册的表的 S3 密钥(路径)
- javascript - 幕后的 Try-Catch 功能
- linux - 在运行时发送信号(linux)
- bayesian - 如何使用 MCMC 拟合多元正态分布(MHadaptive)
- webrtc - protobufjs 通过 webrtc 数据通道编码的消息
- c# - C# 在线程完成当前函数循环后使用按钮停止线程
- reactjs - 如何仅重新渲染选定的项目和未选定的项目
- reactjs - 下载 .svg 时字体样式消失