1. 程式人生 > >SpringMVC基於代碼的配置方式(零配置,無web.xml)

SpringMVC基於代碼的配置方式(零配置,無web.xml)

-c size ons imp .net rri import 右鍵 無需

基於配置文件的web項目維護起來可能會更方便,可是有時候我們會有一些特殊的需求,比方防止客戶胡亂更改配置,這時候我們須要給配置隱藏到代碼中。

1.創建一個動態web項目(無需web.xml)

2.右鍵項目加入幾個package: com.easyweb.config (保存項目配置) com.easyweb.controller (保存springMvc controller)

3.在 com.easyweb.config 新建一個類 WebApplicationStartup 。這個類實現WebApplicationInitializer 接口,是項目的入口,作用相似於web.xml,詳細代碼例如以下:

package com.easyweb.config;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import
org.springframework.web.servlet.DispatcherServlet; /** * server啟動入口類 * * @author Administrator * */ public class WebApplicationStartup implements WebApplicationInitializer { private static final String SERVLET_NAME = "Spring-mvc"; private static final long MAX_FILE_UPLOAD_SIZE = 1024 * 1024
* 5; // 5 Mb private static final int FILE_SIZE_THRESHOLD = 1024 * 1024; // After 1Mb private static final long MAX_REQUEST_SIZE = -1L; // No request size limit /** * server啟動調用此方法,在這裏能夠做配置 作用與web.xml同樣 */ @Override public void onStartup(ServletContext servletContext) throws ServletException { // 註冊springMvc的servlet this.addServlet(servletContext); // 註冊過濾器 // servletContext.addFilter(arg0, arg1) // 註冊監聽器 // servletContext.addListener(arg0); } /** * 註冊Spring servlet * * @param servletContext */ private void addServlet(ServletContext servletContext) { // 構建一個application context AnnotationConfigWebApplicationContext webContext = createWebContext(SpringMVC.class, ViewConfiguration.class); // 註冊spring mvc 的 servlet Dynamic dynamic = servletContext.addServlet(SERVLET_NAME, new DispatcherServlet(webContext)); // 加入springMVC 同意訪問的Controller後綴 dynamic.addMapping("*.html", "*.ajax", "*.css", "*.js", "*.gif", "*.jpg", "*.png"); // 所有通過請用 “/” // dynamic.addMapping("/"); dynamic.setLoadOnStartup(1); dynamic.setMultipartConfig(new MultipartConfigElement(null, MAX_FILE_UPLOAD_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD)); } /** * 通過自己定義的配置類來實例化一個Web Application Context * * @param annotatedClasses * @return */ private AnnotationConfigWebApplicationContext createWebContext(Class<?

>... annotatedClasses) { AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext(); webContext.register(annotatedClasses); return webContext; } }

4.在com.easyweb.config 下加入類 SpringMVC 繼承 WebMvcConfigurerAdapter。這個類的作用是進行SpringMVC的一些配置,代碼例如以下:

package com.easyweb.config;

import org.springframework.context.annotation.ComponentScan;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
//指明controller所在的包名
@ComponentScan(basePackages = {"com.easyweb.controller"})
public class SpringMVC extends WebMvcConfigurerAdapter {

  /**
   * 非必須
   */
  @Override
  public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }

  /**
   * 假設項目的一些資源文件放在/WEB-INF/resources/以下
   * 在瀏覽器訪問的地址就是相似:http://host:port/projectName/WEB-INF/resources/xxx.css
   * 可是加了例如以下定義之後就能夠這樣訪問:
   * http://host:port/projectName/resources/xxx.css
   * 非必須
   */
  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**/*").addResourceLocations("/WEB-INF/resources/");
  }
}

5.加入view配置文件com.easyweb.config下新建類ViewConfiguration,裏面能夠依據自己的須要定義視圖攔截器:

package com.easyweb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;

@Configuration
public class ViewConfiguration {

    @Bean
    public ViewResolver urlBasedViewResolver() {
        UrlBasedViewResolver viewResolver;
        viewResolver = new UrlBasedViewResolver();
        viewResolver.setOrder(2);
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        // for debug envirment
        viewResolver.setCache(false);
        return viewResolver;
    }
    @Bean
    public ViewResolver tilesViewResolver() {
        UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
        urlBasedViewResolver.setOrder(1);
        urlBasedViewResolver.setViewClass(TilesView.class);
        //urlBasedViewResolver.
        return urlBasedViewResolver;
    }
    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions(new String[] { "classpath:tiles.xml" });
        return tilesConfigurer;
    }
}

6.本例中還用了tiles視圖解析器。替換了原始的include方式

7.完整代碼已上傳
http://download.csdn.net/detail/u013816347/8998891

學習路上,歡迎評論指正。

SpringMVC基於代碼的配置方式(零配置,無web.xml)