spring Boot 默认的处理方式就已经足够了,默认情况下Spring Boot 使用WebMvcAutoConfiguration中配置的各种属性。

建议使用Spring Boot 默认处理方式,需要自己配置的地方可以通过配置文件修改。

但是如果你想完全控制Spring MVC,你可以在@Configuration注解的配置类上增加@EnableWebMvc,增加该注解以后WebMvcAutoConfiguration中配置就不会生效,你需要自己来配置需要的每一项。这种情况下的配置方法建议参考WebMvcAutoConfiguration类。

http://blog.csdn.net/isea533/article/details/50412212

静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。

默认配置

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

  • /static
  • /public
  • /resources
  • /META-INF/resources

举例:我们可以在src/main/resources/(classpath下)目录下创建static,在该位置放置一个图片文件D.jsp(src/main/resources/static/D.jpg)。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。

http://blog.didispace.com/springbootweb/

27.1.5 Static Content

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method.

In a stand-alone web application the default servlet from the container is also enabled, and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. Most of the time this will not happen (unless you modify the default MVC configuration) because Spring will always be able to handle requests through the DispatcherServlet.

You can customize the static resource locations using spring.resources.staticLocations (replacing the default values with a list of directory locations). If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html in any of your locations on startup, it will be the home page of the application.

In addition to the ‘standard’ static resource locations above, a special case is made for Webjars content. Any resources with a path in /webjars/** will be served from jar files if they are packaged in the Webjars format.

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.

Spring Boot also supports advanced resource handling features provided by Spring MVC, allowing use cases such as cache busting static resources or using version agnostic URLs for Webjars.

To use version agnostic URLs for Webjars, simply add the webjars-locator dependency. Then declare your Webjar, taking jQuery for example, as "/webjars/jquery/dist/jquery.min.js" which results in "/webjars/jquery/x.y.z/dist/jquery.min.js" where x.y.z is the Webjar version.

If you are using JBoss, you’ll need to declare the webjars-locator-jboss-vfs dependency instead of the webjars-locator; otherwise all Webjars resolve as a 404.

To use cache busting, the following configuration will configure a cache busting solution for all static resources, effectively adding a content hash in URLs, such as<link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

Links to resources are rewritten at runtime in template, thanks to a ResourceUrlEncodingFilter, auto-configured for Thymeleaf, Velocity and FreeMarker. You should manually declare this filter when using JSPs. Other template engines aren’t automatically supported right now, but can be with custom template macros/helpers and the use of the ResourceUrlProvider.

When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That’s why other strategies are also supported and can be combined. A "fixed" strategy will add a static version string in the URL, without changing the file name:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12

With this configuration, JavaScript modules located under "/js/lib/" will use a fixed versioning strategy "/v12/js/lib/mymodule.js" while other resources will still use the content one <link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>.

See ResourceProperties for more of the supported options.

This feature has been thoroughly described in a dedicated blog post and in Spring Framework’s reference documentation.

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html

While this may not be a new revelation to those of you that have been following Spring Boot since the SpringOne announcement, there is one detail for which you may not be aware. Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/
/resources/
/static/
/public/
In the case of the Consuming a RESTful Web Service with jQuery guide, we included index.html and hello.js files in the /public/ folder. This means that not only does Spring Boot offer a simple approach to building Java or Groovy apps, you can also use it to easily deploy client-side JavaScript code and test it within a real web server environment!

You can analyze the details of how this works by reviewing the source code for WebMvcAutoConfiguration in Spring Boot, you will see the following declaration for a string array containing locations for Classpath resources.

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };

Further in the code you can see that these locations are added to a Spring MVC ResourceHandlerRegistry.

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
RESOURCE_LOCATIONS);
}
}

To review, web AutoConfiguration is executed when Spring Boot identifies a class with the @Controller annotation. The result is that you can place static web resources in any of these locations, and those static assets are then served by Tomcat when you access your application.

Spring Boot offers many exciting features to help easily create Spring based applications that you can “just run”. The fun byproduct is that it is equally as easy to build and test client-side JavaScript apps with Spring Boot.

https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

URL重定向:

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/1.txt");//1.txt文件放在src/main/resources/static/1.txt
}
}

It would have worked out of the box if you hadn't used @EnableWebMvc annotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}

Ok I figured it out. In case you also want to change the url from / to /index.html use "redirect:/index.html" instead of forward.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class MyWebMvcConfig { @Bean
public WebMvcConfigurerAdapter forwardToIndex() {
return new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// forward requests to /admin and /user to their index.html
registry.addViewController("/admin").setViewName(
"forward:/admin/index.html");
registry.addViewController("/user").setViewName(
"forward:/user/index.html");
}
};
} }

http://stackoverflow.com/questions/27381781/java-spring-boot-how-to-map-my-app-root-to-index-html?noredirect=1&lq=1

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesViewResolver; import java.util.*; /**
* Created by MyWorld on 2016/11/13.
*/
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
} @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);//将视图解析为JstlView而不是InternalResourceView
return viewResolver;
} @Bean
public TilesConfigurer tilesConfigurer() {
final TilesConfigurer configurer = new TilesConfigurer();
// configurer.setDefinitions(new String[] { "WEB-INF/views_common.xml" });
configurer.setDefinitions(new String[]{"/WEB-INF/views_*.xml"});
configurer.setCheckRefresh(true);
return configurer;
} @Bean
public TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
} @Bean
public MappingJackson2JsonView mappingJackson2JsonView() {
return new MappingJackson2JsonView();
} @Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver(TilesViewResolver tilesViewResolver, MappingJackson2JsonView mappingJackson2JsonView) {
ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
viewResolver.setIgnoreAcceptHeader(true);
viewResolver.setDefaultContentType(MediaType.TEXT_HTML);
Map<String, String> map = new HashMap<>();
map.put("atom", "application/atom+xml");
map.put("html", "text/html");
map.put("json", "application/json");
viewResolver.setMediaTypes(map);
viewResolver.setFavorParameter(false);
List<ViewResolver> list = new ArrayList<>();
list.add(tilesViewResolver);
viewResolver.setViewResolvers(list);
viewResolver.setDefaultViews(Collections.singletonList(mappingJackson2JsonView));
return viewResolver;
} @Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(10485760000L);
commonsMultipartResolver.setMaxInMemorySize(40960); return commonsMultipartResolver;
} }

