SpringBoot前后端分离 - 集成部署(打包)客户端

现在都流行使用 Aungular/React/Vue 开发Web应用。基本上客户端都是独立部署的,也就是前后端分离。

独立部署客户端,也就意味着更多的成本(硬件成本、维护成本)。

对于Spring Boot应用来说,项目初期,也可以把客户端一同打包进一个独立的jar包。

客户端 + 服务端,部署一个文件就行。省事也省心。但它仍然是名副其实的前后端分离架构(免去了跨域的问题)。

Spring Boot 静态资源配置

客户端程序文件布局。

|-assets 
      |-js
      |-css
|-favicon.ico        
|-index.html

yaml文件配置

spring:
  web:
    resources:
      static-locations:
        - file:${user.dir}/public/		# 程序运行目录
        - file:${user.home}/public/		# 用户home目录
        - classpath:/public/			# classpath目录

配置了3个静态资源目录。

不要把当前程序运行目录的根目录(file:${user.home} )作为静态资源目录,因为客户端能直接访问到可执行jar文件,比较危险。

视图映射配置

默认主页需要映射到客户端的主页index.html

某些路由也需要路由到前端,例如是论坛应用,请求地址 /post/{topicId}

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 
 * WebMvc
 * @author KevinBlandy
 *
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
	
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		/**
		 * 默认主页路由到前端
		 */
		registry.addViewController("/").setViewName("/index.html");
		/**
		 * /post 开头的请求,都路由到前端HTML
		 */
		registry.addViewController("/post/**").setViewName("/index.html");
	}
}

部署客户端

部署客户端到classpath目录下

image

启动应用程序后,访问 http://localhost,成功加载到了classpath下的index.html文件以及assets资源目录下的js文件。

访问 http://localhost/post/6666 也路由到了index.html

部署客户端到 ${user.home} 目录下

启动后访问 http://localhost ,也成功路由到了index.html

这个目录中新建了一个 /upload 目录,用于存储用户上传的文件数据。通过 /upload 访问。

总结

部署在classpath目录下,这种方式好处就是简单方便,缺点就是前端不能热部署。如果前端需要修改,则需要重新打包部署程序。部署在其他目录,这种好处就是比较灵活。修改客户端文件,不需要重新编译,部署程序。