博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring MVC的WebMvcConfigurerAdapter用法收集(零配置,无XML配置)
阅读量:5889 次
发布时间:2019-06-19

本文共 14304 字,大约阅读时间需要 47 分钟。

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

用法:

@EnableWebMvc

开启MVC配置,相当于

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;@Configurationpublic class MyConverterRegistry {    @Autowired    private ConverterRegistry converterRegistry;    @PostConstruct    public void init() {        converterRegistry.addConverter(new StringToListConvert());    }    private static  class StringToListConvert implements Converter
> { @Override public List
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;@Configurationpublic class MyFormatterRegistry {    @Autowired    private FormatterRegistry formatterRegistry;    @PostConstruct    public void init() {        formatterRegistry.addFormatter(new StringDateFormatter());    }    public static class StringDateFormatter implements Formatter
{ //解析接口,根据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配置

 

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配置

使用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);    }}
json=application/json xml=application/xml

View

@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/").setViewName("home");    }}

View Resolvers

@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void configureViewResolvers(ViewResolverRegistry registry) {        registry.enableContentNegotiation(new MappingJackson2JsonView());        registry.jsp();    }}

Resources

@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/");    }}
@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {        configurer.enable();    }}
@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {        configurer.enable("myCustomDefaultServlet");    }}

Path Matching

@Configuration@EnableWebMvcpublic 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@EnableWebMvcpublic class WebConfiguration extends WebMvcConfigurerAdapter {    @Override    public void configureMessageConverters(List
> 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())); }}

以上示例代码:

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

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

 

参考:

(以上大部分内容转自此篇文章)

(以上小部分内容转自此篇文章)

(官方文档)

==>如有问题,请联系我:easonjim#163.com,或者下方发表评论。<==

转载地址:http://bkwsx.baihongyu.com/

你可能感兴趣的文章
策略模式简介
查看>>
UIViewController中loadView的用法(应当注意的几点)
查看>>
POJ NOI0105-42 画矩形
查看>>
Java 数组在内存中的结构
查看>>
《关爱码农成长计划》第一期报告
查看>>
entity framework 6 通用数据类
查看>>
读取FTP上的excel文件,并写入数据库
查看>>
vs2008快捷键极其技巧 转载
查看>>
window 7上安装Visual Studio 2017失败的解决方法
查看>>
Python数值计算:一 使用Pylab绘图(2)
查看>>
k8s集群监控布署
查看>>
JAVA DataOutputStream和DataInputStream
查看>>
系统集成项目管理(二)
查看>>
6.2实现用户登录逻辑
查看>>
JavaScript 正整数正则表达式
查看>>
单元测试之Stub和Mock
查看>>
solr
查看>>
IOS7 viewDidLoad中调用 pushViewController 的问题
查看>>
oracle merge into 用法详解
查看>>
tf.concat&tf.gather&tf.gather_nd&tf.greater&tf.cast&tf.expand_dims&tf.squeeze
查看>>