it-source

Json 객체를 에이잭스에서 스프링 mvc 컨트롤러로 전달하는 방법은 무엇입니까?

criticalcode 2023. 7. 30. 17:54
반응형

Json 객체를 에이잭스에서 스프링 mvc 컨트롤러로 전달하는 방법은 무엇입니까?

저는 SpringMVC에서 일하고 있으며, Ajax에서 컨트롤러로 데이터를 전달하고 있지만 컨트롤러에서 null 값을 받았습니다. 아래 코드를 확인하십시오.

function searchText()
{
   var sendData = {
    "pName" : "bhanu",
     "lName" :"prasad"
   }
  $.ajax({
type: "POST",
 url: "/gDirecotry/ajax/searchUserProfiles.htm,
    async: true,
    data:sendData,
    success :function(result)
    {
    }
 }

내 컨트롤러 코드

         RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)

       public  @ResponseBody String  getSearchUserProfiles(HttpServletRequest request)
       {
         String pName = request.getParameter("pName");
         //here I got null value
       }

아무나 나를 도와주세요

여러분, 다음 코드를 즐겨보세요.

Javascript AJAX 호출

function searchText() {
   var search = {
      "pName" : "bhanu",
      "lName" :"prasad"
   }

   $.ajax({
       type: "POST",
       contentType : 'application/json; charset=utf-8',
       dataType : 'json',
       url: "/gDirecotry/ajax/searchUserProfiles.html",
       data: JSON.stringify(search), // Note it is important
       success :function(result) {
       // do what ever you want with data
       }
   });
}

스프링 컨트롤러 코드

RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)

public  @ResponseBody String  getSearchUserProfiles(@RequestBody Search search, HttpServletRequest request) {
    String pName = search.getPName();
    String lName = search.getLName();

    // your logic next
}

다음 검색 클래스는 다음과 같습니다.

class Search {
    private String pName;
    private String lName;

    // getter and setters for above variables
}

이 클래스의 장점은 향후 필요한 경우 이 클래스에 더 많은 변수를 추가할 수 있다는 것입니다.
예: 정렬 기능을 구현하려는 경우.

Stringifying 없이 JSON을 직접 보낼 수 있는 클래스를 만들지 않으려면 이 방법을 사용합니다.기본 내용 유형을 사용합니다.그냥 사용@RequestParam대신에@RequestBody.@RequestParam이름은 다음과 같아야 합니다.json.

아약스 콜

function searchText() {
    var search = {
    "pName" : "bhanu",
    "lName" :"prasad"
    }
    $.ajax({
    type: "POST",
    /*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
    dataType : 'json',
    url: "/gDirecotry/ajax/searchUserProfiles.htm",
    data: search, // Note it is important without stringifying
    success :function(result) {
    // do what ever you want with data
    }
    });

스프링 컨트롤러

RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)

   public  @ResponseBody String  getSearchUserProfiles(@RequestParam String pName, @RequestParam String lName) {
       String pNameParameter = pName;
       String lNameParameter = lName;

       // your logic next
   }

dataType 옵션을 포함해야 합니다.

dataType: "JSON"

그리고 아래와 같이 컨트롤러에서 폼 데이터를 얻을 수 있습니다.

 public  @ResponseBody String  getSearchUserProfiles(@RequestParam("pName") String pName ,HttpServletRequest request)
       {
         //here I got null value
       } 

하나의 쿼리 문자열 매개 변수에 전체 json을 전달할 수 있다면 서버 측의 rest 템플릿을 사용하여 json에서 Object를 생성할 수 있지만 여전히 최적의 접근 방식은 아닙니다.

u take like this 
var name=$("name").val();
var email=$("email").val();

var obj = 'name='+name+'&email'+email;
  $.ajax({
   url:"simple.form",
   type:"GET",
   data:obj,
   contentType:"application/json",
   success:function(response){
  alert(response);
  },
  error:function(error){
  alert(error);
  }
});

스프링 컨트롤러


@RequestMapping(value = "simple", method = RequestMethod.GET)
public @ResponseBody String emailcheck(@RequestParam("name") String name, @RequestParam("email") String email, HttpSession session) {

    String meaaseg = "success";
    return meaaseg;
}

언급URL : https://stackoverflow.com/questions/20245544/how-to-pass-json-object-from-ajax-to-spring-mvc-controller

반응형