我在带有安全性的Spring上编写应用程序。我与用户建立了数据库,可以从数据库中以用户身份登录应用程序。但是,当我尝试在数据库中注册新用户时,它不会存储。
我没有错误,只需重定向到主页即可。
如果取消注释自动登录字符串,则会得到Null Point EX。
这是我的应用程序的结构:
UserServiceImpl.class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import com.ya.pokupay.dao.RoleDAO;
import com.ya.pokupay.dao.UserDAO;
import com.ya.pokupay.model.Role;
import com.ya.pokupay.model.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDao;
@Autowired
private RoleDAO roleDao;
@Override
public void save(User user) {
System.out.println("HERE");
Set<Role> roles = new HashSet<>();
roles.add(roleDao.getOne(1L));
user.setRoles(roles);
System.out.println("user: " + user);
userDao.save(user);
}
@Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
}
控制器方法:
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
//securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
return "redirect:/all";
}
UserDetailServiceImpl:
import com.ya.pokupay.dao.UserDAO;
import com.ya.pokupay.model.Role;
import com.ya.pokupay.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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.transaction.annotation.Transactional;
import java.util.HashSet;
import java.util.Set;
public class UserDetailsServiceImpl implements UserDetailsService{
@Autowired
private UserDAO userDao;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}
如果可以,我可以添加一些其他代码或设置。
编辑:
UserDAO:
import com.ya.pokupay.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDAO extends JpaRepository<User, Long> {
User findByUsername(String username);
}
我没有找到解决方案,所以我只写了自己的asve方法实现,并且对我有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句