Spring single page redirect download angular2

I have a single page angular app with spring loading. It looks like this

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

Spring loads correctly by default in the webapp folder and serves for the index.html file.

What I want to do is

1) For each local REST request , starting with / api does not overwrite and redirect the default webapp / index.html. I plan to use anything / api for spring controllers.

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

eg.

@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 better explain above.

api 1) http://localhost:8080/api/home api api json.

, - url http:///localhost/some-url http:///localhost/some-other/123/url index.html URL-.

enter image description here

- #ErrorViewResolver Springboot/ Angular2 - URL- HTML5?

+8
8

REST, /api, webapp/index.html. -/api spring.

15/05/2017

. ( , )


spring


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=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);
    }
}

, .

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;

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

}

Filter, /index.html, /api.

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

@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:/";
    }
}
+10

, - !

, , - PURE + angular 6, index.html REST API. @EnableWebMvc, @ControllerAdvice, application.properties, ResourceHandlerRegistry, :

* * ng build resources/static Spring. maven-resources-plugin. : Maven

@Controller
@SpringBootApplication
public class MyApp implements ErrorController {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "forward:/index.html";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

  • ng-build resources/static "forward: /index.html" "forward: /index.html" ("forward: /index.html"). , Spring - , , , .
  • ( @EnableWebMvc application.properties), @EnableWebMvc / @EnableWebMvc index.html ( resources/static), .
  • ( ) , , ErrorController /error , ErrorController - - index.html Angular .

+1

application.properties

server.contextPath =/API

"/api" URL- http://localhost:8080/api/home

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "/home");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    super.addViewControllers(registry);
}

WebMVCConfig.java

0

, :

api, api ?

: , "" @RequestMapping , :

@RestController
@RequestMapping("/api")
public class ApiController{

   @RequestMapping("/hello") 
   public String hello(){
      return "hello simple controller";
   }

   @RequestMapping("/hello2") 
   public String hello2(){
      return "hello2 simple controller";
   }
}

hello URL-: /api/hello

URL: /api/hello2

/api.

, :

- , /api?

, HTTP (302) Redirect, , angularJs "" REST , Java/ Spring, .

HTTP- 302, JS .

:

On AngularJS:

var headers = {'Content-Type':'application/json', 'Accept':'application/json'}

var config = {
    method:'GET'
    url:'http://localhost:8080/hello',
    headers:headers
};

http(config).then(
    function onSuccess(response){
        if(response.status == 302){
            console.log("Redirect");
            $location("/")
        }
}, function onError(response){
    console.log("An error occured while trying to open a new game room...");
});

Spring:

@RestController
@RequestMapping("/api")
public class ApiController{

   @RequestMapping("/hello") 
   public ResponseEntity<String> hello(){
      HttpHeaders header = new HttpHeaders();
      header.add("Content-Type", "application/json");
      return new ResponseEntity<String>("", header, HttpStatus.FOUND);
   }
}

, .

0

In the @Configuration bean, you can add a ServletRegistrationBean to make the spring server only for the / api / * resquest request, and then you don't need to add it in the controller.

@Bean
public ServletRegistrationBean dispatcherRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(
            dispatcherServlet());
    registration.addUrlMappings("/api/*");
    registration.setLoadOnStartup(1);
    registration.setName("mvc-dispatcher");
    return registration;
}
0
source
@Controller
public class RedirectController {
    /*
     * Redirects all routes to FrontEnd except: '/', '/index.html', '/api', '/api/**'
     */
    @RequestMapping(value = "{_:^(?!index\\.html|api).*$}")
    public String redirectApi() {
        return "forward:/";
    }
}
0
source

Source: https://habr.com/ru/post/1017169/


All Articles