原理先不了解,只记录常用方法

用法:

@EnableWebMvc

开启MVC配置,相当于

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> </beans>

Conversion and Formatting

配置convert和formatter的方法有两种,分别使用ConverterRegistry和FormatterRegistry

使用注册工厂

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry; import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List; @Configuration
public class MyConverterRegistry {
@Autowired
private ConverterRegistry converterRegistry; @PostConstruct
public void init() {
converterRegistry.addConverter(new StringToListConvert());
} private static class StringToListConvert implements Converter<String, List<String>> {
@Override
public List<String> convert(String source) {
if (source == null) {
return Arrays.asList();
} else {
String[] split = source.split(",");
return Arrays.asList(split);
}
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry; import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.util.List;
import java.util.Locale; @Configuration
public class MyFormatterRegistry { @Autowired
private FormatterRegistry formatterRegistry; @PostConstruct
public void init() {
formatterRegistry.addFormatter(new StringDateFormatter());
} public static class StringDateFormatter implements Formatter<List> {
//解析接口,根据Locale信息解析字符串到T类型的对象; @Override
public List parse(String text, Locale locale) throws ParseException {
return null;
} //格式化显示接口,将T类型的对象根据Locale信息以某种格式进行打印显示(即返回字符串形式);
@Override
public String print(List object, Locale locale) {
return "我是格式化的日期";
}
}
}

WebMvcConfigurerAdapter

import com.lf.web.convert.StringToListConvert;
import com.lf.web.formatter.StringDateFormatter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
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.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration
@EnableWebMvc
@ComponentScan//组件扫描
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addFormatters(FormatterRegistry registry) {
super.addFormatters(registry);
registry.addFormatter(new StringDateFormatter());
registry.addConverter(new StringToListConvert());
}
}

使用XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.web.convert.StringToListConvert"/>
</set>
</property>
<property name="formatters">
<set>
<bean class="com.web.formatter.StringDateFormatter"/>
</set>
</property>
<property name="formatterRegistrars">
<set>
<bean class="com.web.formatter.StringDateFormatter"/>
</set>
</property>
</bean> </beans> 

Interceptors

拦截器的实现

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class MyHandlerInterceptor extends HandlerInterceptorAdapter { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("===========HandlerInterceptor1 preHandle");
return super.preHandle(request, response, handler);
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
System.out.println("===========HandlerInterceptor1 postHandle");
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
System.out.println("===========HandlerInterceptor1 afterCompletion");
}
}

XML配置

<bean id="handlerInterceptor1"   class="com.lf.web.MyHandlerInterceptor"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="handlerInterceptor1"/>
<ref bean="handlerInterceptor2"/>
</list>
</property>
</bean> <mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/admin/**"/>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/secure/*"/>
<bean class="org.example.SecurityInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

使用Java配置

import com.lf.web.convert.StringToListConvert;
import com.lf.web.formatter.StringDateFormatter;
import com.lf.web.interceptor.MyHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration
@EnableWebMvc
@ComponentScan//组件扫描
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/").excludePathPatterns("/admin");
}
}

ConfigureContentNegotiation

ContentNegotiatingViewResolver是ViewResolver使用所请求的媒体类型的一个实现(基于文件类型扩展,输出格式URL参数指定类型或接受报头)来选择一个合适的视图一个请求。ContentNegotiatingViewResolver本身并不解决视图,只不表示为其他的ViewResolver,您可以配置来处理特定的视图(XML,JSON,PDF,XLS,HTML,..)。

@Configuration
@EnableWebMvc
@ComponentScan//组件扫描
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("json", MediaType.APPLICATION_JSON);
}
}
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
</value>
</property>
</bean>

View

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
} }
<mvc:view-controller path="/" view-name="home"/>

View Resolvers

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(new MappingJackson2JsonView());
registry.jsp();
} }
<mvc:view-resolvers>
<mvc:content-negotiation>
<mvc:default-views>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</mvc:default-views>
</mvc:content-negotiation>
<mvc:jsp/>
</mvc:view-resolvers>

Resources

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/");
} }
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
} }
<mvc:default-servlet-handler/>
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable("myCustomDefaultServlet");
} }

Path Matching

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer
.setUseSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUseRegisteredSuffixPatternMatch(true)
.setPathMatcher(antPathMatcher())
.setUrlPathHelper(urlPathHelper());
} @Bean
public UrlPathHelper urlPathHelper() {
//...
} @Bean
public PathMatcher antPathMatcher() {
//...
} }

Message Converters

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter { @Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.modulesToInstall(new ParameterNamesModule());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
} }

以上示例代码:https://gitee.com/jim.zhan/SpringLearning

下面是基于零配置的项目示例:

1、创建一个动态Web项目(无需web.xml)

2、右键项目添加几个package: com.easyweb.config(保存项目配置)、com.easyweb.controller(保存Spring MVC Controller)

3、在com.easyweb.config新建一个类WebApplicationStartup,这个类实现WebApplicationInitializer接口,是项目的入口,作用类似于web.xml,具体代码如下:

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; /**
* 服务器启动入口类
*
* @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 /**
* 服务器启动调用此方法,在这里可以做配置 作用与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的一些配置,代码如下:

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/下面
* 在浏览器访问的地址就是类似:https://host:port/projectName/WEB-INF/resources/xxx.css
* 但是加了如下定义之后就可以这样访问:
* https://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,里面可以根据自己的需要定义视图拦截器:

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;
}

参考:

http://blog.csdn.net/L_Sail/article/details/71436392(以上大部分内容转自此篇文章)

https://www.2cto.com/kf/201508/432280.html

https://segmentfault.com/a/1190000004343063?_ea=575820(以上小部分内容转自此篇文章)

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html(官方文档)

Spring MVC的WebMvcConfigurerAdapter用法收集(零配置,无XML配置)的更多相关文章

  1. Spring MVC 中使用AOP 进行统一日志管理--XML配置实现

    1.介绍 上一篇博客写了使用AOP进行统一日志管理的注解版实现,今天写一下使用XML配置实现版本,与上篇不同的是上次我们记录的Controller层日志,这次我们记录的是Service层的日志.使用的 ...

  2. Spring MVC RedirectAttributes的用法解决办法

    Spring MVC RedirectAttributes的用法很久没发过技术贴了,今天对于一个问题纠结了2小时,遂放弃研究用另一种方法解决,奈何心中一直存在纠结,发帖求解 我先解释下什么是Redir ...

  3. Spring注解配置和xml配置优缺点比较

    Spring注解配置和xml配置优缺点比较 编辑 ​ 在昨天发布的文章<spring boot基于注解方式配置datasource>一文中凯哥简单的对xml配置和注解配置进行了比较.然后朋 ...

  4. Spring的注解配置与XML配置之间的比较

    注释配置相对于 XML 配置具有很多的优势: 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作. 如:使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO ...

  5. IDEA用maven创建springMVC项目和配置(XML配置和Java配置)

    1.DEA创建项目 新建一个maven project,并且选择webapp原型. 然后点击next 这里的GroupId和ArtifactID随意填写,但是ArtifactID最好和你的项目一名一样 ...

  6. Hibernate实现有两种配置,xml配置与注释配置

    hibernate实现有两种配置,xml配置与注释配置. (1):xml配置:hibernate.cfg.xml (放到src目录下)和实体配置类:xxx.hbm.xml(与实体为同一目录中) < ...

  7. hibernate实现有两种配置,xml配置与注释配置。<转>

    <注意:在配置时hibernate的下载的版本一定确保正确,因为不同版本导入的jar包可能不一样,所以会导致出现一些错误> hibernate实现有两种配置,xml配置与注释配置. (1) ...

  8. 使用IDEA搭建一个 Spring + Spring MVC 的Web项目(零配置文件)

    注解是Spring的一个构建的一个重要手段,减少写配置文件,下面解释一下一些要用到的注解: @Configuration 作用于类上面,声明当前类是一个配置类(相当于一个Spring的xml文件)@C ...

  9. 使用IDEA搭建一个Spring + AOP (权限管理 ) + Spring MVC + Mybatis的Web项目 (零配置文件)

    前言: 除了mybatis 不是零配置,有些还是有xml的配置文件在里面的. 注解是Spring的一个构建的一个重要手段,减少写配置文件,下面解释一下一些要用到的注解: @Configuration  ...

随机推荐

  1. 原创:PHP编译安装配置参数说明

    --prefix=/application/php-5.5.32 \          #指定PHP的安装路径 --with-mysql=/application/mysql/ \          ...

  2. XtraBackUp 热备份工具

    是一款强大的在线热备份工具 备份的过程中,不锁表 使用percona-xtrabackup-24-2.4.7-1.el7.x86_64.rpm yum源安装: 1.安装Percona的库:       ...

  3. Python基础2 列表 元祖 字符串 字典 集合 文件操作 -DAY2

    本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...

  4. 测试常用的linux命令

    一.系统 1.halt:         关机   poweroff: 关机 2.reboot:     重启 二.处理目录和文件的命令 1.ll:     显示文件详细信息 ls:    显示文件目 ...

  5. 最短路 || POJ 1511 Invitation Cards

    已知图中从一点到另一点的距离,从1号点到另一点再从这一点返回1号点,求去到所有点的距离之和最小值 *解法:正着反着分别建图,把到每个点的距离加起来 spfa跑完之后dist数组就是从起点到每一点的最短 ...

  6. js实现音量拖拽的效果模拟

    <!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>js ...

  7. 万能的搜索--之BFS(三)

    接着(一)start (二)广度优先搜索(BFS) 广度优先搜索(又称宽度优先搜索算法)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型.   Dijkstra单源最短路径算法和Pri ...

  8. Oracle 10g R2 Transparent Data Encryption 透明数据加密

    Oracle 10g R2 Transparent Data Encryption 透明数据加密 本章介绍如何使用透明数据加密来保护Oracle数据库中的敏感数据,该功能使您可以加密数据库列并管理加密 ...

  9. pycharm的快捷键以及常用设置

    1.编辑(Editing) Ctrl + Space 基本的代码完成(类.方法.属性) Ctrl + Alt + Space 快速导入任意类 Ctrl + Shift + Enter 语句完成 Ctr ...

  10. Python中 模块、包、库

    模块:就是.py文件,里面定义了一些函数和变量,需要的时候就可以导入这些模块. 包:在模块之上的概念,为了方便管理而将文件进行打包.包目录下第一个文件便是 __init__.py,然后是一些模块文件和 ...