解决第二个问题的方式是对vue的路由的路径做rewrite,交给router来处理,而不是springboot自己处理,rewrite时可以考虑路由的路径统一增加后最,然后在springboot中编写过滤拦截特定后缀来做请求转发交给vue的路由处理。如:
const router = new VueRouter({
mode: ‘history’,
base: __dirname,
routes: [
{
path: ‘/ui/first.vhtml’,
component: First
},
{
path: ‘/ui/second.vhtml’,
component: secondcomponent
}
]
})
后端拦截到带有vhtml的都交给router来处理,这种方式在后端写过滤器拦截后打包是完全可行的,但是前端开发的直接访问带后缀的路径会有问题。
另外一种方式是给前端的路由path统一加个前缀比如/ui,这时后端写过滤器匹配该前缀,也不会影响前端单独开发是的路由解析问题。过滤器参考如下:
public class RewriteFilter implements Filter {
public static final String REWRITE_TO = “rewriteUrl”;
public static final String REWRITE_PATTERNS = “urlPatterns”;
private Set urlPatterns = null;//配置url通配符
private String rewriteTo = null;
@Override
public void init(FilterConfig cfg) throws ServletException {
//初始化拦截配置
rewriteTo = cfg.getInitParameter(REWRITE_TO);
String exceptUrlString = cfg.getInitParameter(REWRITE_PATTERNS);
if (StringUtil.isNotEmpty(exceptUrlString)) {
urlPatterns = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(exceptUrlString.split(";", 0))));
} else {
urlPatterns = Collections.emptySet();
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String servletPath = request.getServletPath();
String context = request.getContextPath();
//匹配的路径重写
if (isMatches(urlPatterns, servletPath)) {
req.getRequestDispatcher(context+"/"+rewriteTo).forward(req, resp);
}else{
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
private boolean isMatches(Set patterns, String url) {
if(null == patterns){
return false;
}
for (String str : patterns) {
if (str.endsWith("/*")) {
String name = str.substring(0, str.length() - 2);
if (url.contains(name)) {
return true;
}
} else {
Pattern pattern = Pattern.compile(str);
if (pattern.matcher(url).matches()) {
return true;
}
}
}
return false;
}
}
过滤器的注册:
@SpringBootApplicat
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
开源完整内容戳这里
ion
public class SpringBootMainApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMainApplication.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, “/errors/401.html”);
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, “/errors/404.html”);
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, “/errors/500.html”);
container.addErrorPages(error401Page, error404Page, error500Page);
});
}
@Bean
public FilterRegistrationBean testFilterRegistration() {
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)