栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带单页angular2重定向的Spring Boot

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带单页angular2重定向的Spring Boot

对于不是以/ api开头的每个本地REST请求,请覆盖并重定向
到默认的webapp / index.html。我计划将任何/ api服务提供给spring
控制器。

更新15/05/2017

让我为其他读者重新表达您的查询。(如果误解了,请纠正我)

使用Spring Boot并从classpath提供静态资源的后台

要求
所有

404
非api请求都应重定向到
index.html

NON API-表示URL开头不为的请求

/api

API -404应该
404
照常抛出。

示例响应

/api/something
-将抛出404
/index.html-
将服务器index.html-
/something
重定向到index.html

我的解决方案

如果
给定资源没有可用的处理程序,则让Spring MVC引发异常。

将以下内容添加到

application.properties

spring.mvc.throw-exception-if-no-handler-found=truespring.resources.add-mappings=false

添加ControllerAdvice如下

@ControllerAdvicepublic class RedirectonResourceNotFoundException {    @ExceptionHandler(value = NoHandlerFoundException.class)    public Object handleStaticResourceNotFound(final NoHandlerFoundException ex, HttpServletRequest req, RedirectAttributes redirectAttributes) {        if (req.getRequestURI().startsWith("/api")) return this.getApiResourceNotFoundBody(ex, req);        else { redirectAttributes.addFlashAttribute("errorMessage", "My Custom error message"); return "redirect:/index.html";        }    }    private ResponseEntity<String> getApiResourceNotFoundBody(NoHandlerFoundException ex, HttpServletRequest req) {        return new ResponseEntity<>("Not Found !!", HttpStatus.NOT_FOUND);    }}

您可以根据需要自定义错误消息。

有没有一种方法可以为所有控制器加上api前缀,这样我就不必每次都写api。

为此,您可以创建一个

baseController
并将RequestMapping路径设置为
/api

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping("/api")public abstract class baseController {}

并延长这个

baseController
,并确保你没有注释子类
@RequestMapping

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class FirstTestController extends baseController {    @RequestMapping(path = "/something")    public String sayHello() {        return "Hello World !!";    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/382808.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号