对于不是以/ 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 !!"; }}


