2016-09-29 18 views
0

我有一個與mongoDB作爲數據庫的Spring啓動應用程序。只有GET Http請求正在工作。對於所有其他方法,我得到的錯誤代碼404(信息不可用)春季啓動RestController總是得到404錯誤代碼(GET Http請求工作正常,但所有其他結果爲錯誤代碼)

應用程序看起來是這樣的:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class }) 
public class ManagementApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(ManagementApplication.class, args); 
    } 
} 

控制器:

@RestController 
@RequestMapping("/user") 
public class UserController { 

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); 

    @Autowired 
    private UserService userService; 

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public List<User> findAll() { 
     LOGGER.info("Finding all User entries"); 
     return userService.findAllUsers(); 
    } 

    @RequestMapping(value = "{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public User findById(@PathVariable(value = "userId") String userId) { 
     LOGGER.info("Getting the user with the id: " + userId); 
     return userService.findUserWithId(userId); 
    } 

    @RequestMapping(value = "{userId}", method = RequestMethod.DELETE) 
    public void delete(@PathVariable(value = "userId") String userId) { 
     LOGGER.info("Deleting the user with the id: " + userId); 
     userService.deleteUser(userId); 
    } 

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) 
    public User create(@RequestBody @Valid User user, BindingResult result) throws Exception { 
     LOGGER.info("Creating or Updating a user with the following informations: " + user); 
     if (result.hasErrors()) { 
      throw new Exception("Error in request"); 
     } 
     return userService.createOrUpdateUser(user); 
    } 

    @RequestMapping(method = RequestMethod.PUT) 
    public User update(@RequestBody @Valid User user) { 
     LOGGER.info("Updating the user with the following informations: " + user); 
     return userService.createOrUpdateUser(user); 
    } 

    @ExceptionHandler 
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
    public void handleUserNotFound(Exception exception) { 
     LOGGER.info("An Exception occured in controller " + exception.getMessage()); 
    } 

對於除得到我之外的任何其他通話得到以下回應:

"timestamp": "1475149066750", 
    "status": "404", 
    "error": "Not Found", 
    "message": "No message available", 
    "path": "/user" 

請任何人都可以在這幫助我嗎?

+0

您正在使用哪種工具測試GET以外的調用? –

+0

我只是使用其餘的客戶端工具(CocoaRestClient)。結果與捲曲相同 – Wafo

+0

您是否在restclient中設置了合適的標頭 –

回答

0

嘗試削減

value = "/{userId}" 

,而不是

value = "{userId}" 
+0

謝謝,但這並沒有幫助。我只是想知道爲什麼只有Http-GET請求得到執行(findAll和findById方法按預期的方式得到執行),而其他所有方法都沒有執行。 findAll(GET)和create(POST)方法共享相同的url,但通過create方法只是不會執行 – Wafo

+0

您可以試試: @RequestMapping(method = RequestMethod.POST) public ResponseEntity create(@ RequestBody @Valid用戶用戶)拋出異常{ return ResponseEntity.ok(userService.createOrUpdateUser(user)); } –

+0

同樣的結果。最大的問題是該方法甚至不被調用。 – Wafo

0

它改變了你的類了一下:

RestController 
@RequestMapping("/user") 
public class UserController { 


    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public List<String> findAll() { 
     return asList("findAll"); 
    } 

    @RequestMapping(value = "{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public String findById(@PathVariable(value = "userId") String userId) { 
     return "findById"; 
    } 

    @RequestMapping(value = "{userId}", method = RequestMethod.DELETE) 
    public void delete(@PathVariable(value = "userId") String userId) { 
     System.out.println("delete"); 
    } 

    @RequestMapping(method = RequestMethod.POST) 
    public ResponseEntity<?> create(@RequestBody @Valid String user) throws Exception { 
     return ResponseEntity.ok(user); 
    } 

