2016-03-20 12 views
1

私はspring mvc 4を学んでおり、テンプレートエンジンとしてthymeleafを使っています...私は簡単な質問をしています。ユーザは、例えば、同じボタンをクリックすることができる。ajax経由でメソッドを呼び出して可変スプリングを返すmvc 4

html要素は、リクエストマッピングを使用して適切なメソッドを呼び出すhref(ajaxかどうか)を介してサーバーサイドコントローラを呼び出しますが、これらのメソッドはビュー名を表す文字列を返します。しかし、私はビューを返すことを望んでいない、例えば、ユーザーが好きなときに、私はちょうどDBを変更し、ブール値を返すメソッドを呼び出すと、それに基づいて、修正が成功した場合、またはエラーメッセージが表示されない場合はどうすればよいですか?ここでEDIT

は、私のようなボタンがそのように私は、ユーザーのためのDBを更新するなど挿入するかどうかを返すことができ、製品の上にクリックされたときに(ちょうどAJAX要求を提出達成しようとしているかの簡単な例でありますDBが成功したかに)

Thymeleafテンプレート:

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="viewport" 
    content="width=device-width, initialscale=1, maximum-scale=1.0, user-scalable=no" /> 
<title>Home</title> 

<link rel="stylesheet" type="text/css" media="all" 
    th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css}" 
    th:integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" 
    th:crossorigin="anonymous" /> 
<!-- Optional theme --> 
<link rel="stylesheet" type="text/css" media="all" 
    th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css}" 
    th:integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" 
    th:crossorigin="anonymous" /> 
</head> 
<body> 
    <div class="container"> 
     <div class="row"> 
      <div class="col-xs-12"> 
       <table class="table"> 
        <tr> 
         <th>ID</th> 
         <th>Name</th> 
         <th>Description</th> 
        </tr> 
        <tr th:each="prod : ${products}"> 
         <td th:text="${prod.id}">Id</td> 
         <td th:text="${prod.name}">Product Name</td> 
         <td th:text="${prod.desc}">Product Description</td> 
         <td> 
          <div th:id="${prod.id}"> 
           <button id="like-btn">Like</button> 
          </div> 
         </td> 
         <td></td> 
        </tr> 
       </table> 
      </div> 
     </div> 
    </div> 


    <script 
     th:src="@{https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js}"></script> 
    <script th:inline="javascript"> 
    $("#like-btn").click(function() { 
     var divId = $(this).parent().attr('id'); 

     $.ajax({ 
      type: "GET", 
      url: ("http://localhost:9090/like?prodId=" + divId), 
      success: function(){alert("Submit succeeded");}, 
      fail: function(){alert("Submit failed");} 
     }); 
    }); 
    </script> 
</body> 
</html> 

春コントローラー:

@Controller 
public class HomeController 
{ 
    @RequestMapping("/") 
    public String getHomePage() 
    { 
     return "home"; 
    } 

    @RequestMapping("/products") 
    public String getProducts(Model model) 
    { 
     ArrayList<Product> products = new ArrayList<>(); 

     Product p1 = new Product(); 
     p1.setId(1); 
     p1.setName("Product 1"); 
     p1.setDesc("Product 1 Description"); 
     products.add(p1); 

     Product p2 = new Product(); 
     p2.setId(2); 
     p2.setName("Product 2"); 
     p2.setDesc("Product 2 Description"); 
     products.add(p2); 

     model.addAttribute("products", products); 

     return "products"; 
    } 

    @RequestMapping(value="/like", method=RequestMethod.GET) 
    public boolean likePage(@RequestParam("prodId") int productId) 
    { 
     System.out.println("Prod ID: " + productId); 
     //DB insert and modification and return result code, just a sample here 
     //to be processed by jquery 
     //if(insertionSucceeded) 
      return true; 
     //else 
     // return false; 
    } 
} 

しかしもちろん、これはlikeというテンプレートがないというエラーを出します。

+0

これはajaxで行いますか? – Lucky

+0

はい、私はAJAXでそれをしたいです –

+0

@Lucky私はほしいと思うものの簡単な例で質問を編集しました –

答えて

0

あなたは、あなたがあなたのAJAXメソッドのための@ResponseBody注釈とproduces = "application/json"を追加する必要が

$("#like-btn").click(function(){ 
    var prodLikeId = $(this).parent().attr('id'); 
    $.ajax(function(){ 
     type: "GET", 
     dataType: "json", 
     url: "http://localhost:9090/like?prodId="+prodLikeId, 
     success: function(response){ 
      alert("Submit succeeded"+response); 
      if(response===true){ 
       window.alert("Update the HTML"); 
       //update the like button color here 
       $('#like-btn').css('color','blue'); 
      } 
     }, 
     error: function(e){ 
      alert("Submit failed"+e); 
     } 
    }); 
}); 

そして、あなたのコントローラでは、このコードを試すことができ、

@RequestMapping(value="/like", method=RequestMethod.GET,produces = "application/json") 
public @ResponseBody Boolean likePage(@RequestParam("prodId") int productId) 
{ 
    System.out.println("Prod ID: " + productId); 
    //DB insert and modification and return result code, just a sample here 
    //to be processed by jquery 
    //int res = productService.insertProductLike(productId); 
    //if(res>0) 
     return true; 
    //else 
    // return false; 
} 

使用FirebugのAJAXを検査するためのツールのような要求応答データを検証することができます。または、メソッドタイプとしてMap<String,String>を使用して、map.put("success","true");のようにマップを埋めることで応答を返すこともできます。これは、あなたがresponse.successで成功ブロックでこれにアクセスし、それに対応したHTML内のデータを表示したり、更新することができます。このキーと値のペアのJSONレスポンスに基づいて

{"success":"true"} 

、のようなJSON文字列の応答を返します。

+1

thxたくさん..これは素晴らしいですが、今は春のセキュリティに問題があります。 ..しかし、解決策は正しいです、私の問題は残りのコントローラと通常のコントローラの両方のスプリングセキュリティを設定することです。 –

関連する問題