磕一磕:Spring boot 打包后静态资源及JSP等资源访问不到问题

问题描述:

spring boot项目打包成jar包后,无法访问静态资源问题。

原因分析:

资源文件未打包到对应目录,导致容器无法识别,需要配置代码实现。

解决办法:

图片、js、css等静态资源配置:

spring.mvc.static-path-pattern=/static/**,/page/**,/upload/** 
spring.resources.static-locations=classpath:/static/,classpath:/page/,classpath:/upload/

代码配置:

import java.util.ArrayList;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	public WebMvcConfig() {
		logger.info("WebMvcConfig init!!!");
	}

	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 指定了静态资源文件的位置
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
		registry.addResourceHandler("/page/**").addResourceLocations("classpath:/page/");
		registry.addResourceHandler("/upload/**").addResourceLocations("file:" + Global.getRoot() + "/upload/");


		super.addResourceHandlers(registry);
	}

}

jsp文件配置:

首先需要配置文件及代码中添加相关配置。

#jsp配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

代码配置:

import java.util.ArrayList;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	public WebMvcConfig() {
		logger.info("WebMvcConfig init!!!");
	}


	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/jsp/");
		resolver.setSuffix(".jsp");
		registry.viewResolver(resolver);
	}
}

文件目录:

src/main/resources下放静态资源。

src/main/webapp下放jsp文件,需放WEB-INF下。

项目打包:使用maven打包项目。

可执行jar包导报配置:

<!--打包jar -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
					<!--不打包资源文件 -->
					<excludes>
						<exclude>*.**</exclude>
						<exclude>*/*.xml</exclude>
						<exclude>**/page/**</exclude>
						<exclude>**/static/**</exclude>
						<exclude>**/upload/**</exclude>
						<exclude>/WEB-INF/**</exclude>
					</excludes>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<!--MANIFEST.MF 中 Class-Path 加入前缀 -->
							<classpathPrefix>lib/</classpathPrefix>
							<!--jar包不包含唯一版本标识 -->
							<useUniqueVersions>false</useUniqueVersions>
							<!--指定入口类 -->
							<mainClass>com.xxxx.启动类的路径</mainClass>
						</manifest>
						<manifestEntries>
							<!--MANIFEST.MF 中 Class-Path 加入资源文件目录 -->
							<Class-Path>./resources/</Class-Path>
						</manifestEntries>
					</archive>
					<outputDirectory>${project.build.directory}/dist</outputDirectory>
				</configuration>
			</plugin>

拷贝依赖的jar包到lib目录下:

<!--拷贝依赖 copy-dependencies -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>
								${project.build.directory}/dist/lib/
							</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>

拷贝资源文件到指定目录:

<!--拷贝资源文件 copy-resources -->
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-resources</id>
						<phase>package</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<resources>
								<resource>
									<directory>src/main/resources</directory>
								</resource>
							</resources>
							<outputDirectory>${project.build.directory}/dist/resources</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>

spring boot repackage,依赖 maven-jar-plugin 打包的jar包 重新打包成 spring boot的jar包:

<!--spring boot repackage,依赖 maven-jar-plugin 打包的jar包 重新打包成 spring boot 
				的jar包 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<!--重写包含依赖,包含不存在的依赖,jar里没有pom里的依赖 -->
					<includes>
						<include>
							<groupId>null</groupId>
							<artifactId>null</artifactId>
						</include>
					</includes>
					<layout>ZIP</layout>
					<!--使用外部配置文件,jar包里没有资源文件 -->
					<addResources>true</addResources>
					<outputDirectory>${project.build.directory}/dist</outputDirectory>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
						<configuration>
							<!--配置jar包特殊标识 配置后,保留原文件,生成新文件 *-run.jar -->
							<!--配置jar包特殊标识 不配置,原文件命名为 *.jar.original,生成新文件 *.jar -->
							<!--<classifier>run</classifier> -->
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>

打包静态资源文件:

<!-- jsp 404解决 -->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<targetPath>${project.build.directory}/dist/resources</targetPath>
				<includes>
					<include>**/*.*</include>
				</includes>
			</resource>
			<!-- 打包时将jsp文件拷贝到META-INF目录下 -->
			<resource>
<!-- 				jsp所在的根目录,相当于以前的webroot -->
				<directory>src/main/webapp</directory>
<!-- 				必须打包到此目录,不仅仅限于jsp文件,而是所有格式的文件全部复制 -->
				<targetPath>META-INF/resources</targetPath>
				<includes>
					<include>**/*.*</include>
				</includes>
			</resource>
		</resources>
		<!-- jsp 404解决 -->

打包后的目录结构:

可运行jar包目录结构:


版权声明:本文为m0_37631110原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。