    @RequestMapping(method = RequestMethod.PUT) 
    public String update(@RequestBody @Valid String user) { 
     return "update"; 
    } 

} 

,這是因爲它的測試:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest 
public class UserControllerTest { 

    @Autowired 
    private WebApplicationContext context; 

    private MockMvc mvc; 

    @Autowired 
    private WebApplicationContext wac; 

    private MockMvc mockMvc; 

    protected MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), 
      MediaType.APPLICATION_JSON.getSubtype(), 
      Charset.forName("utf8")); 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
    } 




    @Test 
    public void testFindAll() throws Exception { 
     this.mockMvc.perform(get("/user").contentType(contentType)) 
       .andExpect(status().isOk()); 
    } 

    @Test 
    public void testFindById() throws Exception { 
     this.mockMvc.perform(get("/user/1").contentType(contentType)) 
       .andExpect(status().isOk()); 
    } 

    @Test 
    public void testDelete() throws Exception { 
     this.mockMvc.perform(delete("/user/1").contentType(contentType)) 
       .andExpect(status().isOk()); 
    } 

    @Test 
    public void testCreate() throws Exception { 
     this.mockMvc.perform(post("/user").content("new user").contentType(contentType)) 
       .andExpect(status().isOk()); 
    } 

    @Test 
    public void testUpdate() throws Exception { 
     this.mockMvc.perform(put("/user").content("updated user").contentType(contentType)) 
       .andExpect(status().isOk()); 
    } 
} 

我通過了所有測試。 嘗試玩方法和請求映射的簽名。嘗試在你的ENV

+0

我實現了控制器的單元測試,全部按預期工作。感謝那。問題似乎是GET請求以外的URL訪問(或客戶端)。我真的不明白爲什麼 – Wafo

+0

所以你可以關閉問題 –

0
@Component  
@RestController 
    @RequestMapping(value = {"/user"}) 
    public class UserController { 

     private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); 

     @Autowired 
     private UserService userService; 

     @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
     public List<User> findAll() { 
      LOGGER.info("Finding all User entries"); 
      return userService.findAllUsers(); 
     } 

     @RequestMapping(value = "/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
     public User findById(@PathVariable(value = "userId") String userId) { 
      LOGGER.info("Getting the user with the id: " + userId); 
      return userService.findUserWithId(userId); 
     } 

     @RequestMapping(value = "/{userId}", method = RequestMethod.DELETE) 
     public void delete(@PathVariable(value = "userId") String userId) { 
      LOGGER.info("Deleting the user with the id: " + userId); 
      userService.deleteUser(userId); 
     } 

     @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) 
     public User create(@RequestBody @Valid User user, BindingResult result) throws Exception { 
      LOGGER.info("Creating or Updating a user with the following informations: " + user); 
      if (result.hasErrors()) { 
       throw new Exception("Error in request"); 
      } 
      return userService.createOrUpdateUser(user); 
     } 

     @RequestMapping(method = RequestMethod.PUT) 
     public User update(@RequestBody @Valid User user) { 
      LOGGER.info("Updating the user with the following informations: " + user); 
      return userService.createOrUpdateUser(user); 
     } 

     @ExceptionHandler 
     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 
     public void handleUserNotFound(Exception exception) { 
      LOGGER.info("An Exception occured in controller " + exception.getMessage()); 
     } 

運行測試這應該解決您的問題

+0

這並沒有幫助。從應用程序中找到控制器後,組件註釋不會帶來太多內容。 – Wafo

+0

我只是沒有添加@Component,如果你在RequestMapping中看到你缺少的方法級別/ value =之前,那是定義映射的正確方法。 –

+0

我還在任何'值'之前添加了/符號,但結果相同 – Wafo

-1

我得到它通過設置使用STS一個新的項目工作,複製我的舊代碼粘貼到新的項目。舊代碼是使用Spring-CLI從命令行生成的。如何以及爲什麼會發生這種情況仍然不清楚。非常感謝您的幫助:)

相關問題