I have the following configuration for serving static content from Spring Boot.
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Value("${frontend.location}")
private String frontendLocation;
#Override
public void addViewControllers(ViewControllerRegistry reg) {
reg.addViewController("/").setViewName("forward:/index.html");
reg.addViewController("/{x:[\\w\\-]+}").setViewName("forward:/index.html");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(frontendLocation);
}
}
This works fine as long as there is no server.servlet.context-path. When server.servlet.context-path is configured, it is being passed down to the frontend router as part of the URL.
The solution would be not to forward context path to index.html. How can I achieve that?
Related
As now I've always served my images through a static path in the application.properties file:
spring.resources.staticlocations=file:/Applications/MAMP/htdocs/reportMaker/template
spring.mvc.static-path-pattern=/resources/**
Then by doing
http://localhost:8080/resources/logo.png
I'm able to reach the logo.
Now my aim is to switch with a folder path taken from my DB.
I've tried this approach:
#EnableWebMvc
#Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
#Autowired
ConfigurationRepository confRepo;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
myConfiguration conf = confRepo.findByConfKey("downloadPath");
String path = conf.getConfValue();
if(path !=null) {
registry.addResourceHandler("/resources/**").addResourceLocations(path);
}
}
But I can't reach the logo in same way as before.
The path variable is /Applications/MAMP/htdocs/reportMaker/template.
The path variable is /Applications/MAMP/htdocs/reportMaker/template.
According to this documentation https://www.baeldung.com/spring-mvc-static-resources the path should be prefixed by file:/
I've resolved by removing: #EnableWebMvc and adding a / at the end of my path
#Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("file:/Applications/MAMP/htdocs/reportMaker/template/");
}
}
I want to completely remove CORS from Spring Boot (2.3.3.RELEASE) with Spring Security.
There is WebSecurityConfigurerAdapter#configure method for HttpSecurity object where I can call cors().disable() but it seems not to work.
class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable();
}
}
With just above snippet I still get CORS errors while accessing endpoints from my frontend application.
Instead of that I have to override addCorsMappings from WebMvcConfigurer interface like below 👇.
Why is that? Why it is not enough to call http.cors().disable()?
class MySecurityConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*");
}
Hi you need to create a global cors configuration in your spring boot project.Create a class and annotate it with #Configuration. You can follow this example below.
#Configuration
public class MyConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
};
}
}
Here is the full guide that spring framework provides https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
I have set the context path for tomcat as follows:
#Component
public class CustomContainer implements
WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
#Override
public void customize(TomcatServletWebServerFactory factory) {
factory.setContextPath("/capripol");
factory.setPort(8080);
}
}
Navigating to localhost:8080/capripol works fine and I am prompted with my login screen, however after logging in my forms and controllers do not append to the context path, so instead of navigating to /capripol/MainMenu etc. they navigate to /MainMenu. How do I set the context path such that my form actions and controllers will be appended do it - why is the tomcat factory context path not setting?
Edit: My Application class
#SpringBootApplication
public class CapripolApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(CapripolApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CapripolApplication.class);
}
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/", "classpath:/images/")
.setCachePeriod(0);
}
}
}
A few ways to do it. You can add it to each controller, usefully if you want to change the context path
#Controller
#RequestMapping(value = "/foo")
public class bar{
#GetMapping(value = "/bar")
public void stuff(){
//doing stuff
}
}
Or you can put it in your application.properties / yml
server.servlet.contextPath=/foo/*
There are technically some other more round about ways to do it, especially if you are using an older version of Spring, but I would think the application properties is what you are looking for.
I'm new to web sockets so iv'e a few question. Since im using WebSocketConfigurer Interface with code implemented below:
#Configuration
#EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer{
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(this.socketHandler(), "/socket")
.addInterceptors(new AuthInterceptor())
.setAllowedOrigins("*")
.withSockJS();
}
#Bean
public WebSocketHandler socketHandler() {
return new PerConnectionWebSocketHandler(socketHandler.class);
}
}
1) Can i somehow add Controller that will listen to my /socket and execute commands when some1 sends message with destination /topic/user
something like:
#Controller
public class TestController {
#MessageMapping("/user")
#SendTo("/topic/user")
public String test() {
//TODO: do something usefull
}
}
You have to create one more configuration
#Configuration
#RequiredArgsConstructor
public class WebConfiguration implements WebMvcConfigurer {
....
}
While implementing the interceptors in my spring boot application I came across a weird problem which is as follows:
My Application class code:
#Import(CommonConfig.class)
#EnableAsync
#SpringBootApplication
#EnableSwagger2
#EnableScheduling
#EnableSpringDataWebSupport
#ImportResource({ "classpath:META-INF/applicationContext.xml" })
#AutoConfigureAfter(WebMvcAutoConfiguration.class)
public class Application extends SpringBootServletInitializer {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
.......
................
}
#Bean
public TokenInterceptor intializeTokenInterceptor() {
System.out.println("Adding interceptors");
return new TokenInterceptor();
}
#Bean
public WebMvcConfigurerAdapter adapter() {
return new WebMvcConfigurerAdapter() {
#Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("Adding interceptors");
registry.addInterceptor(intializeTokenInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
};
}
}
Inside my application-context I have mentioned tag (mvc:annotation-driven) as I need this for initializing my bean classes.
Now, if I test my application by removing the annotation-driven tag, my interceptors are getting called. However, if I keep this tag, my interceptors are not getting called, (which I believe is overriding the implementation of WebMvcConfigurerAdapter bean from WebMvcAutoConfiguration.class somehow).