[개발일지10] @RequestBody를 붙였는데도 컨트롤러가 .html파일을 찾으려고 할 때, map 데이터를 html파일 js에서 꺼내는 방법

김희주·2023년 1월 27일
0

개발일지

목록 보기
8/10
post-thumbnail

1. 문제

1-1. @RequestBody를 붙였는데도 컨트롤러가 .html파일을 찾으려고 함

html 파일에서 ajax로 데이터를 요청해 비동기로 데이터를 받으려고 할 때

  • controller
	@RequestMapping(value="/url", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> method(@RequestBody Map<String, Object> param) throws ParseException {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		//로직 생략
        map.put("date", data);
		//로직 생략
        
	    return map;
    }

와 같은 형식으로 controller를 작성하니까
template might not exist or might not be accessible by any of the configured Template Resolvers
와 같은 error문구가 발생했다. 대충 map이라는 html파일 경로를 못 찾겠다는 뜻.
아니 html 파일이 아니라 Map을 보내겠다는 왜 자꾸 경로를 찾는지...
삽질하다가 겨우 해결했다

1-2. map 데이터를 html파일 js에서 꺼내는 방법

$.ajax({
  url : '/dashboardChartReset',
  method : 'POST',
  data : JSON.stringify({
    "startDt2":startDt2,
    "endDt2":endDt2
  }),
  contentType: 'application/json; charset=utf-8',
  success : function(data){		
    console.log(data);
    console.log(data.get("selectedDayChartColumn"));

을 하니까 data에 있는 arrayList, 즉 배열이 꺼내지지 않았다...

1-3. ajax로 보낸 data를 못 받을 때

  • html
			data : JSON.stringify({
				"startDt2":startDt2,
				"endDt2":endDt2
		}),

이렇게 데이터를 보내고

  • controller
@RequestMapping(value="/url", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> method(String startDt2, String endDt2) throws ParseException {
}

이렇게 받으려고 하면 자꾸 해당 parameter를 찾을 수 없다는 error문구가 떴다.

1-4. POST 작동 자체가 안 될 때

  • WebSecurityConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .csrf().disable();
    }
}

를 만드니까 됐다!

2. 해결

2-1. RequestBody.ok()

	@RequestMapping(value="/url", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> method(@RequestBody Map<String, Object> param) throws ParseException {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		//로직 생략
        map.put("date", data);
		//로직 생략
        
	   return ResponseEntity.ok().body(map);

으로 return타입을 바꾸니까 오류가 없어지고 html단에서 ajax 비동기 호출을 성공해서 map 데이터를 잘 받아왔다!

2-2. map.key

console.log(data.selectedDayChartColumn);

로 하니까 해당 map에 있는 배열이 잘 꺼내졌다!!

2-3. Map<String, Object>으로 받기

    public ResponseEntity<Map<String, Object>> method(@RequestBody Map<String, Object> param) throws ParseException {
}

로 하니까 받아졌다! 넘겨줄 때 json 형식으로 넘겨줬기 때문에 map으로 받아야 하는 걸까...? 이유는 찾아봐야겠다

profile
백엔드 개발자입니다 ☘

0개의 댓글