用户角色权限表关系
使用数据库完成springSecurity用户登录验证
springSecurity的使用步骤:
1.在web工程的pom.xml文件下导入依赖
<!--Spring Security权限管理-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!--使用标签拦截配置-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
2.创建spring-security.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 配置不拦截的资源 -->
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/failer.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>
<!--
配置具体的规则
auto-config="true" 不用自己编写登录的页面,框架提供默认登录页面
use-expressions="false" 是否使用SPEL表达式(没学习过)
-->
<security:http auto-config="true" use-expressions="true">
<!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
<!-- 定义跳转的具体的页面 -->
<security:form-login
login-page="/login.jsp"
login-processing-url="/login.do"
default-target-url="/index.jsp"
authentication-failure-url="/failer.jsp"
authentication-success-forward-url="/pages/main.jsp"
/>
<!-- 关闭跨域请求 -->
<security:csrf disabled="true"/>
<!-- 退出 -->
<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />
</security:http>
<!-- 切换成数据库中的用户名和密码 -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<!-- 配置加密的方式-->
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<!-- 配置加密类 -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>
3.用户登录的前台页面login.jsp
<div class="login-logo">
<a href="all-admin-index.html"><b>WANG</b>后台管理系统</a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">登录系统</p>
<form action="${pageContext.request.contextPath}/login.do" method="post">
<div class="form-group has-feedback">
<input type="text" name="username" class="form-control"
placeholder="用户名"> <span
class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control"
placeholder="密码"> <span
class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label><input type="checkbox"> 记住 下次自动登录</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">登录</button>
</div>
<!-- /.col -->
</div>
</form>
<a href="#">忘记密码</a><br>
</div>
4.用户权限登录的service层
@Service("userService")
@Transactional
public class IUserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userDao.findByUsername(username);
User user = new User(userInfo.getUsername(),
userInfo.getPassword(),
userInfo.getStatus() == 0 ? false : true,
true, true,
true, getAuthority(userInfo.getRoles()));
return user;
}
private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
List<SimpleGrantedAuthority> list = new ArrayList<>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
}
return list;
}
5.userDao层
@Select("select * from users where username=#{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(column = "username", property = "username"),
@Result(column = "email", property = "email"),
@Result(column = "password", property = "password"),
@Result(column = "phoneNum", property = "phoneNum"),
@Result(column = "status", property = "status"),
@Result(column = "id", property = "roles", javaType = java.util.List.class, many =
@Many(select = "com.wang.ssm.dao.IRoleDao.findRoleByUserId")) })
public UserInfo findByUsername(String username);
用户退出
配置
<security:logout invalidate-session="true" logout-url="/logout.do" logout-successurl="/login.jsp" />
页面
<a href="${pageContext.request.contextPath}/logout.do" class="btn btn-default btn-flat">注销</a>
用户查询
UserController层
/**
* 查看用户
* @return
* @throws Exception
*/
@RequestMapping("/findAll.do")
public ModelAndView findAll() throws Exception {
List<UserInfo> users = userService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("userList", users);
mv.setViewName("user-list");
return mv;
}
Dao层
@Select("select * from user")
public List<UserInfo> findAll()
用户添加
UserController层
/**
* 保存用户
* @param user
* @return
*/
@RequestMapping("/save.do")
public String save(UserInfo user){
userService.save(user);
return "redirect:findAll.do";
}
Dao层
@Insert("insert into users(email,username,password,phoneNum,status) " +
"values(#{email},#{username},#{password},#{phoneNum},#{status})")
public void save(UserInfo user);
用户详情
/**
* 根据id查询某个用户
* @param id
* @return
* @throws Exception
*/
@RequestMapping("/findById.do")
public ModelAndView findById(String id) throws Exception {
ModelAndView mv = new ModelAndView();
UserInfo userInfo = userService.findById(id);
mv.addObject("user", userInfo);
mv.setViewName("user-show1");
return mv;
}
@Select("select * from users where id=#{id}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "password", column = "password"),
@Result(property = "phoneNum", column = "phoneNum"),
@Result(property = "status", column = "status"),
@Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.wang.ssm.dao.IRoleDao.findRoleByUserId"))
})
public UserInfo findById(String id);