56. Installing Spring Boot applications

In additional to running Spring Boot applications using java -jar it is also possible to make fully executable applications for Unix systems. This makes it very easy to install and manage Spring Boot applications in common production environments.

To create a ‘fully executable’ jar with Maven use the following plugin configuration:

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>

With Gradle, the equivalent configuration would be:

apply plugin: 'org.springframework.boot'

springBoot {
executable = true
}

You can then run your application by typing ./my-application.jar (where my-application is the name of your artifact).

Fully executable jars work by embedding an extra script at the front of the file. Not all tools currently accept this format so you may not always be able to use this technique.

The default script supports most Linux distributions and is tested on CentOS and Ubuntu. Other platforms, such as OS X and FreeBSD, will require the use of a custom embeddedLaunchScript.

When a fully executable jar is run, it uses the jar’s directory as the working directory.

http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

Spring boot executable jar/war

spring boot里其实不仅可以直接以 Java -jar demo.jar的方式启动,还可以把jar/war变为一个可以执行的脚本来启动,比如./demo.jar。

把这个executable jar/war 链接到/etc/init.d下面,还可以变为Linux下的一个service。

只要在spring boot maven plugin里配置:

1
2
3
4
5
6
7
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>

这样子打包出来的jar/war就是可执行的。更多详细的内容可以参考官方的文档。

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#deployment-install

zip 格式里的 magic number

生成的jar/war实际上是一个zip格式的文件,这个zip格式文件为什么可以在shell下面直接执行?

研究了下zip文件的格式。zip文件是由entry组成的,而每一个entry开头都有一个4个字节的magic number:

1
2
3
Local file header signature = 0x04034b50 (read as a little-endian number)
 
即 PK\003\004

参考:https://en.wikipedia.org/wiki/Zip_(file_format)

zip处理软件是读取到magic number才开始处理。所以在linux/unix下面,可以把一个bash文件直接写在一个zip文件的开头,这样子会被认为是一个bash script。 而zip处理软件在读取这个文件时,仍然可以正确地处理。

比如spring boot生成的executable jar/war,的开头是:

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
#
# . ____ _ __ _ _
# /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
# ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
# \\/ ___)| |_)| | | | | || (_| | ) ) ) )
# ' |____| .__|_| |_|_| |_\__, | / / / /
# =========|_|==============|___/=/_/_/_/
# :: Spring Boot Startup Script ::
#

在script内容结尾,可以看到zip entry的magic number:

1
2
exit 0
PK^C^D

spring boot 的 launch.script

实际上spring boot maven plugin是把下面这个script打包到fat jar的最前面部分。

https://github.com/spring-projects/spring-boot/blob/1ca9cdabf71f3f972a9c1fdbfe9a9f5fda561287/spring-boot-tools/spring-boot-loader-tools/src/main/resources/org/springframework/boot/loader/tools/launch.script

这个launch.script 支持很多变量设置。还可以自动识别是处于auto还是service不同mode中。

所谓的auto mode就是指直接运行jar/war:

1
./demo.jar

而service mode则是由操作系统在启动service的情况:

1
service demo start/stop/restart/status

所以fat jar可以直接在普通的命令行里执行,./xxx.jar 或者link到/etc/init.d/下,变为一个service。

http://www.importnew.com/24471.html

