First Spring
建立一個Spring Web Application,首先要將Spring環境建立好,後續即可使用Tomcat等應用伺服器開啟!
Servlet Initializer
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Servlet Config
@Configuration
@EnableWebMvc
@ComponentScan({"com.andy.example.*"})
public class ServletConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
這邊將web.xml改為使用JavaConfig設定,web.xml其實就是Spring對於Servlet的設定,這邊設定好後,大家可以嘗試運行看看是否設定成功。