2017-10-19 10 views
0

2つのSpringブートアプリケーションを構築しました.1つはREST API、もう1つはRESTクライアントがRest TemplateとThymeleafでAPIを消費しています。クライアントは基本的に基本的なCRUD機能を実装し、APIを使用していますが、これまではクライアント側でCREATE、READ、DELETEしかできませんでした。 * UPDATEの機能に問題があります: コントローラにはすでにupdate()メソッドがありますが、ビューテンプレートに接続する方法はわかりません。たとえば、編集ボタンを追加するとSpringMVC、ThymeleafおよびRestTemplateの「更新」を実装する方法は?

:それをクリック、リスト上の各「ユーザー」オブジェクトは、それがここに

screeshootは、更新のための私のコントローラコード()である(画像を参照)、「ユーザー」の名前が事前にフォームに私を取る必要があります

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

Restテンプレートを使用してCRUD操作を実行するRestClientクラスを作成しました。

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); 
関連する問題