2017-10-19 62 views
0

我構建了2個Spring Boot應用程序:一個是REST API,另一個是REST客戶端通過Rest Template和Thymeleaf使用API​​。客戶端基本上實現了基本的CRUD功能並使用API​​,到目前爲止,我只能使用CREATE,READ和DELETE工作客戶端。 *我遇到了問題更新功能: 我已經在控制器上的update()方法,但不知道如何將它連接到視圖模板,例如,如果我添加一個編輯按鈕名單上的每一個「用戶」的對象,點擊它,它應該帶我去預填充的形式與「用戶」的名稱(見圖片)screeshoot如何實現「更新」SpringMVC,Thymeleaf和RestTemplate?

這裏是更新)我的控制器代碼(:

@PutMapping("update") 
public String update(@RequestParam Long id, User user) { 
    restClient.update(id, user); 
    System.out.println("updated"); 
    return "redirect:/users"; 
} 

我創建了RestClient類來使用Rest模板執行CRUD操作:

public class RestClient { 

public final String GET_ALL_URL = "http://localhost:8080/api/all"; 
public final String POST_URL = "http://localhost:8080/api/user"; 
private static final String DEL_N_PUT_URL = "http://localhost:8080/api/"; 


private static RestTemplate restTemplate = new RestTemplate(); 


//get all users 
public List<User> getAllUsers() { 
    return Arrays.stream(restTemplate.getForObject(GET_ALL_URL, User[].class)).collect(Collectors.toList()); 
} 

//create user 
public User postUser(User user) { 
    return restTemplate.postForObject(POST_URL, user, User.class); 
} 

//delete user 
public void delete(Long id){ 
    restTemplate.delete(DEL_N_PUT_URL+id); 
} 

//update user 
public User update(Long id, User user){ 
    return restTemplate.exchange(DEL_N_PUT_URL+id, HttpMethod.PUT, 
      new HttpEntity<>(user), User.class, id).getBody(); 
} 

} 摘錄視圖模板: (我已經有一個 「NEWUSER」 形式做工精細)

<table class="u-full-width"> 
     <thead> 
      <tr> 
       <th>Id</th> 
       <th>Name</th> 
       <th>Delete</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr th:each="user : ${users}"> 
       <td th:text="${user.id}"></td> 
       <td th:text="${user.name}"></td> 
       <td> 
        <form th:method="delete" th:action="@{/}"> 
         <input type="hidden" name="id" th:value="${user.id}" /> 
         <button type="submit">Delete</button> 
        </form> 
       </td> 
      </tr> 
     </tbody> 
    </table> 

client project GITHUB

回答

0

可以直接調用RestTemplate喜歡的PUT方法..

UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url) 
    // Add query parameter 
    .queryParam("id",id); 

RestTemplate restTemplate = new RestTemplate(); 
restTemplate.put(builder.toUriString(), user); 
相關問題