Spring 4.x基于Java代码的配置:静态资源文件和Dispatcher Servlet [英] Spring 4.x Java code-based configuration: Static resource files and Dispatcher servlet

查看:58
本文介绍了Spring 4.x基于Java代码的配置:静态资源文件和Dispatcher Servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Servlet 3.0版之前,所有配置均基于xml. 我目前正在使用基于代码/注释的配置.

Prior to servlet version 3.0, all configuration are xml based. I'm currently using code/annotation based configuration.

在xml样式配置中,我们有

In xml style configuration, we have

<mvc:resources mapping="/res/**" location="/res/" />

如何将其转换为基于代码的配置?我不断从Eclipse调试控制台收到错误消息,即找不到资源文件的调度程序servlet.

How can I translate it into code based configuration? I keep receiving error from eclipse debug console that there is no dispatcher servlet found for resource file.

顺便说一句,这是我的参考资料,

BTW, here is my reference, Migrating from Spring Security 3.x to 4.x (Java Configuration)

初始化器

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MvcConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

mvc配置

@EnableWebMvc
@ComponentScan({ "com.appname.controller" })
public class MvcConfig {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password")
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/res/**").permitAll()
            .and().authorizeRequests()
            .anyRequest().hasRole("USER")
            .and().formLogin().loginPage("/account/signin").permitAll()
            .and().logout().permitAll();
    }
}

安全初始化程序

public class SecurityInitializer extends
        AbstractSecurityWebApplicationInitializer {

}

自定义登录

public class CustomUserDetailsService implements UserDetailsService {

    private AccountRepository accountRepository;

    public CustomUserDetailsService() {
        this.accountRepository = new AccountRepository();
    }

    @Override
    public UserDetails loadUserByUsername(String email)
            throws UsernameNotFoundException {

        Account account = accountRepository.getAccountByEmail(email);

        if (account == null) {
            throw new UsernameNotFoundException("Invalid email/password.");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("USER"));

        return new User(account.getEmail(), account.getPassword(), authorities);
    }
}

推荐答案

您可以从

You can extend from WebMvcConfigurerAdapter and override the addResourceHandlers method

@EnableWebMvc
@ComponentScan({"com.appname.controller"})
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/res/**")
                .addResourceLocations("/res/");
    }
}

这篇关于Spring 4.x基于Java代码的配置:静态资源文件和Dispatcher Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