728x90
반응형
#자바(Java) 클래스로 스프링 기본 설정(Java Config) 하는 방법
-자바버전: JDK1.8
-톰캣버전: tomcat9
#pom.xml 파일에 스프링 관련 라이브러리를 추가해줍니다.
<!-- 스프링 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- 서블릿 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
#WebAppInitConfig.java
// 톰캣 실행시 기본 설정을 위해 호출
public class WebAppInitConfig implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(DispatcherContextConfiguration.class);
ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
// 우선순위
dynamic.setLoadOnStartup(0);
// 모든 URL매핑
dynamic.addMapping("/");
}
}
#DispatcherContextConfiguration.java
@Configuration // 설정 파일
@EnableWebMvc // 스프링 MVC 활성화
@ComponentScan(basePackages= "com.jks.web1") // basePackages패키지 범위내 빈 등록
public class DispatcherContextConfiguration implements WebMvcConfigurer{
@Bean
public ViewResolver viewResolver(){
// VIEW 지정
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
// 접두사(ex./WEB-INF/views/main.jsp)
resolver.setPrefix("/WEB-INF/views");
// 접미사
resolver.setSuffix(".jsp");
return resolver;
}
}
#MainController.java
@Controller
public class MainController {
@RequestMapping("/main")
public String main(){
return "/main";
}
}
#main.jsp
<html>
<body>
<h2>Main</h2>
</body>
</html>
728x90
반응형
댓글