Inserting an image from local directory in thymeleaf spring framework (with maven)

前端 未结 6 1504
北荒
北荒 2020-12-09 17:19

I have developed a project using this link: https://spring.io/guides/gs/serving-web-content/ I used maven to develop above project.

I have two html files under this.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 18:03

    Recently I had similar issue, but in my case, the spring security was making a problem. As mentioned in other answers and documentation:

    Media Resource
    

    should be enough. But since the spring security has been added to my project, I had to all /img/ ** for get Requests and add addResourceHandlers. Here is the code:

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler(
                    "/webjars/**",
                    "/img/**",
                    "/css/**",
                    "/js/**")
                    .addResourceLocations(
                            "classpath:/META-INF/resources/webjars/",
                            "classpath:/static/img/",
                            "classpath:/static/css/",
                            "classpath:/static/js/");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http.csrf().disable();
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    
            http.authorizeRequests().antMatchers(HttpMethod.GET, "/js/**", "/css/**", "/img/**" ,"/pressiplus", "/public/**", "/index", "/", "/login").permitAll();
            http.authorizeRequests()
                    .antMatchers("/secure/admin/**").hasAnyRole("ADMIN","USER")
                    .antMatchers("/secure/admin/**").hasAnyRole("ADMIN")
                    .and()
                    .formLogin()  //login configuration
                        .loginPage("/login")
                        .failureUrl("/login-error")
                        .loginProcessingUrl("/login")
                        .usernameParameter("email")
                        .passwordParameter("password")
                        .successHandler(myAuthenticationSuccessHandler())
                    .and()
                    .logout()    //logout configuration
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(myLogoutSuccessHandler)
                    .and()
                        .rememberMe()
                            .tokenRepository(persistentTokenRepository())
                            .tokenValiditySeconds(7 * 24 * 60 * 60) // expires in 7 days
                    .and()
                        .exceptionHandling() //exception handling configuration
                    .accessDeniedHandler(accessDeniedHandler());
        }
    
    }
    

    I hope this helps someone in the future

提交回复
热议问题