调用REST控制器方法返回404 null

时间:2018-05-28 16:28:50

标签: java spring rest spring-mvc spring-boot

我想创建Fog架构。我在云和客户端 - 服务器应用程序中有2台服务器,其中服务器是雾服务器。云服务器用于与数据库通信。问题是当我尝试在我的应用程序中进行注册时。我想在验证时检查数据库中是否存在用户。当我调用rest方法时,它返回" 404 null"。

REST控制器,用于检查用户是否存在的方法。当我使用http://localhost:8081/user/test调用此方法时,它返回JSON

{"userID":1,"username":"test","password":"test","events":[]}
  

UserController.java

    @RestController
    public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/user/{username}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserByUsername(@PathVariable("username") String username) {
        User user = userRepository.findByUsername(username);

        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<Void> addUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
        userRepository.save(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getUserID()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }
}

现在我尝试以这种方式在雾服务器中获取该用户:

public boolean sendRequestIfUserExists(String username) {
    CloudServer cloudServer = getAvailableServer();
    if (cloudServer != null) {
        ResponseEntity<User> userEntity = restTemplate.getForEntity(cloudServer.getURI() + "/user/" + username, User.class);
        changeServerStatusToAvailable(cloudServer.getServerName());
        HttpStatus status = userEntity.getStatusCode();
        if (status == HttpStatus.NOT_FOUND) {
            SpeechRecognitionApplication.logger.info("User: " + username + "does not exist");
            return false;
        }
    }

    return true;
}

这一行:

  ResponseEntity<User> userEntity = restTemplate.getForEntity(cloudServer.getURI() + "/user/" + username, User.class);

抛出异常:

org.springframework.web.client.HttpClientErrorException: 404 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:775) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:728) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:684) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:359) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at pl.speechrecognition.services.CloudService.sendRequestIfUserExists(CloudService.java:65) ~[classes/:na]
    at pl.speechrecognition.controller.IndexController.postRegister(IndexController.java:53) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]

修改 最后,我找到了该异常的解决方案。这是因为我在User类中有错误的Contructor。

  

User.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

private Long userID;
private String username;

private String password;
private List<Event> events;

public Long getUserID() {
    return userID;
}

public void setUserID(Long userID) {
    this.userID = userID;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public List<Event> getEvents() {
    return events;
}

public void setEvents(List<Event> events) {
    this.events = events;
}

public User(String username) {
    this.username = username;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}
public String toString() {
    return "Username: " + username;
}


// Missing constructor
public User(Long userID, String username, String password, List<Event> events) {
    this.userID = userID;
    this.username = username;
    this.password = password;
    this.events = events;
}
}

但现在它抛出:

org.springframework.web.client.RestClientException: Error while extracting response for type [class pl.speechrecognition.model.User] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `pl.speechrecognition.model.User` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `pl.speechrecognition.model.User` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 1, column: 2]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:115) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1000) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:983) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]

2 个答案:

答案 0 :(得分:3)

最后我找到了解决方案。构造函数存在问题。当我添加带有所有参数的构造函数时,我发现要反序列化JSON Spring的信息还需要零参数构造函数

答案 1 :(得分:1)

您是否尝试启用日志以查看启动呼叫的确切位置? 尝试添加:logging.level.org.springframework.web = DEBUG 您应该看到完整的网址。

希望这有助于您进一步调试..