From de8d81990ac4646057738987a5c599f4de4eabe9 Mon Sep 17 00:00:00 2001 From: egmp777 Date: Thu, 14 Aug 2014 18:12:45 -0500 Subject: [PATCH 1/3] spring security and registration could not run it - see video /Users/Elena/Google Drive/SharedWithEugene/Spring-Security-Login-and_Registration/2014-08-14 _1805.swf --- .../.classpath | 10 +- spring-security-login-error-handling/.project | 6 + spring-security-login-error-handling/pom.xml | 11 +- .../persistence/dao/UserRepository.java | 3 +- .../org/baeldung/persistence/model/Role.java | 92 +- .../org/baeldung/persistence/model/User.java | 20 +- .../service/EmailExistsException.java | 5 +- .../RegistrationFormWithValidation.java | 73 - .../service/RepositoryService.java | 28 +- .../baeldung/persistence/service/UserDto.java | 28 +- .../persistence/service/UserService.java | 4 +- .../persistence/service/UserValidator.java | 17 +- .../security/MyUserDetailsService.java | 18 +- .../java/org/baeldung/spring/AppConfig.java | 25 +- .../java/org/baeldung/spring/MvcConfig.java | 24 +- .../baeldung/spring/PersistenceJPAConfig.java | 12 +- .../baeldung/spring/SecSecurityConfig.java | 2 +- .../controller/RegistrationController.java | 66 +- .../src/main/resources/application.properties | 2 +- .../src/main/resources/messages_en.properties | 3 +- .../main/resources/messages_es_ES.properties | 11 +- .../src/main/resources/webSecurityConfig.xml | 9 - .../src/main/webapp/WEB-INF/view/admin.jsp | 4 +- .../src/main/webapp/WEB-INF/view/console.jsp | 4 +- .../src/main/webapp/WEB-INF/view/home.jsp | 1 + .../src/main/webapp/WEB-INF/view/homepage.jsp | 4 +- .../webapp/WEB-INF/view/invalidSession.jsp | 4 +- .../src/main/webapp/WEB-INF/view/login.jsp | 24 +- .../src/main/webapp/WEB-INF/view/logout.jsp | 6 +- .../main/webapp/WEB-INF/view/registration.jsp | 28 +- .../webapp/WEB-INF/view/successRegister.jsp | 3 +- .../src/main/webapp/resources/bootstrap.css | 6167 +++++++++++++++++ 32 files changed, 6372 insertions(+), 342 deletions(-) delete mode 100644 spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RegistrationFormWithValidation.java create mode 100644 spring-security-login-error-handling/src/main/webapp/resources/bootstrap.css diff --git a/spring-security-login-error-handling/.classpath b/spring-security-login-error-handling/.classpath index 0f4a4c27e0..1151b0d257 100644 --- a/spring-security-login-error-handling/.classpath +++ b/spring-security-login-error-handling/.classpath @@ -17,16 +17,16 @@ - - - - - + + + + + diff --git a/spring-security-login-error-handling/.project b/spring-security-login-error-handling/.project index 41c4e13e7c..818a1e1a48 100644 --- a/spring-security-login-error-handling/.project +++ b/spring-security-login-error-handling/.project @@ -35,6 +35,11 @@ + + org.hibernate.eclipse.console.hibernateBuilder + + + org.eclipse.jem.workbench.JavaEMFNature @@ -44,5 +49,6 @@ org.eclipse.m2e.core.maven2Nature org.eclipse.wst.common.project.facet.core.nature org.eclipse.wst.jsdt.core.jsNature + org.hibernate.eclipse.console.hibernateNature diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml index d750675411..53d446cc99 100644 --- a/spring-security-login-error-handling/pom.xml +++ b/spring-security-login-error-handling/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 1.1.5.RELEASE + 1.1.4.RELEASE @@ -100,6 +100,10 @@ org.hibernate hibernate-entitymanager + + org.hibernate + hibernate-validator + @@ -137,6 +141,9 @@ 1.7 + 3.1.1.RELEASE + 3.2.4.RELEASE + 1.6.10 1.7.6 @@ -149,7 +156,7 @@ 1 - 1.6.2.RELEASE + 1.4.1.RELEASE 17.0 diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/dao/UserRepository.java index 373a28b476..d36cd1ba2f 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/dao/UserRepository.java @@ -3,6 +3,7 @@ package org.baeldung.persistence.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.baeldung.persistence.model.User; -public interface UserRepository extends JpaRepository { + +public interface UserRepository extends JpaRepository{ public User findByUsername(String username); } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/Role.java index 4be1696e6e..f0a08885f5 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/Role.java @@ -11,58 +11,52 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; -@Entity(name = "role") + +@Entity(name="role") @Table(name = "role") public class Role { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; - @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinColumn(name = "user_id") - private User user; + + @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @JoinColumn(name = "user_id") + private User user; + + @Column(name="role") + private Integer role; - @Column(name = "role") - private Integer role; - - public Role() { - super(); - - } - - public Role(Integer role) { - super(); - this.role = role; - } - - public Role(Integer role, User user) { - super(); - this.role = role; - this.user = user; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public Integer getRole() { - return role; - } - - public void setRole(Integer role) { - this.role = role; - } + public Role(){ + super(); + + } + public Role(Integer role){ + super(); + this.role = role; + } + public Role(Integer role, User user){ + super(); + this.role = role; + this.user = user; + } + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public User getUser() { + return user; + } + public void setUser(User user) { + this.user = user; + } + public Integer getRole() { + return role; + } + public void setRole(Integer role) { + this.role = role; + } } \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/User.java index 33851c9fa5..4fe8c9986f 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/model/User.java @@ -17,16 +17,17 @@ public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @Column(name = "firstName") + @Column(name="firstName") private String firstName; - @Column(name = "lastName") + @Column(name="lastName") private String lastName; - @Column(name = "username") + @Column(name="username") private String username; - @Column(name = "password") + @Column(name="password") private String password; - - @OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) + + + @OneToOne(mappedBy = "user",fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Role role; public Long getId() { @@ -76,7 +77,8 @@ public class User { public void setRole(Role role) { this.role = role; } - + + @Override public int hashCode() { final int prime = 31; @@ -98,11 +100,11 @@ public class User { return false; return true; } - @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]"); + builder.append("User [firstName=").append(firstName).append("]"). + append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]"); return builder.toString(); } } \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/EmailExistsException.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/EmailExistsException.java index eaf5c36409..edb44bd598 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/EmailExistsException.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/EmailExistsException.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.service; -public class EmailExistsException extends Throwable { - +@SuppressWarnings("serial") +public class EmailExistsException extends Throwable{ + public EmailExistsException(String message) { super(message); } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RegistrationFormWithValidation.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RegistrationFormWithValidation.java deleted file mode 100644 index 6be64b8414..0000000000 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RegistrationFormWithValidation.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.baeldung.persistence.service; - -import javax.validation.constraints.Size; - -import org.hibernate.validator.constraints.Email; -import org.hibernate.validator.constraints.NotEmpty; - -public class RegistrationFormWithValidation { - - @Email - @NotEmpty - @Size(max = 100) - private String email; - - @NotEmpty - @Size(max = 100) - private String firstName; - - @NotEmpty - @Size(max = 100) - private String lastName; - - private String password; - - private String passwordVerification; - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPasswordVerification() { - return passwordVerification; - } - - public void setPasswordVerification(String passwordVerification) { - this.passwordVerification = passwordVerification; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]"); - return builder.toString(); - } -} diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RepositoryService.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RepositoryService.java index 25630ad9d6..e5fbc3622d 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RepositoryService.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/RepositoryService.java @@ -1,48 +1,42 @@ package org.baeldung.persistence.service; import javax.transaction.Transactional; - import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.Role; import org.baeldung.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @Service public class RepositoryService implements UserService { - @Autowired + @Autowired private UserRepository repository; - - private final PasswordEncoder passwordEncoder; - + @Autowired private Environment env; - + @Autowired - public RepositoryService(PasswordEncoder passwordEncoder, UserRepository repository) { - this.passwordEncoder = passwordEncoder; + public RepositoryService( UserRepository repository) { this.repository = repository; - } - + } + @Transactional @Override public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException { if (emailExist(userAccountData.getUsername())) { - + throw new EmailExistsException("There is an account with that email adress: " + userAccountData.getUsername()); - } - - User user = new User(); + } + User user = new User(); user.setFirstName(userAccountData.getFirstName()); user.setLastName(userAccountData.getLastName()); user.setPassword(userAccountData.getPassword()); user.setUsername(userAccountData.getUsername()); user.setRole(new Role(userAccountData.getRole(), user)); - return repository.save(user); + return repository.save(user); } - + private boolean emailExist(String email) { User user = repository.findByUsername(email); if (user != null) { diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserDto.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserDto.java index 3d7dfd6642..b313b89b13 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserDto.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserDto.java @@ -1,68 +1,48 @@ package org.baeldung.persistence.service; -//Renamed original RegistrationForm - public class UserDto { private String firstName; private String lastName; private String password; private String username; - private Integer role; - private String lastError; - - public String getLastError() { - return lastError; - } - - public void setLastError(String lastError) { - this.lastError = lastError; - } - + private Integer role; + public Integer getRole() { return role; } - public void setRole(Integer role) { this.role = role; } - public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } - public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } - public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } - public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } - @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]"); + builder.append("User [firstName=").append(firstName).append("]"). + append("[lastName=").append(lastName).append("]").append("[username").append(username).append("]").append("[password").append(password).append("]"); return builder.toString(); } } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserService.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserService.java index 1166503fba..b51bda5b3b 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserService.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserService.java @@ -1,8 +1,8 @@ package org.baeldung.persistence.service; - import org.baeldung.persistence.model.User; public interface UserService { - + public User registerNewUserAccount(UserDto userAccountData) throws EmailExistsException; + } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserValidator.java b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserValidator.java index f93ba5825e..ac6bbb89f3 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserValidator.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/persistence/service/UserValidator.java @@ -1,22 +1,33 @@ package org.baeldung.persistence.service; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class UserValidator implements Validator { - + private Pattern pattern; + private Matcher matcher; + private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + @Override public boolean supports(Class clazz) { return UserDto.class.isAssignableFrom(clazz); } - + @Override public void validate(Object obj, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "message.firstName", "Firstname is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "message.lastName", "LastName is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "message.password", "LastName is required."); - ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required."); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "message.username", "UserName is required."); } + public boolean validateEmail(String email) { + pattern = Pattern.compile(EMAIL_PATTERN); + matcher = pattern.matcher(email); + return matcher.matches(); + + } } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MyUserDetailsService.java index 464a747683..41c27e2a9c 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -22,33 +22,33 @@ import org.springframework.transaction.annotation.Transactional; public class MyUserDetailsService implements UserDetailsService { private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsService.class); - + private UserRepository userRepository; @Autowired public MyUserDetailsService(UserRepository repository) { this.userRepository = repository; } - + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { LOGGER.debug("Loading user by username: {}", username); User user = userRepository.findByUsername(username); LOGGER.debug("Found user: {}", user); if (user == null) { - // throw new UsernameNotFoundException("No user found with username: " + username); - boolean enabled = false; - return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1))); + //throw new UsernameNotFoundException("No user found with username: " + username); + boolean enabled = false; + return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1))); } boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; - return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole())); + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole())); } catch (Exception e) { throw new RuntimeException(e); - } + } } public Collection getAuthorities(Integer role) { @@ -60,7 +60,7 @@ public class MyUserDetailsService implements UserDetailsService { List roles = new ArrayList(); if (role.intValue() == 2) { - // roles.add("ROLE_USER"); + // roles.add("ROLE_USER"); roles.add("ROLE_ADMIN"); } else if (role.intValue() == 1) { @@ -69,7 +69,7 @@ public class MyUserDetailsService implements UserDetailsService { return roles; } - + public static List getGrantedAuthorities(List roles) { List authorities = new ArrayList(); for (String role : roles) { diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/AppConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/AppConfig.java index 987ae89cc7..6047130a69 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/AppConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/AppConfig.java @@ -1,43 +1,20 @@ package org.baeldung.spring; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.env.Environment; @Configuration @ComponentScan(basePackages = { "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) @Import({ MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class }) @PropertySource("classpath:application.properties") public class AppConfig { - @Autowired - private Environment env; - + @Bean public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } - -// @Bean -// public JavaMailSenderImpl javaMailSenderImpl() { -// JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); -// mailSenderImpl.setHost(env.getProperty("smtp.host")); -// mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); -// mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); -// mailSenderImpl.setUsername(env.getProperty("smtp.username")); -// mailSenderImpl.setPassword(env.getProperty("smtp.password")); -// -// Properties javaMailProps = new Properties(); -// javaMailProps.put("mail.smtp.auth", true); -// javaMailProps.put("mail.smtp.starttls.enable", true); -// -// mailSenderImpl.setJavaMailProperties(javaMailProps); -// -// return mailSenderImpl; -// } - } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java index a7a46a1028..4747821d1f 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java @@ -1,7 +1,6 @@ package org.baeldung.spring; import java.util.Locale; - import org.baeldung.persistence.service.UserValidator; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; @@ -12,6 +11,7 @@ import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; @@ -19,8 +19,11 @@ import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; + @Configuration -@ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) +@ComponentScan(basePackages = { + "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" +}) @EnableWebMvc public class MvcConfig extends WebMvcConfigurerAdapter { @@ -33,7 +36,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); - registry.addViewController("/login.html"); registry.addViewController("/logout.html"); registry.addViewController("/homepage.html"); @@ -42,19 +44,23 @@ public class MvcConfig extends WebMvcConfigurerAdapter { registry.addViewController("/console.html"); registry.addViewController("/admin.html"); registry.addViewController("/registration.html"); - registry.addViewController("/successRegister.html"); - + registry.addViewController("/successRegister.html"); } - + @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); - return bean; } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**") + .addResourceLocations("/","/resources/"); + } @Override public void addInterceptors(InterceptorRegistry registry) { @@ -79,11 +85,11 @@ public class MvcConfig extends WebMvcConfigurerAdapter { messageSource.setCacheSeconds(0); return messageSource; } - + @Bean public UserValidator userValidator() { UserValidator userValidator = new UserValidator(); return userValidator; } - + } \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java index 32cd80854c..e4c3d4835f 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/PersistenceJPAConfig.java @@ -1,9 +1,7 @@ package org.baeldung.spring; import java.util.Properties; - import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -18,14 +16,13 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; -//import com.google.common.base.Preconditions; - @Configuration @EnableTransactionManagement @PropertySource({ "classpath:application.properties" }) @ComponentScan({ "org.baeldung.persistence.model" }) @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") public class PersistenceJPAConfig { + @Autowired private Environment env; @@ -38,12 +35,9 @@ public class PersistenceJPAConfig { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - // vendorAdapter.set em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); - return em; } @@ -54,7 +48,6 @@ public class PersistenceJPAConfig { dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); - return dataSource; } @@ -74,8 +67,7 @@ public class PersistenceJPAConfig { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } - + } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..3e793a33f6 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -10,5 +10,5 @@ public class SecSecurityConfig { public SecSecurityConfig() { super(); } - + } diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/web/controller/RegistrationController.java b/spring-security-login-error-handling/src/main/java/org/baeldung/web/controller/RegistrationController.java index 3d70f8b5a1..a8494efb2d 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/web/controller/RegistrationController.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/web/controller/RegistrationController.java @@ -1,5 +1,6 @@ package org.baeldung.web.controller; +import javax.validation.Valid; import org.baeldung.persistence.model.User; import org.baeldung.persistence.service.EmailExistsException; import org.baeldung.persistence.service.UserDto; @@ -8,6 +9,8 @@ import org.baeldung.persistence.service.UserValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -17,29 +20,31 @@ import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.ModelAndView; + @Controller -@SessionAttributes("user") public class RegistrationController { private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class); private UserService service; @Autowired + private MessageSource messages; + @Autowired + private JavaMailSender mailSender; + @Autowired private UserValidator validator; - + @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(this.validator); } - @Autowired public RegistrationController(UserService service) { this.service = service; } - + @RequestMapping(value = "/user/registration", method = RequestMethod.GET) public String showRegistrationForm(WebRequest request, Model model) { LOGGER.debug("Rendering registration page."); @@ -47,57 +52,34 @@ public class RegistrationController { model.addAttribute("user", userDto); return "registration"; } - - /* @RequestMapping(value ="/user/registration", method = RequestMethod.POST) - public String registerUserAccount( @ModelAttribute("user") UserDto userAccountData, - BindingResult result, - WebRequest request, Errors errors) { - LOGGER.debug("Registering user account with information: {}", userAccountData); - if (result.hasErrors()) { - LOGGER.debug("Validation errors found. Rendering form view."); - return "registration"; - } - LOGGER.debug("No validation errors found. Continuing registration process."); - User registered = createUserAccount(userAccountData, result); - if (registered == null) { - errors.rejectValue("lastError", "message.regError"); - return "registration"; - } - LOGGER.debug("Registered user account with information: {}", registered); - - sendConfirmMail(userAccountData.getUsername(), request.getLocale()); - return "successRegister"; - //return "redirect:/"; - }*/ + @RequestMapping(value = "/user/registration", method = RequestMethod.POST) - public ModelAndView registerUserAccount(@ModelAttribute("user") UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) { - LOGGER.debug("Registering user account with information: {}", userAccountData); - validator.validate(userAccountData, result); - User registered = createUserAccount(userAccountData, result); - if (registered == null) { - result.rejectValue("lastError", "message.regError"); + public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto userAccountData, BindingResult result, WebRequest request, Errors errors) { + boolean goodEmailCheck = validator.validateEmail(userAccountData.getUsername()); + if (!goodEmailCheck) + result.rejectValue("username", "message.badEmail"); + User registered = null; + if (!result.hasErrors()) + registered = createUserAccount(userAccountData, result); + if (registered == null && !userAccountData.getUsername().isEmpty() && goodEmailCheck) { + result.rejectValue("username", "message.regError"); } if (result.hasErrors()) { - // show errors return new ModelAndView("registration", "user", userAccountData); } else { - - // success return new ModelAndView("successRegister", "user", userAccountData); } } - + private User createUserAccount(UserDto userAccountData, BindingResult result) { - LOGGER.debug("Creating user account with information: {}", userAccountData); User registered = null; try { registered = service.registerNewUserAccount(userAccountData); } catch (EmailExistsException e) { - // TODO Auto-generated catch block return null; - } + } return registered; - } - + } } + diff --git a/spring-security-login-error-handling/src/main/resources/application.properties b/spring-security-login-error-handling/src/main/resources/application.properties index 1144b5f03f..334ec63ed0 100644 --- a/spring-security-login-error-handling/src/main/resources/application.properties +++ b/spring-security-login-error-handling/src/main/resources/application.properties @@ -1,6 +1,6 @@ ################### DataSource Configuration ########################## jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_02?createDatabaseIfNotExist=true +jdbc.url=jdbc:mysql://localhost:3306/AUTHDATA jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql init-db=false diff --git a/spring-security-login-error-handling/src/main/resources/messages_en.properties b/spring-security-login-error-handling/src/main/resources/messages_en.properties index 66a58dfeab..de6630ec92 100644 --- a/spring-security-login-error-handling/src/main/resources/messages_en.properties +++ b/spring-security-login-error-handling/src/main/resources/messages_en.properties @@ -8,7 +8,8 @@ message.logoutSucc=You logged out successfully message.regSucc=You registered successfully. We will send you a confirmation message to your email account. message.regError=An account for that username/email already exists. Please enter a different username. message.lastName=Last name is required -message.firstName=First name is required +message.firstName=First name required +message.badEmail=Invalid email address label.user.email=Email label.user.firstName=First name label.user.lastName=Last name diff --git a/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties index 0becc40dd4..3f870472a4 100644 --- a/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties +++ b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties @@ -3,14 +3,15 @@ message.password=Por favor ingrese una clave message.unauth=Acceso denegado !! message.badCredentials=Usuario o clave invalida message.sessionExpired=La sesion expiro -message.logoutError=Lo sentimos, hubo problemas en logout -message.logoutSucc=Logout con exito +message.logoutError=Lo sentimos, hubo problemas al salir +message.logoutSucc=Salida con exito message.regSucc=Se registro correctamente. Le enviaremos un mensaje de confirmacion a su direccion de email. message.regError=Ya existe una cuenta con ese nombre de usuario. Ingrese un nombre de usuario diferente. -message.lastName=El campo Last Name es obligatorio -message.firstName=El campo First Name es obligatorio +message.lastName=Por favor ingrese su apellido +message.firstName=Por favor ingrese su nombre +message.badEmail=Direccion de correo no es valida label.user.email=Email label.user.firstName=Nombre label.user.lastName=Apellido label.user.password=Clave -label.login=Loguee aqui \ No newline at end of file +label.login=Autehtifiquese aqui \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml index ef5ba495da..7c362885ae 100644 --- a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml @@ -29,22 +29,13 @@ - - - - - - - \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp index 5aefc9ab55..027b387b96 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp @@ -5,7 +5,9 @@ - + +" rel="stylesheet"> + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp index 05a930731b..b82842169f 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp @@ -1,7 +1,9 @@ <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> - + +" rel="stylesheet"> +

This is the landing page for the admin

diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp index fe6e572b99..4d54257bff 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp @@ -2,6 +2,7 @@ <%@ page session="true" %> +" rel="stylesheet"> Home diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp index fab96383df..c13acb7756 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp @@ -2,7 +2,9 @@ <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <%@ page session="true" %> - + +" rel="stylesheet"> + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp index 175c498117..8aa9d7b49f 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp @@ -1,10 +1,12 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> +" rel="stylesheet"> Home -

+

diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp index 97bc749acc..97c8b3317d 100644 --- a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp @@ -5,28 +5,17 @@ <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ page session="true"%> - -
- -
-
- -
- -
-
- -
- -
- Register -
- +" rel="stylesheet"> + +
+ +
+