ฉันมีแอปพลิเคชัน Spring Boot พร้อม Spring Security ในระดับพื้นฐาน มันค่อนข้างจะเข้ากันกับอันจากบทช่วยสอนของ Spring คำถามของฉันคือ เมื่อฉันไปที่หน้าแรก มันจะเรียกตัวควบคุมการเข้าสู่ระบบ (สองครั้ง) ทำไม ไม่ชัดเจนว่าจะดำเนินการดังกล่าวด้วยการตั้งค่าพื้นฐาน เนื่องจากเป็นเพียงการแสดงหน้าแรกเท่านั้น แต่ถ้าฉันเพิ่มคลาส LoginController มันจะถูกเรียก (สองครั้ง) เมื่อโหลดหน้าแรก อีกวิธีในการดูสิ่งนี้คือการเพิ่มแท็ก thymeleaf ที่ไม่ถูกต้องลงในเทมเพลต login.html ซึ่งจะทำให้เกิดข้อผิดพลาด แม้ว่าหน้าแรกจะไม่ได้รับการตรวจสอบสิทธิ์ก็ตาม คำอธิบายใด ๆ ที่จะช่วยได้
รหัสของฉัน:
แอปพลิเคชัน:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
การกำหนดค่าความปลอดภัยบนเว็บ:
@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");
}
}
ตัวควบคุมหน้าแรก:
@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";
}
}