서블릿 스펙에 따르면 WEB-INF 폴더의 하위 폴더로 lib 폴더와 classes 폴더를 생성하고 각각의 폴더에 필요한 jar파일과
컴파일 된 클래스 파일이 위치해야 한다. 하지만 메이븐이나 그레이들 프로젝트의 경우 필요한 jar 파일은 pom.xml/build.gradle파일의 의존을 통해
지정하고 컴파일된 결과는 target 폴더나 build 폴더에 위치한다. 때문에 WEB-INF 폴더 밑에 lib폴더나 classes 폴더를 생성할 필요가 없다.
package config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
}
package chap09;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model,
@RequestParam(value = "name", required = false) String name) {
model.addAttribute("greeting", "안녕하세요, " + name);
return "hello";
}
}
컨트롤러란?
웹 요청을 처리하고 그 결과를 뷰에 전달하는 스프링 빈 객체이다.
스프링 컨트롤러로 사용될 클래스는 @Controller 어노테이션을 붙여야하고, @GetMapping 어노테이션이나 @PostMapping 어노테이션과 같은 요청 매핑 어노테이션을 이용해서 처리할 경로를 지정해줘야한다.
아래와 같은 url이 있다고 가정한다면,
@GetMapping("/hello")
public String hello(Model model, @RequestParam(value = "name", required = false) String name) {
model.addAttribute("greeting", "안녕하세요," + name);
return "hello";
}
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import chap09.HelloController;
@Configuration
public class ControllerConfig {
@Bean
public HelloController helloController() {
return new HelloController();
}
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}