springboot拦截请求路径_SpringBoot整合Ant Design Pro进行部署

本文详细介绍了如何将Ant Design Pro与SpringBoot整合,包括打包Ant Design Pro并将其静态文件放入Spring Boot的资源目录,配置Spring Boot访问静态资源,特别是解决js和css的加载问题,以及讨论了对404错误的处理策略,确保页面正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Ant Design Pro 打包

1.1 运行 build打包

$ npm run build

1.2 将打包生成的静态文件拷贝到spring boot 项目中

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

41d7bd20b242e2fbb2ba88a6694f32a2.png

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,错误页面如下:

4c9c4d77c24d1a36ba56e6abf4ad9adf.png

页面加载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 页面显示正常

a818455d69a3ec0eb4b90133d8f9e4be.png

login

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

52af0b7c0a57645148724dab0f2c88f2.png

后台界面

四、补充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

竟然都看到最后了,给小编点个关注吧,小编还会持续更新的,只收藏不点关注的都是在耍流氓!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值