Spring 4.x Java-Codebasierte Konfiguration: Statische Ressourcendateien und Dispatcher-Servlet [duplizieren]
Diese Frage hat hier bereits eine Antwort:
Annotation Configuration Ersatz für mvc: resources - Spring 2 AntwortenVor Servlet-Version 3.0 basieren alle Konfigurationen auf XML. Ich verwende derzeit eine Code / Annotation-basierte Konfiguration.
n der XML-Stil-Konfiguration haben wir
<mvc:resources mapping="/res/**" location="/res/" />
Wie kann ich es in eine codebasierte Konfiguration übersetzen? Ich erhalte ständig eine Fehlermeldung von der Eclipse-Debug-Konsole, dass für die Ressourcendatei kein Dispatcher-Servlet gefunden wurde.
BTW, hier ist meine Referenz,Migration von Spring Security 3.x nach 4.x (Java-Konfiguration)
initializer
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;
}
}
security config
@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();
}
}
security initializer
public class SecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
}
custom login
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);
}
}