2017-10-19 107 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);