कस्टम 404 हैंडलर को लागू करने के लिए आप जो चाहते हैं उसे हासिल करने का सबसे आसान तरीका है।
अपने application.properties करने के लिए इन पैरामीटर जोड़ें:
spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true
पहले संपत्ति सभी डिफ़ॉल्ट स्थिर संसाधन से निपटने निकाल देता है, दूसरी संपत्ति (डिफ़ॉल्ट स्प्रिंग द्वारा NoHandlerFoundException
पकड़ता और मानक Whitelabel पेज में कार्य करता है) वसंत के डिफ़ॉल्ट Whitelabel पेज को निष्क्रिय
आपके आवेदन संदर्भ के लिए 404 हैंडलर जोड़ें:
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";
}
}
अंत आप (इस मामले में index.html) अपने स्थैतिक सामग्री की सेवा के लिए अपने कस्टम दृश्य समाधानकर्ता जोड़ने की आवश्यकता होगी पर
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;
}
}
आपका index.html
/resources/static/
निर्देशिका में रखा जाना चाहिए।
स्रोत
2016-08-18 21:29:47