SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍
一、
二、用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介绍的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model
一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-006-处理表单数据(注册、显示用户资料)
一.显示注册表单 1.访问资源 @Test public void shouldShowRegistration() throws Exception { SpitterRepository mock ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-003-示例项目用到的类及配置文件
一.配置文件 1.由于它继承AbstractAnnotationConfigDispatcherServletInitializer,Servlet容器会把它当做配置文件 package spittr ...
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
随机推荐
- 20160507-hibernate入门
关联映射 多对一(Employee - Department) 一对多(Department-Employee) 一对一(Person - IDCard) 多对多(teacher - student) ...
- sql 更新重复数据只取一条记录
select s.* from ( select *, row_number() over (partition by PersonnelAccount order BY Personnel ...
- mysql空间数据相关操作
建表语句: CREATE TABLE ts.points ( name ) NOT NULL, location POINT NOT NULL, description ) ); 添加记录如下: IN ...
- C语言 宏/macor/#define/
C语言 宏/macor/#define 高级技巧 1.在进行调试的时候,需要进行打印/PRINT,可以通过define进行自定义.例如,自己最常用的DEBUG_PRINT() #define DEBU ...
- 7zS.sfx RunProgram with parameters
Config.txt as below: Pay attention to this \" ;!@Install@!UTF-8! RunProgram="setup.exe&qu ...
- sgu 104 Little Shop of Flowers
经典dp问题,花店橱窗布置,不再多说,上代码 #include <cstdio> #include <cstring> #include <iostream> #i ...
- json字符串转JSONObject,输出JSONObject问题
json架包:json-lib-2.4-jdk15.jar json字符串(存在null值)转JSONObject 后return JSONObject对象的时候会报错 例如: String str= ...
- 转:基于IOS上MDM技术相关资料整理及汇总
一.MDM相关知识: MDM (Mobile Device Management ),即移动设备管理.在21世纪的今天,数据是企业宝贵的资产,安全问题更是重中之重,在移动互联网时代,员工个人的设备接入 ...
- C#实现登录窗口(不用隐藏)
C#登录窗口的实现,特点就是不用隐藏,感兴趣的朋友不要错过 (1).在程序入口处,打开登录窗口 复制代码代码如下: static void Main() { Application.EnableV ...
- 多行滚动jQuery循环新闻列表代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...