Cách dễ nhất để đạt được những gì bạn muốn là triển khai trình xử lý 404 tùy chỉnh.
Thêm các params để application.properties của bạn:
spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true
bất động sản đầu tiên loại bỏ tất cả các xử lý tài nguyên tĩnh mặc định, tài sản thứ hai vô hiệu hóa trang Nhãn trắng mặc định Spring (bởi Spring mặc định bắt NoHandlerFoundException
và phục vụ trang Nhãn trắng tiêu chuẩn)
Thêm handler 404 đến bối cảnh ứng dụng của bạn:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class PageNotFoundController {
@ExceptionHandler(NoHandlerFoundException.class)
public String handleError404() {
return "redirect:/index.html";
}
}
Vào cuối bạn sẽ cần phải thêm cái nhìn thống xử lý tuỳ chỉnh của bạn để phục vụ nội dung tĩnh của bạn (index.html trong trường hợp này)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/index.html").addResourceLocations("classpath:/static/index.html");
super.addResourceHandlers(registry);
}
@Bean
public ViewResolver viewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(InternalResourceView.class);
return viewResolver;
}
}
bạn index.html
nên được đặt trong thư mục /resources/static/
.
Nguồn
2016-08-18 21:29:47