본문 바로가기
프로그래밍/Spring

Spring Controller

by 커피코더 2018. 2. 25.
반응형

Spring에서 Controller를 이용하여 Request Mapping이 이루어진다.

아래에는 STS의 기본 Spring MVC 프로젝트를 만들고 나서 생기는 Controller를 기준으로 간단히 작성하였다.


아래 캡쳐 화면을 보면 MyExample  프로젝트로 Spring  MVC 프로젝트를 생성하게 되면 HomeController.java가 생성된것을 확인 할 수 있다.



HomeController.java를 보면 @Controller 어노테이션을 통해 컨트롤로를 등록한것을 알수 있다.

그리고 @RequestMapping을 사용하여 Request 경로에 따른 Mapping 경로를 정의한다.

이후 return 반환값으로 jsp명칭이 home인 jsp를 호출한다.

@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
}


Controller에서 model에 attribute로 넣은 serverTime을 ${serverTime}으로 매핑하여 표시한것을 확인 할 수 있다.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>


	Home


Hello world!

The time on the server is ${serverTime}.


JSP를 호출 하면 아래와 같은 화면이 표시되는것을 확인 할 수 있다.

나의 경우 톰캣 웹서버의 Context Root 경로(http://localhost/example/)를 호출하였다.




위의 캡쳐 화면을 보면 한글이 깨져 있는것을 확인 할 수 있는데

아래처럼 UTF-8로 jsp encoding 태그를 넣어주면 된다.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>



반응형

댓글