▼ Backend/스프링 (Spring)

Spring Boot | return jsonView 사용, JSON 데이터로 응답

Valar 2021. 8. 4. 12:15
반응형

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [jsonView]
template might not exist or might not be accessible by any of the configured Template Resolvers

 

클라이언트에서 요청한 데이터를 JSON(JavaScript Object Notation) 형식으로 리턴할 때

Model 또는 ModelAndView에 데이터를 담아 jsonView로 설정했지만 에러 발생

 

Case1, Case2와 같이 데이터를 jsonView로 리턴 중일 때 발생

 

//Case1
@PostMapping("/login/action.ajax")
public String loginAction(Model model) throws Exception {
	model.addAttribute("code", "code_data");
	return "jsonView";
}

//Case2
@PostMapping("/rewrite/action.ajax")
public ModelAndView rewriteAction() throws Exception {
	ModelAndView mav = new ModelAndView("jsonView");
	mav.addObject("code", "code_data");
	
	return mav;
}

 

# jsonView을 사용하기 위한 설정

@Configuration 사용 시

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Bean
    MappingJackson2JsonView jsonView() {
    	return new MappingJackson2JsonView();
    }
}

 

 

DispatcherServlet 사용 시

 

<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="application/json;charset=UTF-8"> </property>
</bean>

 

 


Error resolving template [/login/action.ajax] template might not exist or might not be accessible by any of the configured Template Resolvers

 

@ResponseBody 어노테이션 추가

 

@PostMapping("/login/action.ajax")
@ResponseBody
public HashMap<String, String> loginAction() throws Exception {
	HashMap<String, String> returnMap = new HashMap<>();
	returnMap.put("code", "code_data");
		
	return returnMap;
}

 

@ResponseBody를 메서드마다 추가하기 번거롭다면

@Controller를 @RestController로 변경한다.

하위의 메서드마다 @ResponseBody가 자동 생성된다.

 

반응형