SpringBoot整合Ant Design Pro进行部署

一、Ant Design Pro 打包

1.1 运行 build打包
$ npm run build
1.2 将打包生成的静态文件拷贝到spring boot 项目中

构建打包成功之后,会在根目录生成 dist 文件夹,然后将dist 文件夹里的的文件复制到 spring boot 项目的 /src/main/resources/static 目录下

resources/static目录

二、配置spring boot 项目可访问到static目录下的index.html

2.1 以gradle为例导入spring-boot-starter-thymeleaf
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.1.5.RELEASE'
2.2 在application.yml配置文件中配置
#配置html资源路径
spring:
  thymeleaf:
    prefix: classpath:static/
2.3 在controller配置访问地址
/**
 * @author Alan Chen
 * @description 拦截Ant Design Pro访问路径
 * @date 2019/5/24
 */
@Controller
public class AntDesignController {
    /**
     * 配置url通配符,拦截多个地址
     * @return
     */
    @RequestMapping(value = {
            "/",
            "/user",
            "/user/**",
            "/console",
            "/console/**"
    })
    public String fowardIndex() {
        return "index";
    }
}

注意:@Controller不是@RestController,使用@RestController会返回“index”字符串
输入地址 http://localhost:8080 、http://localhost:8080/user/login 都会转发到index.html,从而展示Ant Design Pro页面

2.4 配置spring boot 项目可访问到static目录下的js、css

尝试访问http://localhost:8080/user/login时,发现现在已经能访问到index.html了,但页面报错了,访问不到js和css,错误页面如下:

页面加载js报错

需要配置一下,让js、css等静态资源去static目录下去加载

@Configuration
@EnableWebMvc
public class UseStaticResourceConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
}

三、整合完成

再次访问http://localhost:8080/user/login 页面显示正常

login

访问http://localhost:8080/console/commodity/product-brand 显示后台界面

后台界面

四、补充2.3

关于2.3,网上有一种思路是这样的:

Ant Design构建完成后只有一个index.html页面和一些js、css文件,当使用browserHistory,如果直接放在Spring Boot的resource/static文件夹下面,当浏览器直接访问或者在非 "/ “,”/index"路径刷新时,由于服务器无法正确响应,会直接触发404报错。

解决思路:浏览器访问任何404错误路径都返回 /index.html文件。剩下的事情交给前端路由

@Controller
public class AntDesignController implements ErrorController {
    @Override
    public String getErrorPath(){
        return "/error";
    }

    @RequestMapping(value = "/error")
    public String getIndex(){
        return "index"; //返回index页面
    }

}

这种方式也能实现效果,但这种方式使得所有的错误请求(404)都会被拦截跳转到index.html ,其实不太严谨,而且给人的感觉是,先让其“出错”,再来“补救”

参考官方文档:Ant Design Pro

你可能感兴趣的:(SpringBoot整合Ant Design Pro进行部署)