使用 Java 設定

Quick Start 裡我們使用xml設定spring
您也可以使用java進行設定

Servlet Inializer (對應web.xml)

public class WebXML extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{ApplicationContextConfig.class, SecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{DispatcherServlet.class};
    }

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

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(new MyContextLoaderListener());
        super.onStartup(servletContext);
    }
}

說明

  • getRootConfigClasses()定義哪些class需載入
  • getServletConfigClasses()定義dispatcher class的實作,相當於web.xml內定義<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  • onStartup()內新增ContextLoaderListener,相當於web.xml內定義<listener></listener>

DispaterhServlet

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan({"my.controller"})
public class DispatcherServlet extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setExposeContextBeansAsAttributes(true);
        return viewResolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

說明:

  • 宣告@Configuration代表是一個設定
  • 宣告@EnableWebMvc代表開啟MVC機制
  • 宣告@EnableAspectJAutoProxy代表使用aop功能
  • 宣告@ComponentScan代表哪些component的package需要掃描
  • 改寫viewResolver()可定義一些路徑

Context Loader Listener

public class MyContextLoaderListener extends ContextLoaderListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("########################################");

        // do something

        System.out.println("contextInitialized");
        System.out.println("########################################");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        super.contextDestroyed(event);
    }
}

Controller

@Controller
public class HelloworldController {
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    @ResponseBody
    public String helloworld(HttpServletRequest request) {
        return "Hello_World";
    }
}

results matching ""

    No results matching ""