WebMvcConfigurerAdapter的更多相关文章

  1. SpringBoot---页面跳转之WebMvcConfigurerAdapter

    摘要:在springboot中定义自己的方法继承WebMvcConfigurerAdapter方法可以实现扩展springMvc功能,要全面实现接管springmvc就要在自己的方法上加上@Enabl ...

  2. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案(转)

    文章转自 http://blog.51cto.com/12066352/2093750 最近项目采用spring icloud,用的spring boot版本是1.5.x的,spring boot 2 ...

  3. spring boot 2.0 WebMvcConfigurerAdapter过时解决方法

    第一种: @Configuration public class WebAppConfig implements WebMvcConfigurer{ @Bean public HandlerInter ...

  4. SpringBoot Web开发(3) WebMvcConfigurerAdapter过期替代方案

    springboot2.0中 WebMvcConfigurerAdapter过期替代方案 最近在学习尚硅谷的<springboot核心技术篇>,项目中用到SpringMVC的自动配置和扩展 ...

  5. WebMvcConfigurerAdapter已过时,替换接口或类

    WebMvcConfigurerAdapter已经过时,在新版本2.x中被废弃,原因是springboot2.0以后,引用的是spring5.0,而spring5.0取消了WebMvcConfigur ...

  6. WebMvcConfigurerAdapter已过时

    Spring Boot2.0的版本(创建的时候自动选择的这个版本),然后编译器告诉我WebMvcConfigurerAdapter已过时了 @Deprecated public abstract cl ...

  7. spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案

    Springboot中静态资源和拦截器处理(踩了坑)   背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到spr ...

  8. WebMvcConfigurerAdapter已经过时的问题解决

    spring 5开始已经废弃WebMvcConfigurerAdapter,替代的是WebMvcConfigurer接口. 参考: https://blog.csdn.net/lenkvin/arti ...

  9. spring boot 拦截器之WebMvcConfigurerAdapter

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+]   上一篇我们讲到了拦截器,我们也简单的讲解到了WebMvcConfigurerAdapter这个拦截器.本篇我们来对Web ...

随机推荐

  1. j2SE基回顾(一)

    1. 九种基本数据类型的大小,以及他们的封装类. 2. Switch能否用string做参数? 3. equals与==的区别. 4. Object有哪些公用方法? Object是所有类的父类,任何类 ...

  2. OS X 使用技巧——轻松地调整窗口大小

    如果你想调整窗口大小,只需要把鼠标指针悬停在窗口边框上.当它变成双向箭头时,点击并拖动鼠标即可完成这一操作. 但在实际操作中,迅速把鼠标指针定位到边框上比较困难. 解决的办法是:在终端输入以下命令: ...

  3. Spring MVC mapping[From Spring MVC Beginner's Guide]

    In a Spring MVC application, the URL can logically be divided into five parts (see the following fig ...

  4. Ext.Ajax中scope的作用

    在Ext的前台Js中使用Ajax请求,如果想让回调函数中的this作用域跟当前的类一样如何实现呢?Ajax提供了一个参数scope. 详细代码如下: layout : { type : 'accord ...

  5. 系统集成之用户统一登录( LDAP + wso2 Identity Server)

    本文场景: LDAP + wso2 Identity Server + asp.net声明感知 场景 ,假定读者已经了解过ws-*协议族,及 ws-trust 和 ws-federation. 随着开 ...

  6. 博弈论入门小结 分类: ACM TYPE 2014-08-31 10:15 73人阅读 评论(0) 收藏

    文章原地址:http://blog.csdn.net/zhangxiang0125/article/details/6174639 博弈论:是二人或多人在平等的对局中各自利用对方的策略变换自己的对抗策 ...

  7. cordova /phonegap 自定义插件

    ### cordova /phonegap 自定义插件 在使用cordova 的过程中,虽然官方提供的插件以及其他人开源的插件较多.但有时为了实现某种需求,还是需要自己编写插件. 以前总是会手动的配置 ...

  8. 如何混合使用ARC和非ARC

    如果你的项目使用的非ARC模式,则为ARC模式的代码文件加入-fobjc-arc标签.如果你的项目使用的ARC模式,则为非ARC模式的代码文件加入 -fno-objc-arc标签.添加标签的方法: 1 ...

  9. C#获取网页中的验证码图片(转载)

    有时候我们需要获得网页上的图片,尤其是向验证码这样的图片.这个方法就是将网页上的图片获取到PictureBox中.效果入下图所示. 右边是使用Webbrowser控件装载的某网站的注册页面,其中包括了 ...

  10. 小圣求职记B:总集篇

    1. 搜狐sohu 搜狐在正式招聘前邀请了部分应聘者到武汉研发中心开座谈会(因此简历尽量早投,机会多些),有研发的也有产品的,40人左右,座谈会期间介绍了搜狐汽车.北京研发中心.武汉研发中心和搜狐媒体 ...