Spring 3 MVC hello world example – Annotation

5. Spring @JavaConfig

SpringWebConfig.java

package com.mkyong.config; 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; 

@EnableWebMvc //mvc:annotation-driven
@Configuration
@ComponentScan({ "com.mkyong.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter { 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {   
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 
    
    @Bean 
    public InternalResourceViewResolver viewResolver() { 
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();  
        viewResolver.setViewClass(JstlView.class); 
        viewResolver.setPrefix("/WEB-INF/views/jsp/"); 
        viewResolver.setSuffix(".jsp"); 
        return viewResolver; 
    } 
}

XML equivalent.

 
     
     
         
            /WEB-INF/views/jsp/ 
         
         
            .jsp 
        
     
     
     

6. Servlet 3.0+ Container

Create a ServletInitializer class by extending AbstractAnnotationConfigDispatcherServletInitializer, the Servlet 3.0+ container will pick up this class and run it automatically. This is the replacement for web.xml.

MyWebInitializer.java

package com.mkyong.servlet3;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.mkyong.config.SpringWebConfig;
public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
    @Override 
    protected Class[] getServletConfigClasses() { 
        return new Class[] { 
            SpringWebConfig.class 
        }; 
    } 

    @Override 
    protected String[] getServletMappings() { 
        return new String[] { "/" }; 
    } 

    @Override 
    protected Class[] getRootConfigClasses() { return null; }
}

你可能感兴趣的:(Spring 3 MVC hello world example – Annotation)