[Spring Boot] view 와 controller 사용하기

yihyun·2024년 9월 4일

Spring Boot

목록 보기
3/33

✨ view와 controller 사용하기

전 포스트에서 view는 사용자의 요청을 받아 controller 에 보내고 controller 에서 요청을 처리할 model 에게 요청을 넘겨준다고 했었다.
(간단한 요청은 controller 에서 해결할 수도 있다.)

그렇다면 view에서 특정한 값이 오면 정해진 입력값을 전달하는 controller 을 작성해보자!

📌 적용 예제 1

  • 주소창에 /message 라는 입력값이 들어오면 "Invalid Type" 이라는 문구를 출력하고
  • 파라미터에 greeting가 들어오면 "안녕하세요"
  • 다른 문구가 들어오면 현재 날짜를 출력하는 코드를 작성해보자
    [http://localhost:8080/01_Start] = context 경로
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller 
public class MainController {
	
	@RequestMapping(value="/") 
	public String home() {
		return "home"; 
	}
	
	@RequestMapping("/message")
	public String message(HttpServletRequest req, Model model) { 
		System.out.println("param : " + param);
		Object msg="";
		if (param == null) {
			msg = "Invalid Type";
		} else if(param.equals("greeting")) {
			msg = "안녕하세요";
		} else {
			msg = new Date();
		}
		model.addAttribute("msg", msg);
		return "home";
	}
}

✔ HttpServletRequest, Model, Date()

  • HttpServletRequest : 사용자가 입력한 값을 파라미터로 받기 위해 선언 (요청 객체기 때문에 view로 넘길 수 없다.)
    → 파라미터를 받을 때에는 request가 필요한데 jsp에선 내장객체로 있지만 java에서는 내장하고 있지 않아서 사용해준다.
  • Model : 입력값을 view에 보내기 위해 선언
    → java에서는 Model(인터페이스) 가 forward 역할을 해준다. (특정 페이지로 값을 보내주는 역할)
    → ❗ MVC 패턴에 Model 과는 다른것이다!!!
  • Date() 를 사용하기 위해 변수 msg는 Object 형태로 선언 (더 큰 타입으로 바꾸는 것은 캐스팅 하지 않아도 된다.)
    Date() : 현재 날짜를 반환한다. (java.util 패키지)

→ [http://localhost:8080/01_Start/message?param=greeting] 형태로 주소창에 값을 입력하면 동작한다!


📌 적용 예제 2

  • / 를 넣으면 "홈페이지에 어서오세요"
  • /main 을 넣으면 "메인 페이지에 어서오세요"
  • /index 를 넣으면 "인덱스 페이지에 어서오세요"
    를 출력하는 코드를 작성해보자!
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {
	@RequestMapping(value="/")
	public String home(Model model) {
		model.addAttribute("msg", "홈페이지에 어서오세요"); 
		return "home";
	}

	@RequestMapping(value="/main")
	public String main(Model model) {
		model.addAttribute("msg", "메인 페이지에 어서요세요");
		return "main";
	}
	
	@RequestMapping(value="/index")
	public String index(Model model) {
		String msg="인덱스 페이지에 어서오세요";
		model.addAttribute("msg", msg);
		return "index";
	}
}

📌 사용 예제 3

  • view 에서 숫자와 연산기호를 선택하면 그에 해당하는 값을 출력해주는 코드
  • view의 요청을 controller 에서 수행하기 위해 conrtoller 에서 수행 코드 작성

메인 페이지

<body>
	<h3>계산기 예제</h3>
	<form action="calc" method="post">
		<input type="text" name="su1"/>
		
		<select name="oper">
			<option value="+">+</option>
			<option value="-">-</option>
			<option value="*">*</option>
			<option value="/">/</option>
		</select>
		
		<input type="text" name="su2"/>
		<input type="submit" value="계산요청"/>
	</form>
</body>

결과 출력 페이지

<body>
	<h3>${result}</h3>
	<a href="<c:url value='/'></c:url>">메인으로 돌아가기</a>
</body>

controller

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
	Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value="/") // method를 지정안해두면 get, post를 모두 받는다는 의미
	public String home() {
		logger.info("home.jsp 요청");
		return "home";
	}
	
	@RequestMapping(value="/calc", method = RequestMethod.POST)
	public String calc(Model model, String su1, String su2, String oper) {
		logger.info(su1 + oper + su2);
		int num1 = Integer.parseInt(su1);
		int num2 = Integer.parseInt(su2);
		int result = 0;
		
		switch (oper) {
		case "+": 
			result = num1 + num2;
			break;
		case "-": 
			result = num1 - num2;
			break;
		case "*": 
			result = num1 * num2;
			break;
		case "/": 
			result = num1 / num2;
			break;
		}
		
		model.addAttribute("result", result);
		return "result";
	}
}

✔ Logger, RequestMethod.POST

  • Logger : 콘솔에서 출력값을 볼 수 있도록 해준다. (org.slf4j)
    .info() 는 문자열만 출력할 수 있다.
    → 어느 클래스에서 나온 값인지를 찾을 수 있기 위해 사용
    LoggerFactort : 어떤 클래스를 찍어줄까? (getClass()) : 현재 클래스
    (System.out.println 과 다른점! : syso는 모두 출력하지만 Logger은 에러날 때만 출력하거나 디버그를 위한 출력, 정보를 위한 출력 → .info() 등 출력을 구분해서 하기 위해 사용한다.)

  • RequestMethod.POST : method 를 post 방식만 받겠다는 의미 (get 등 다른 방식도 사용 가능)
    ❗ 이때 맞지 않는 메서드로 요청을 보낼 경우 405 에러 가 발생한다.
    메소드를 작성해준 뒤 작성해야 자동완성이 가능하다.

  • 문자열을 정수로 바꿔주기 위해 Integer.parseInt() 를 사용하고, switch 를 사용해 연산에 따라 값을 반환


❌ 주의

  • jsp 를 건들때는 서버 안끄로 새로고침 해도 괜찮지만
  • java 건드릴 때는 서버를 꼭 꺼야한다.

수정의 우선순위

  • view와 java가 있다면 view를 수정
  • java와 DB가 있다면 java를 수정해주는게 좋다.
profile
개발자가 되어보자

0개의 댓글