一、

二、用Java文件配置web application

1.

 package spittr.config;

 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

 import spittr.web.WebConfig;

 public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
//Specify configuration class
return new Class<?>[] { WebConfig.class };
} @Override
protected String[] getServletMappings() {
//Map DispatcherServlet to "/"
return new String[] { "/" };
} }

(1)值得注意的是SpitterWebInitializer继承了AbstractAnnotationConfigDispatcherServletInitializer,所以在Servlet3.1以上的容器中,会自动将此类作为DispatcherServlet和Spring Application Context的配置文件

从Servlect3.0开始,窗器会在classpath中寻找实现javax.servlet.ServletContainerInitializer的类作为配置文件,而Spring提供了实现SpringServletContainerInitializer、WebApplicationInitializer、AbstractAnnotationConfigDispatcherServletInitializer

(2)在Spring web application通常有两种context:Dispactcherservlet、ContextLoaderListener

Dispactcherservlet用来装载springmvc相关组件,如controller、view resolvers、handler mappings,ContextLoaderListener是装载应用的其他组件,通常是中间层和后台打交道的组件,如service、dao。 上述配置文件通过getServletConfigClasses()以返回的java配置文件来定义Dispatcherservlet,用getRootConfigClasses()以返回的配置文件定义ContextLoaderListener,其实就是相当于以前的web.xml配置

2.

package spittr.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
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;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter { @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
} @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//Configure static content handling
configurer.enable();
//configurer.enable();是you’re asking DispatcherServlet to forward
//requests for static resources to the servlet container’s default servlet and not to try to
//handle them itself.
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
super.addResourceHandlers(registry);
} }

在xml中是用 <mvc:annotation-driven>

3.

package spittr.config;

import java.util.regex.Pattern;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.core.type.filter.RegexPatternTypeFilter; import spittr.config.RootConfig.WebPackage; @Configuration
@Import(DataConfig.class)
@ComponentScan(basePackages={"spittr"},
excludeFilters={
@Filter(type=FilterType.CUSTOM, value=WebPackage.class)
})
public class RootConfig {
public static class WebPackage extends RegexPatternTypeFilter {
public WebPackage() {
super(Pattern.compile("spittr\\.web"));
}
}
}

4.

 package spittr.config;

 import javax.sql.DataSource;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration
public class DataConfig { @Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
} @Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
} }

5.

SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  2. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error

    一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...

  3. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)

    一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...

  4. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model

    一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...

  5. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)

    一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件

    一.配置文件 1.由于它继承AbstractAnnotationConfigDispatcherServletInitializer,Servlet容器会把它当做配置文件 package spittr ...

  7. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice

    No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...

  8. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver

    一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...

  9. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

随机推荐

  1. android webview乱码问题

    使用 loadData方法是中文部分会出现乱码,即使指定“utf-8”.“gbk”.“gb2312”也一样. webView.getSettings().setDefaultTextEncodingN ...

  2. Apache 流媒体 拖动模块编译

    Windows使用apxs独立编译 Apache 模块 http://blog.sina.com.cn/s/blog_43b83d340100mdhl.html 安装 apxs 1.解压apxs.zi ...

  3. C# 高精度减法 支持小数(待优化)

    是现实思路 1,先小数点补位,8913758923475893274958738945793845-4893127498372459823745324532453245.284929384729837 ...

  4. JSON parser error with double quotes

    Use backslash charater \ to escape double quotes in JSON file as below example. { "myInfo" ...

  5. 【JSP&Servlet学习笔记】5.Servlet进阶AIP、过滤器与监听器

    Servlet接口上,与生命周期及请求服务相关的三个方法是init().service()与destory()方法.当Web容器加载Servlet类并实例化之后,会生成ServletConfig对象并 ...

  6. 使用jQuery.FileUpload和Backload自定义控制器上传多个文件

    当需要在控制器中处理除了文件的其他表单字段,执行控制器独有的业务逻辑......等等,这时候我们可以自定义控制器. 通过继承BackloadController □ 思路 BackloadContro ...

  7. matlab2014在mac Yosemite下出现java空指针情况

    恢复方法为 使用xcode打开 /System/Library/CoreServices/SystemVersion.plist 将 ProductVersion 下的10.10或10.10.1改为1 ...

  8. ecshop二次开发 给商品添加自定义字段

    说起自定义字段,我想很多的朋友像我一样会想起一些开源的CMS(比如Dedecms.Phpcms.帝国)等,他们是可以在后台直接添加自定义字段的. 抱着这种想法我在Ecshop的后台一顿找,不过肿么都木 ...

  9. 捕获ClientDataSet.ApplyUpdates和SocketConnection异常

    核心提示:如何捕获ClientDataSet.ApplyUpdates的错误,不用ReconcileError... var cdsEmp:TClientDataSet; //保存 procedure ...

  10. oracle expdp 无法导出SYS下特定TABLE

    创建测试表: D:\app\product\\db_1>sqlplus "/as sysdba" SQL :: Copyright (c) , , Oracle. All r ...