2016-08-23 47 views
0

我有Spring Security的Spring Boot應用程序。在基本層面上,它與Spring教程中的很相似。我的問題是,當我點擊主頁時,它會調用登錄控制器(兩次)。爲什麼?由於它只是顯示主頁,因此在基本設置中它並不是顯而易見的。但是,如果我添加一個LoginController類,它會在加載主頁時調用(兩次)。看到這個的另一種方法是在login.html templage中添加一個無效的thymeleaf標籤,它會引發錯誤,即使主頁不應該被認證。任何解釋都會有幫助。Spring Boot與Spring Security應用程序在加載主頁時調用登錄控制器

我的代碼:

應用:

@SpringBootApplication 
public class Application { 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

WebSecurityConfig:

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
      .logout() 
       .permitAll(); 
    } 

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

的HomeController:

@Controller 
public class HomeController { 
    @RequestMapping(value="/", method=RequestMethod.GET) 
    public String getHomePage(Model model) { 
     return "home"; 
    } 
} 

可選的LoginController,將被調用時,伊特荷蘭國際集團的主頁:

@Controller 
public class LoginController { 
    @RequestMapping(value="/login", method=RequestMethod.GET) 
    public String getLoginPage(Model model) { 
     return "login"; 
    } 
} 
+0

當您加載主頁時,您是如何確認登錄控制器被調用過兩次的?從日誌? (如果是這樣,你可以分享日誌)。 – rhinds

+0

放了一個斷點,或只是一個打印語句......它實際上被調用一次,一定是我的HTML中的東西,導致它被調用兩次,但現在它被調用一次。 – ikcodez

回答

0

你或許應該在LoginController添加一個RequestMapping

但是,爲什麼你有一個HomeControllerLoginController當你已經在addViewControllers這些映射?

+0

抱歉,格式不正確...糾正了它。問題是,爲什麼登錄控制器會被調用,更重要的是,它爲什麼會呈現login.html模板(或者似乎是這樣做,並且兩次)? – ikcodez

+0

可能與您登錄/家庭模板中的任何鏈接有關。例如,您可以鏈接到由安全配置阻止的image/js/css文件。 –

+0

進行測試,我的家庭模板只是 – ikcodez

相關問題