【发布时间】:2014-08-20 18:08:58
【问题描述】:
我创建了一个基于this tutorial 的小型网络应用程序。原始版本按预期工作。然后我做了一些更改,但它停止了工作,也就是说我可以在不登录的情况下访问 /hello 页面。我正在学习这个神奇的自动配置世界,我想了解我的代码和原始代码之间的关键区别在哪里。
所以我有了初始化程序,因为我不需要 main 的东西,我只想要一个 webapp:
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class, SecurityConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
然后我有这个:
//@EnableWebMvc
// I tried with and without this annotation, no difference
// I guess as I extend WebMvcConfigurerAdapter I don't need this
@ComponentScan
@Configuration
@EnableAutoConfiguration
public class WebConfig {
}
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
最后是安全部分:
@配置 @EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home").permitAll()
.anyRequest().authenticated();
http.formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
}
@Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
}
这些类都在同一个包中。如果有人向我解释这不起作用的原因,我会很高兴。
【问题讨论】:
-
当你说“我不需要
main的东西,我只想要一个 webapp”时,你的意思是你正在创建一个战争文件并将其部署在外部(即不是-嵌入式)容器?如果是这样,您是否像在这个spring guide 中那样做?
标签: java spring spring-mvc spring-security spring-boot