Pagecontext request contextPath là gì

Bảo mật mùa xuân UserNotFoundException không hiển thị thông báo lỗi trong Spring Boot với mẫu xem JSP

1
Bushan Sirgur 2020-06-09 20:45.

Tôi đang tạo một ứng dụng web với Spring Boot và JSP. Tôi đã triển khai Spring Security và tôi đang ghi đè loadUserByUsername[]phương pháp này, khi người dùng không được tìm thấy, tôi sẽ gửi UsernameNotFoundException["User not found"]một thông báo. Bây giờ tôi muốn hiển thị một thông báo thích hợp trong trang đăng nhập của mình, làm cách nào để đạt được điều đó?

MyUserDetailsService.java

package in.bushansirgur.security.service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import in.bushansirgur.security.entity.Role; import in.bushansirgur.security.entity.User; @Service public class MyUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override @Transactional public UserDetails loadUserByUsername[String email] throws UsernameNotFoundException{ User user = userService.findUserByEmail[email]; if[user == null || user.getActive[] == null]{ throw new UsernameNotFoundException["User not found!"]; } List authorities = getUserAuthority[user.getRoles[]]; return buildUserForAuthentication[user, authorities]; } ... }

LoginController.java

@RequestMapping[value = {"/login", "/"}] public ModelAndView login[@RequestParam[name="error", required = false]String error, @RequestParam[name="logout", required = false]String logout, HttpServletRequest request ] throws UnknownHostException { // Port String portNumber = environment.getProperty["server.port"]; // Local address String hostAddress = InetAddress.getLocalHost[].getHostAddress[]; String hostName = InetAddress.getLocalHost[].getHostName[]; System.out.println["Host address:"+hostAddress+" Host name:"+hostName+" Port number:"+portNumber]; // Remote address InetAddress.getLoopbackAddress[].getHostAddress[]; InetAddress.getLoopbackAddress[].getHostName[]; ModelAndView mv = new ModelAndView["login"]; if[error!=null] { mv.addObject["message", "Invalid Username and Password!"]; } if[logout!=null] { mv.addObject["logout", "User has successfully logged out!"]; } System.out.println["context path:"+request.getContextPath[]]; return mv; }

login.jsp

Insert title here .help-block { color: #ff0000; }

Login

${message}
${logout}


Login --%> Register $[function[]{ const $loginForm = $["#loginform"]; if[$loginForm.length]{ $loginForm.validate[{ rules: { email: { required: true }, password: { required: true } }, messages: { email: { required: "Please enter email" }, password: { required: "Please enter password" } }, errorElement: 'em', errorPlacement: function[error, element] { error.addClass['help-block']; error.insertAfter[element]; } }] } }]

WebSecurityConfiguration.java

@Configuration @EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private MyUserDetailsService userDetailsService; @Override protected void configure[HttpSecurity http] throws Exception { http. authorizeRequests[] .antMatchers["/"].permitAll[] .antMatchers["/login"].permitAll[] .antMatchers["/registration"].permitAll[] .antMatchers["/confirm-account"].permitAll[] .antMatchers["/admin/**"].hasAuthority["ADMIN"] .antMatchers["/user/**"].hasAnyAuthority["ADMIN", "USER"] .anyRequest[].authenticated[].and[].csrf[].disable[].formLogin[] .loginPage["/login"]//.failureUrl["/login?error=true"] .defaultSuccessUrl["/dashboard"] .usernameParameter["email"] .passwordParameter["password"] .and[].exceptionHandling[].accessDeniedPage["/403"]; } ... }

Thông báo lỗi hiển thị trong JSP là "Tên người dùng và mật khẩu không hợp lệ". Vậy làm thế nào để hiển thị thông báo lỗi như "Không tìm thấy người dùng" nếu UserNotFoundExceptionbị ném!

Cảm ơn trước!

Video liên quan

Chủ Đề