Spring 4.x基于Java代码的配置:静态资源文件和Dispatcher servlet

时间:2015-04-08 12:53:03

标签: spring spring-mvc servlets

在servlet 3.0版之前,所有配置都是基于xml的。 我目前正在使用基于代码/注释的配置。

在xml样式配置中,我们有

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

如何将其转换为基于代码的配置?我一直收到来自eclipse调试控制台的错误,即没有找到资源文件的调度程序servlet。

BTW,这是我的参考,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 config

@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);
    }
}

1 个答案:

答案 0 :(得分:4)

您可以从WebMvcConfigurerAdapter延伸并覆盖addResourceHandlers方法

@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/");
    }
}