Сервлет [dispatcherServlet] в контексте с путем [] выдал исключение [Путь кругового просмотра [логин]JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Сервлет [dispatcherServlet] в контексте с путем [] выдал исключение [Путь кругового просмотра [логин]

Сообщение Anonymous »

Я новичок в Spring Boot, но пытаюсь скомпилировать и запустить старый Java-код Spring Boot, который выдает следующую ошибку:

Servlet. service() для сервлета [dispatcherServlet] в контексте с путем [] выдал исключение [Путь кругового просмотра [логин]: снова отправит обратно на текущий URL-адрес обработчика [/login]. Проверьте настройку ViewResolver! (Подсказка: это может быть результатом неопределенного представления из-за генерации имени представления по умолчанию.)] с основной причиной

Мой файл login.jsp такой: следует:

Код: Выделить всё







Username


Password



Log in

и мой WebSecurityConfig.java выглядит следующим образом:

Код: Выделить всё

package elements.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

private final PasswordEncoder passwordEncoder;

@Autowired
public WebSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
return http.build();
}

@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder encoder) {
var usr1 = User.builder()
.username("user1ka")
.password(encoder.encode("y445uri125"))
.roles("USER")
.build();
var usr2 = User.builder()
.username("user2ka")
.password(encoder.encode("sa678sha769"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(usr1, usr2);
}
}
и мой loginController.java выглядит следующим образом:

Код: Выделить всё

package elements.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

@RequestMapping(
value = "/login",
method = {RequestMethod.GET,  RequestMethod.POST})
public String login() {
return "login";
}

}
что вызывает вышеуказанную ошибку и как ее устранить?
Я обновил код в соответствии с ответом @M.Deinum следующим образом :

Код: Выделить всё

package elements.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.requestMatchers("/error").permitAll() // Allow access to /error without authentication
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
return http.build();
}

@Bean
public InMemoryUserDetailsManager userDetailsService() {
var usr1 = User.builder()
.username("user1ka")
.password("y445uri125")
.roles("USER")
.build();
var usr2 = User.builder()
.username("user2ka")
.password("sa678sha769")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(usr1, usr2);
}
}
К сожалению, проблема все еще сохраняется, и некоторые полезные журналы DEBUG выглядят следующим образом:

Код: Выделить всё

2024-10-15 21:51:49.306 [main] INFO  elements.config.WebApplication - Started WebApplication in 12.548 seconds (process running for 14.262)
2024-10-15 21:51:49.561 [main] DEBUG o.s.b.a.ApplicationAvailabilityBean - Application availability state LivenessState changed to CORRECT
2024-10-15 21:51:49.583 [main] DEBUG o.s.b.a.ApplicationAvailabilityBean - Application availability state ReadinessState changed to ACCEPTING_TRAFFIC
2024-10-15 21:52:00.111 [http-nio-8080-exec-1] INFO  o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-10-15 21:52:00.112 [http-nio-8080-exec-1] INFO  o.s.web.servlet.DispatcherServlet - Initializing Servlet 'dispatcherServlet'
2024-10-15 21:52:00.112 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Detected StandardServletMultipartResolver
2024-10-15 21:52:00.112 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Detected AcceptHeaderLocaleResolver
2024-10-15 21:52:00.112 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Detected FixedThemeResolver
2024-10-15 21:52:00.113 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@70047c84
2024-10-15 21:52:00.113 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Detected org.springframework.web.servlet.support.SessionFlashMapManager@a489205
2024-10-15 21:52:00.115 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - enableLoggingRequestDetails='false':  request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2024-10-15 21:52:00.116 [http-nio-8080-exec-1] INFO  o.s.web.servlet.DispatcherServlet - Completed initialization in 4 ms
2024-10-15 21:52:00.242 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - Securing GET /login
2024-10-15 21:52:00.314 [http-nio-8080-exec-1] DEBUG o.s.security.web.FilterChainProxy - Secured GET /login
2024-10-15 21:52:00.319 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - GET "/login", parameters={}
2024-10-15 21:52:00.323 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to elements.controllers.LoginController#login()
2024-10-15 21:52:00.391 [http-nio-8080-exec-1] DEBUG o.s.w.s.v.ContentNegotiatingViewResolver - Selected 'text/html' given [text/html, application/xhtml+xml, image/avif, image/webp, image/png, image/svg+xml, application/xml;q=0.9, */*;q=0.8]
2024-10-15 21:52:00.392 [http-nio-8080-exec-1] DEBUG o.s.w.s.view.InternalResourceView - View name [login], model {}
2024-10-15 21:52:00.394 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Error rendering view [org.springframework.web.servlet.view.InternalResourceView: name [login]; URL [login]]
jakarta.servlet.ServletException: Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
.
.
.
2024-10-15 21:52:00.417 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Failed to complete request: jakarta.servlet.ServletException: Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
2024-10-15 21:52:00.419 [http-nio-8080-exec-1] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Set SecurityContextHolder to anonymous SecurityContext
2024-10-15 21:52:00.422 [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause
jakarta.servlet.ServletException: Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
Большое спасибо за вашу помощь, это очень ценно.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ircular-vi
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»