我有一个带有以下控制器的 Spring 应用程序:
@RestController
@RequestMapping("/app")
public class RegisterRestController {
@Autowired
UserRepository userRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
UserService userService;
@RequestMapping( value="/loginuser", method =RequestMethod.POST,produces="application/json")
public String loginUser(@RequestBody String requestBody) {
System.out.println("inside");
JSONObject responseJsonObject = new JSONObject();
String phonenumber;
String password;
try{
JSONObject object = new JSONObject(requestBody);
phonenumber = object.getString("phonenumber");
password = object.getString("password");
User user = userService.findByNumber(phonenumber);
String sha256Password = passwordEncoder.encode(password);
if(sha256Password.equals(user.getPassword())){
responseJsonObject.put("response", "Login Successful");
}
else {
responseJsonObject.put("repsonse", "Login failed");
}
}
catch (Exception e){
e.printStackTrace();
try {
responseJsonObject.put("response", "Invalid Credentials");
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return responseJsonObject.toString();
}
但是,当我从 Postman 发送包含以下内容的 POST 请求时:
{
"phonenumber":"9123456789",
"password":"password"
}
我收到以下回复:
{
"timestamp": 1456043810789,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@eaa3acb; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@eaa3acb; line: 1, column: 1]",
"path": "/app/loginuser"
}
另外,我也在试验 Spring Security。服务器没有显示任何错误,控制器似乎没有收到请求,因为没有打印“内部”。我正在尝试熟悉 Spring,但是我找不到出现这种错误的原因。如果有任何帮助,我将不胜感激。提前致谢
原文由 raptor123 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码中有两个问题:
@RequestBody String requestBody
您正在发送一个具有两个属性的对象:
解决方案:
为您需要登录的值创建一个类:
更改您的控制器方法,使其需要这种类型的对象