๋ฌธ์ ์ถ๋ ฅ ๋ฐฉ๋ฒ 4๊ฐ์ง, @ResponseBody
ResourceViewResolver๋ฅผ ์ด์ฉํ ๋ฐฉ๋ฒ, TilesViewResolver๋ฅผ ์ด์ฉํ ๋ฐฉ๋ฒ์ ์์ ์ดํด ๋ณด์์ผ๋ ์ด๋ฒ ํฌ์คํ ์์๋ ์๋ธ๋ฆฟ ๊ฐ์ฒด๋ฅผ ์ป์ด์ ์ถ๋ ฅํ๋ ๋ฐฉ๋ฒ๊ณผ @ResponseBody ์ด๋ ธํ ์ด์ ์ ์ด์ฉํด ์ถ๋ ฅํ๋ ๋ฐฉ๋ฒ์ ์์๋ณด๋๋ก ํ๊ฒ ๋ค.
* ์๋ธ๋ฆฟ ๊ฐ์ฒด(HttpServletResponse)๋ฅผ ์ด์ฉํ์ฌ ์ปจํธ๋กค๋ฌ์์ ์ง์ ๋ฌธ์์ด ์ถ๋ ฅํ๊ธฐ
HttpServletResponse ๊ฐ์ฒด์ getWriter() ํจ์๋ฅผ ํตํด ๋ฌธ์๋ฅผ ์ถ๋ ฅํ ์ ์๋ค. index ํจ์์์ void๋ฅผ ๋ฆฌํดํ๋๋ผ๋(๋ฆฌํด๊ฐ์ด ์์) ๋ฉ์๋ ์์์ ์ง์ ์ถ๋ ฅํ๋ฏ๋ก ์ ์์ ์ผ๋ก ์คํ ์ ํ๋ฉด์ ๋ฌธ์์ด์ด ํฌํจ๋ ๋ฌธ์๊ฐ ๋ฌ๋ค.
HomeController.java
@Controller
@RequestMapping("/")
public class HomeController{
@RequestMapping("index")
public void index(HttpServletResponse response) {
PrintWriter out;
try {
out = response.getWriter();
out.println("Hello Index");
} catch (IOException e) {
e.printStackTrace();
}
}
}
๊ธฐ์กด์ ์๋ธ๋ฆฟ์์ ์ฃผ๋ก ์ฐ๋ ๋ฐฉ๋ฒ๋๋ก HttpServletResponse ๊ฐ์ฒด๋ฅผ ์ป์ด์ getWriter ํจ์๋ฅผ ์ด์ฉํด ์ถ๋ ฅํ ์ ์๋ค. view ํ์ด์ง๊ฐ ๋ฐ๋ก ์๊ณ ์ง์ ์ถ๋ ฅ์ ํด์ผ ํ๋ ์ํฉ์ด๋ฉด ์ด ๋ฐฉ์์ ์จ๋ ์ข์ผ๋, ์คํ๋ง์ ์ด๊ฒ์ ์กฐ๊ธ ๋ ํธ๋ฆฌํ๊ฒ ํ ์ ์๋ ๋ฐฉ์์ ์ ๊ณตํ๋ค.
* @ResponseBody ์ค์ ์ ์ด์ฉํ์ฌ ๋ฌธ์์ด ์ถ๋ ฅํ๊ธฐ
๋ฉ์๋์ ๋ฆฌํด ํ์ ์ String์ผ๋ก ํ๊ณ "Hello Index"๋ฅผ ๋ฆฌํดํ๋ค๋ฉด ์์ ๊ฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ ๊ฒ์ด๋ค. tiles์ ๋ทฐ ๋ฆฌ์กธ๋ฒ๋ฅผ ํตํด ๋ทฐ ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ด 404 ์๋ฌ๊ฐ ๋ฐ์ํ๋ ๊ฒ์ด๋ค.
๊ทธ๋ ๋ค๋ฉด ๋ทฐ ํ์ด์ง๋ฅผ ์ค์ ํ๋ ๊ฒ์ด ์๋๋ผ ๋ฌธ์์ด ์์ฒด๋ฅผ ํ๋ฉด์ ์ถ๋ ฅํ๊ณ ์ถ์ ๋๋ ์ด๋ป๊ฒ ํ ๊น? @ResponseBody ์ด๋ ธํ ์ด์ ์ ์ฌ์ฉํ๋ฉด ๋๋ค.
HomeController.java
@Controller
@RequestMapping("/")
public class HomeController{
@RequestMapping("index")
@ResponseBody
public String index() {
return "Hello Index";
}
}
@ResponseBody๋ tiles, ๋ทฐ ๋ฆฌ์กธ๋ฒ๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ง๊ธ ๋ฆฌํดํ๋ ๊ฒ ์์ฒด๊ฐ ResponseBody์์ ์๋ ค์ฃผ๋ ์ด๋ ธํ ์ด์ ์ด๋ค. ์ด ์ด๋ ธํ ์ด์ ์ด ์๋ค๋ฉด tiles ๋๋ ๋ทฐ ๋ฆฌ์กธ๋ฒ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก .jsp ํ์ผ์ ์ฐพ์์ ๋ฆฌํดํ๊ฒ ๋๋ค.