背景:
因为硬件资源问题,且软件并发量不高,故开发阶段是前后端分离,但部署时,是将 前端编译后的包直接放在 springboot 的 static 目录下,maven 打包打成jar 后,将其作为静态资源文件可以被直接访问。
问题:
springboot 内部是tomcat 服务器,将前端包放在 springboot 的static 下后,除了根路径能被访问,其他 vue3 的动态路由都无法跳转(经过测试,这些动态路径是能被拦截器拦截的)。
解决方案:
将无效的路由(vue3的动态路径)都映射到 vue3 编译好的单文件上(即 index.html)
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author Rain
* 处理无效路由
*/
@Controller
public class MyBasicErrorController extends BasicErrorController {
@Autowired
public MyBasicErrorController(ErrorAttributes errorAttributes,
ServerProperties serverProperties,
List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, serverProperties.getError(), errorViewResolvers);
}
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
// 获取 Spring Boot 默认提供的错误信息,然后添加一个自定义的错误信息
Map<String, Object> model = Collections
.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
ModelAndView modelAndView = new ModelAndView("index.html", model, status);
return modelAndView;
}
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
// 获取 Spring Boot 默认提供的错误信息,然后添加一个自定义的错误信息
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
}