简体   繁体   中英

Couldnt call controller method , ajax call with spring mvc

I have a problem,

using spring mvc , i wanted to use ajax call , tried to call controller method but i couldnt, there is a jsp page and controller class

My Jsp page,

            <form role="form" >

                <div class="form-group">
                    <label for="Ders">Ders</label>
                    <form:select path="derslist" class="form-control" id="ddlders">
                        <form:options items="${derslerlistesi}" itemValue="dersid"
                            itemLabel="ders" />
                    </form:select>
                </div>
                <div class="form-group">

                    <label for="KonuAd">Konu Ad</label> <input type="text"
                        class="form-control" id="KonuAd" placeholder="Konu İsmi Giriniz!">


                </div>
                <div class="form-group">
                    <button type="submit" id="btnekle" class="btn btn-default">Ekle</button>
                </div>

and my controller class

package publisher.controller;


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import publisher.dao.Dao;
import publisher.entity.Dersler;
import publisher.entity.Konular;



@Controller
public class IslemlerController  {

    @Autowired
    private Dao dao;

    @Autowired
    private Konular _konu;

    @RequestMapping(value = "/islemler", method = RequestMethod.GET)
    public String Home(Model model,Dersler dersler)  { 

     model.addAttribute("derslist",dersler);
     return "islemler"; 

    } 


    @ModelAttribute("derslerlistesi")
    public List<Dersler> getdersler ()
    {
        return dao.getAll(Dersler.class);
    }

    @ModelAttribute("konulistesi")
    public List<Konular> getKonular ()
    {
        return dao.getAll(Konular.class);
    }

    @ResponseBody
    @RequestMapping(value="/konukaydet",method=RequestMethod.POST)
    private  Konular KonuKaydet (@RequestParam String konu,@RequestParam int dersid)
    {
        _konu.setKonu(konu);
        _konu.setDersid(dersid);
        _konu.setSinavid(1);
        _konu =  dao.save(_konu);
            System.out.println("kaydet e girdi !");
        return _konu;
    }

}

and my script codes

$(document).ready(function() {
  $("#btnekle").click(function() {
    var input = {
      "konu": $("#KonuAd").val(),
      "dersid": $("#ddlders").val()
    };
    var inputStr = JSON.stringify(input);
    alert(inputStr);
    $.ajax({
      url: "/islemler/konukaydet",
      type: "POST",
      data: inputStr,
      dataType: "json",
      success: function(output) { // callback method for further manipulations
        var str = JSON.stringify(output);
        alert("success ");
        $("#output").text(data);
      },
      error: function(data) { // if error occured
          alert("err");
        $("#error").text(data);
      }
    });

  });
});

thanks for help!

I think you have problem in script, you need to pass data as query parameter because you have used @RequestParam in controller class. so in your ajax call your url should like below.

url: "/islemler/konukaydet?konu="+input.konu+"&dersid="+input.dersid;

Note - you didn't use islemler URL in your controller. @RequestMapping(value="/islemler/konukaydet",method=RequestMethod.POST)

It may help you, if not please reply me.

If you want to use your script as it is, then you need to change in your controller and use @RequestBody and use a model

To add to @Sam's point, according to your url on js, you need to add @RequestMapping at controller level. So your controller should look like:

@RequestMapping(value = "/islemler")
    @Controller public class IslemlerController {

So by combining request mapping at controller level and KonuKaydet method level, you now would have complete desired request mapping.

I am assuming you have configured the controller in dispatcher-servlet.xml

If not see this

If you are running it in local machine then you need to invoke the call as

$.ajax({ //other options. . url: http://localhost:<port>/<your-url> //other options. . }); .

Moreover @RequestMapping should be given at Controller level.

In your @RequestMapping you should map full URL At controller method Or add @RequestMapping at controller level Like :

@Controller
@RequestMapping("/islemler/") 
public class IslemlerController  {

    @Autowired
    private Dao dao;

    @Autowired
    private Konular _konu;

    @RequestMapping(value = "home", method = RequestMethod.GET)
    public String Home(Model model,Dersler dersler)  { 

     model.addAttribute("derslist",dersler);
     return "islemler"; 

    } 


    @ModelAttribute("derslerlistesi")
    public List<Dersler> getdersler ()
    {
        return dao.getAll(Dersler.class);
    }

    @ModelAttribute("konulistesi")
    public List<Konular> getKonular ()
    {
        return dao.getAll(Konular.class);
    }

    @ResponseBody
    @RequestMapping(value="konukaydet",method=RequestMethod.POST)
    private  Konular KonuKaydet (@RequestParam String konu,@RequestParam int dersid)
    {
        _konu.setKonu(konu);
        _konu.setDersid(dersid);
        _konu.setSinavid(1);
        _konu =  dao.save(_konu);
            System.out.println("kaydet e girdi !");
        return _konu;
    }

}

Your ajax Call Should be Like :

$(document).ready(function() {
  $("#btnekle").click(function() {
    var input = {
      "konu": $("#KonuAd").val(),
      "dersid": $("#ddlders").val()
    };
    var inputStr = JSON.stringify(input);
    alert(inputStr);
    $.ajax({
      url: "../islemler/konukaydet",
      type: "POST",
      data: inputStr,
      dataType: "json",
      success: function(output) { // callback method for further manipulations
        var str = JSON.stringify(output);
        alert("success ");
        $("#output").text(data);
      },
      error: function(data) { // if error occured
          alert("err");
        $("#error").text(data);
      }
    });

  });
});

For your Home Method your URL Is like "../islemler/home"

I hope It may help you.

fix the problem ,

Script code

    function madeAjaxCall(){
    var data =  {}
    data["konu"] = $("#konuad").val()
    data["dersid"] = $("#ddlders").val()

 $.ajax({
  type: "post",
//  http://localhost:8080
  url: "/islemler/konukaydet",
  cache: false,    
//  data:'konu=' + $("#konuad").val() + "&dersid;=" + $("#ddlders").val(),
  data:data,
  success: function(response){
   $('#result').html("");
   var obj = JSON.parse(response);
   $('#result').html("First Name:- " + obj.konu +"</br>Last Name:- " + obj.dersid  );
  },
  error: function(){      
   alert('Error while request..');
  }
 });
}

and controller code

@RequestMapping(value="islemler/konukaydet",method=RequestMethod.POST)
private   @ResponseBody  Konular KonuKaydet (HttpServletRequest request, HttpServletResponse response) 
{
    _konu.setKonu(request.getParameter("konu"));
    _konu.setDersid(Integer.parseInt(request.getParameter("dersid")));
    _konu.setSinavid(1);
    _konu =  dao.save(_konu);
        System.out.println("kaydet e girdi !");

    return _konu;
}

so many thanks ... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM