본문 바로가기
Project

구구단 출력 프로젝트 03 - 컨트롤러(Controller) 만들기

by 보라코끼리 2021. 10. 10.
728x90

1.  만들어둔 모델(Model)인 TimesTableService를 연결한다.

@Autowired
TimesTableService timesTableService;
  • Autowired를 사용하면 Controller에서 새로운 객체를 만들거나 할 필요 없이 사용이 가능하다.

 

2. 브라우저에서 "localhost:8080/" 을 호출하면 home.jsp로 연결한다.

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
	return "home";
}
  • home.jsp로 연결시키기 위해 return 값을 "home"으로 주었다.
    • servlet-context.xml 파일에 ViewResolver로 .jsp가 bean 등록되어있기 때문에 "home"을 리턴할 경우 /WEB-INF/views/home.jsp 를 찾아서 렌더링을 시켜줄 것이다.

 

3.  input 값을 입력하고 버튼을 누르면 create() 메소드를 호출한다.

@ResponseBody
@RequestMapping(value= "/", method = RequestMethod.POST) 
public String create(TimesTable timesTable) {

    int firstMultiplier = 1;

    String[][] table = timesTableService.generateTimesTable(
    timesTable.getFirstTimes(), // 첫 단
    timesTable.getLastTimes(), // 마지막 단
    firstMultiplier, // 첫 번째 곱할 수
    timesTable.getLastMultiplier()); // 마지막 곱할 수

    Gson gson = new Gson();
    String gsonString = gson.toJson(table);

    return gsonString;
}
  • @ResponseBody는 return 에 입력한 값을 view가 아닌 String 형태 그대로 return되도록 해준다.
    • 뷰 화면으로의 리턴이 아닌 데이터를 리턴해주고싶을 때 반드시 사용해야만 하는 애너테이션이다.
  • 뷰(View) 에서 ajax를 호출하여 "/" url의 post 방식 메서드에 inputValue를 주었다.
    • 이를 TimesTable로 받았고 모델(Model)의 메서드 중 generateTimesTable을 호출하여 table 배열을 얻었다.
    • table 데이터를 Gson을 이용하여 json 형태의 문자열로 만들었고 이를 gsonString 변수에 넣어 리턴해주었다.
    • "첫 단"의 값과 "마지막 단", "마지막 곱할 수"의 경우 input 으로 받은 값을 사용하였고 "첫번째 곱할 수"는 1로 고정하기 위해 변수를 선언하여 1로 주었다.
728x90