如何使用ajax从jsp调用Java控制器方法

时间:2018-10-22 13:35:49

标签: javascript java jquery ajax spring-boot

我已经实现了此问题的不同解决方案,但是我无法从jsp访问控制器方法,而我一直在遵循的某些解决方案

<script type="text/javascript">
var entryId = arguments[0]; 
function callMetod()
    {
   <%!public void clickBtn() {
    ControllerJSP controller = new ControllerJSP();
    controller.likePicture();
    }%>

    }
    </script>

解决方案2是

<script type="text/javascript">
var entryId = arguments[0]; 
function callMetod()
{
    var entryId = arguments[0]
    $.post( "../controllerJSP/LikePicture", {eid: 232 })
    .done(function( data ) {
    alert( "Data Loaded: " + data );
 });
 </script>

我可以实施的解决方案三是

 <script type="text/javascript">
 function callMetod()
 {
      `
         var f={};
                var response = "4292";              
                f.url = "../controllerJSP/LikePicture";
                f.type = "POST";
                f.dataType = "json";
                f.data={eId:entryId};
                f.contentType = "application/json";
                f.success = function (entryId) {
                    console.log(json)

                    alert("success");
                };

                f.error = function (){
                    alert("failed");
                };

                $.ajax(f);
                alert("run")
 }
 </script>

请帮助我解决此问题

1 个答案:

答案 0 :(得分:0)

我会找到一种解决方案,可以从控制器的jsp内调用方法,将注释请求映射并分配一个名称,如下所示,然后在您的ajax url中调用此注释,如下所示

     @RequestMapping("likePicture")
     @ResponseBody
     public void likePicture(@RequestParam("eId") String eId, Map<String, Object>map)
     {
          List<LikeCount> likeCounts = new ArrayList<>();
          likeCounts = dal.getLikeCount(eId);
          SimpleResponseModel srm = new SimpleResponseModel();
          srm = dal.likePicture(eId, "n@n.com");
          dal.updateLikeCount(srm.getMessage(), eId);
          System.out.println(srm.getMessage());
      }

此处显示了ajax方法

    function likeImg(id, votes) 
    {
        var btn = document.getElementById("likeBtn");
        debugger
        $.ajax({

            url : "../likePicture",
            type : "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data : {eId:id, vote:votes},
            success : function(responce) {
                alert("ok")
            }
        });