Spring boot with redirecting with single page angular2

spring-boot-angular-deployment
angular 8 + spring boot login example
angular 2 with spring boot
angular 6 spring boot login example
angular 7 + spring boot login example
spring boot + angular 8
angular spring boot jwt authentication example
angular spring boot crud

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 correctly defaults to webapp folder and serves index.html file.

What I am looking to do is

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.

2) 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") can write shorthand in code  @RequestMapping("/home")

or

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

Edit.. More notes to explain above better

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 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.

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

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.

Update 15/05/2017

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

Background Using Spring Boot and Serving static resources from classpath

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

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

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

My Solution

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

Add following to application.properties

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

Add a ControllerAdvice as follows

@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.

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

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

Example

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

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

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 !!";
    }

}

Previous Answer

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.

Springboot/Angular2 - How to handle HTML5 urls?, static being a folder recognized by Spring Boot to load static resources. I add in a single ResourceHandler to the current ResourceHandlerRegistry . public String redirect() { // Forward to home page so that route is preserved. return  Spring Boot is one of the most popular frameworks for developing Java applications and REST APIs. It also has first-class support for Kotlin! Spring Boot 1.0 was released on April 1, 2014, and revolutionized the way Java developers write Spring apps.

Spring boot with redirecting with single page angular2 – Icetutor, 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  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more Serving Angular2 at a path with Spring Boot

Try this instead

@SpringBootApplication
@RestController
class YourSpringBootApp { 

    // Match everything without a suffix (so not a static resource)
    @RequestMapping(value = "/**/{path:[^.]*}")       
    public String redirect() {
        // Forward to home page so that route is preserved.
        return "forward:/";
    }
}

Serving Angular 6 with Spring Boot : Angular2, I first created A spring boot static web gradle project and copied my angular One important thing to note here, is that you probably don't want to redirect the  static being a folder recognized by Spring Boot to load static resources. Then the idea is to customize the Spring MVC configuration. The simpler way is using Spring Java configuration. I implement WebMvcConfigurer to override addResourceHandlers(). I add in a single ResourceHandler to the current ResourceHandlerRegistry.

@Controller
public class RedirectController {
    /*
     * Redirects all routes to FrontEnd except: '/', '/index.html', '/api', '/api/**'
     */
    @RequestMapping(value = "{_:^(?!index\\.html|api).*$}")
    public String redirectApi() {
        return "forward:/";
    }
}

Tutorial, to use Spring Security with Angular in a "single page application". Following the steps in Part I we can begin with Spring Boot Initializr. Click on the "login" link and you will be redirected to the  I'm trying to get an Angular2 app served up through a springboot web application. Stack Overflow Public questions and Spring boot with redirecting with single

The solution that works to me is to overwrite the BasicErrorController of Spring Boot:

@Component
public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, new ErrorProperties());
    }

    @RequestMapping(produces = "text/html")
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NOT_FOUND) {
            return new ModelAndView("forward:/");
        } else {
            return super.errorHtml(request, response);
        }
    }
}

The method errorHtml only intercepts not found requests and is transparent for responses 404 (not found) from the api.

Make Spring Boot surrender routing control to Angular, In a multi module application Spring Boot should surrender routing control to access any route other than the root page will result in a Whitelabel Error Page: The following code is responsible for redirecting all requests to the index.html solutions but none of them worked, this one worked like a charm. npm install -g angular-cli to install angular 2 cli ( globally ) npm install to install Node packages; How to Run Backend . mvn clean install to clean if exists files and install packages; mvn spring-boot:run to start spring boot; Frontend . ng serve; Screenshots of Demo Angular2+SpringBoot+Mysql CRUD Example Detail/View person Delete person Edit person

How to work with Angular Routing, How to use Angular Http Client to fetch Data from SpringBoot RestAPI – Angular 4 our app will always redirect to http://localhost:4200/jsa/customer with customer-list view. Press on Back button, the browser's url will be backed one step to first page works fine, but remaining routing is not working. Spring and the Single Page Application HTML5, rich browser-based features, and the “single page application” are extremely valuable tools for modern developers, but any meaningful interactions will involve a backend server, so as well as static content (HTML, CSS and JavaScript) we are going to need a backend server.

Building a Web Application with Spring Boot and Angular, Spring Boot and Angular form a powerful tandem that works great for developing With our demo Spring Boot application up and running, let's now create a simple Angular method after the insertion, which redirects the user to the /users path. We use cookies to improve your experience with the site. I told you that because i already got same problem with spring boot and security, then i had to setup the password from the logs, an auto generated password of 20-24 characters, then i was able to work normally with the app and will be redirect. – cralfaro May 16 '16 at 12:26

Spring Security Login Page with Angular, Spring REST Tutorials · Spring MVC Tutorials · Spring Boot Tutorials · Spring Cloud Tutorials · Spring 5 In this tutorial, we'll be creating a login page using Spring Security with: AngularJS; Angular 2, 4, 5, and 6 Angular uses a single page architecture where all the child components (in our case these  I have rest service protected by spring security oauth2. Angular2 app is served from src/main/resources/static and it all works well. Basically all i need is tomcat to fire up initial index.html p

Comments
  • you can have a look into this, mkyong.com/spring-boot/spring-boot-how-to-change-context-path
  • You can try creating a custom annotation which will include @RequestMapping("/api") and apply that to your api controllers. Then use @RequestMapping on methods for specific urls.
  • This looks close to what I am looking for. However it has stopped serving the static content inside webapp? returns ERR_TOO_MANY_REDIRECTS
  • Too many redirects can be due to your Spring Security configuration. Can u share TRACE logs ?
  • I have spring security disabled.. I added logging on doFilter method and it keeps going back to itself.. Its seems to me that it has disabled some of the default spring boot behaviour that resolved to /webapp/index.html.. its stuck in a loop.
  • I have added trace here. You can see the passed one (before adding redirect filter) and the failed one. plnkr.co/edit/McziX5tI179dHiynSw1t?p=preview
  • Ohh !! my bad. For your work, you don't even need a filter. Basically, you want to redirect all 404 to index.html. Rest of the requests will be managed by Spring Resource Handling Mapper. If somebody hits /api/1 - corresponding it will be matched with /api/** and the corresponding controller will be called. On the other hand, if someone hits /xxx and it is not available in your static resources, the servlet will throw 404.
  • Note also that this needs to be annotated with @Controller. @RestController will not work.
  • Are you god? wow... I expend so much time!! thank you very much bro!
  • Just His servant :-) glad the answer helped you.
  • what does the regex "/{[path:[^\\.]*}" match against?.. looks like it matches anything and forwards it to / ... how would this not capture the /api requests?
  • Match everything without a suffix (so not a static resource)
  • answser to @Robbo_UK : convention: all paths that do not contain a period (and are not explicitly mapped already) are Angular routes, and should forward to the home page. Source spring.io/blog/2015/05/13/…