具有单页angular2重定向的Spring Boot [英] Spring Boot with redirecting with single page angular2

查看:178
本文介绍了具有单页angular2重定向的Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Spring Boot的单页Angular应用程序.看起来如下:

I have a single page Angular app with Spring Boot. It looks like the following:

src
  main
  java
    controller
       HomeController
       CustomerController
       OtherController
  webapp
    js/angular-files.js
    index.html

Spring Boot正确默认为webapp文件夹,并提供index.html文件.

Spring boot correctly defaults to webapp folder and serves index.html file.

我想要做的是:

  1. 对于每个以/api开头的本地REST请求, not 覆盖并重定向到默认的webapp/index.html.我打算将任何/api都提供给spring控制器.

  1. For every local REST request not starting with /api overwrite and redirect to default webapp/index.html. I plan to serve anything /api to the spring controllers.

是否可以为所有控制器添加API前缀,这样我就不必每次都写API? 例如

Is there a way to prefix all controllers with API so that I do not have to write API every time? e.g.

@RequestMapping("/api/home")可以用代码@RequestMapping("/home")

@RequestMapping("/api/home") can write shorthand in code @RequestMapping("/home")

@RequestMapping("/api/other-controller/:id") can write shorthand  @RequestMapping("/other-controller/:id")

我正在寻找每个API请求,例如1) http://localhost:8080/api/home 保持API与API并解决以纠正控制器并返回JSON,但是如果有人输入 http:///localhost/some-url http:///localhost/some-other/123/url ,它将为索引提供服务.html页面并保留网址.

I'm looking for every API request, e.g. 1) http://localhost:8080/api/home keep API with API and resolve to correct controller and return JSON, however if someone enters a URL like http:///localhost/some-url or http:///localhost/some-other/123/url then it will serve the index.html page and keep the URL.

替代方法:尝试添加#ErrorViewResolver: Springboot/Angular2-如何处理HTML5 url?

Alternative ways to do it: try adding #ErrorViewResolver: Springboot/Angular2 - How to handle HTML5 urls?

推荐答案

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

For every local REST request not starting with /api overwrite and redirect to default webapp/index.html. I plan to serve anything /api to the spring controllers.

更新15/05/2017

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

Let me re-phrase your query for other readers. (Correct me, if misunderstood)

背景
使用Spring Boot并从类路径提供静态资源

Background
Using Spring Boot and Serving static resources from classpath

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

Requirement
All 404 non api requests should be redirected to index.html.

NON API -表示URL开头不是/api的请求.
API -404应该照常抛出404.

NON API - means Requests in which URL doesn't start with /api.
API - 404 should throw 404 as usual.

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

Sample Response
/api/something - will throw 404
/index.html - will server index.html
/something - will redirect to index.html

我的解决方案

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

Let the Spring MVC throw exceptions, if any handler is not available for the given resource.

将关注添加到application.properties

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

按如下所示添加ControllerAdvice

@ControllerAdvice
public 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);
    }
}

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

You can customize the error message as you like.

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

Is there a way to prefix all controllers with api so that I do not have to write api every time.

为此,您可以创建一个BaseController并将RequestMapping路径设置为/api

For this, you can create a BaseController and set the RequestMapping path to /api

示例

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api")
public abstract class BaseController {}

并扩展此BaseController,并确保您不要使用@RequestMapping

And extend this BaseController and make sure you do not annotate child class with @RequestMapping

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FirstTestController extends BaseController {
    @RequestMapping(path = "/something")
    public String sayHello() {
        return "Hello World !!";
    }

}

上一个答案

您可以创建一个Filter,如果请求路径不是以/api开始的,则可以重定向到/index.html.

You can create a Filter which redirects to /index.html if request path doesn't startsWith /api.

// CODE REMOVED. Check Edit History If you want.

这篇关于具有单页angular2重定向的Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