简单权限系统基于shiro-springmvc-spring-mybatis(学习笔记 1)
来源:互联网 发布:手机淘宝免费注册流程 编辑:程序博客网 时间:2024/05/23 13:07
一个简单的权限管理系统,实现用户、权限、资源的增删改查,这三者之间相互的授权和取消授权,如:一个用户可以拥有多个权限并且一个权限可以拥有多个资源。
系统基于shiro、springmvc、spring、mybatis,使用mysql数据库。
项目地址:https://git.oschina.net/beyondzl/spring-shiro
(前端视图由于时间原因没有全部完成,后端功能测试可行)
log4j的属性文件:
# Global logging configuration#\u5F00\u53D1\u73AF\u5883\u65E5\u5FD7\u7EA7\u522B\u8BBE\u7F6EDEBUG,\u751F\u4EA7\u73AF\u5883\u8BBE\u7F6E\u6210INFO\u6216ERRORlog4j.rootLogger=DEBUG, stdout# MyBatis logging configuration...# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Dao层:
使用mapper代理开发
SqlMapConfig.xml:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="false"></setting> <setting name="lazyLoadingEnabled" value="false"></setting> <setting name="aggressiveLazyLoading" value="true"></setting> <setting name="logImpl" value="LOG4J"></setting> </settings> <typeAliases> <typeAlias type="com.spring.shiro.main.common.utils.PageInfo" alias="PageInfo"></typeAlias> <typeAlias type="com.spring.shiro.main.java.model.User" alias="User"></typeAlias> <typeAlias type="com.spring.shiro.main.common.result.UserVo" alias="UserVo"></typeAlias> <typeAlias type="com.spring.shiro.main.java.model.Resource" alias="Resourcce"></typeAlias> <typeAlias type="com.spring.shiro.main.java.model.Role" alias="Role"></typeAlias> <typeAlias type="com.spring.shiro.main.java.model.Organization" alias="Organization"></typeAlias> <typeAlias type="com.spring.shiro.main.java.model.SysLog" alias="SysLog"></typeAlias> </typeAliases> <!-- (与spring整合后可舍弃)<environments default="development"> 使用JDBC事务管理 <environment id="development"> <transactionManager type="JDBC"></transactionManager> 数据库连接池 <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="xz19950122xz"/> </dataSource> </environment> </environments> --> <mappers > <!-- 加载映射文件 --> <mapper resource="mappers/OrganizationMapper.xml"></mapper> <mapper resource="mappers/ResourceMapperl.xml"></mapper> <mapper resource="mappers/RoleMapper.xml"></mapper> <mapper resource="mappers/RoleResourceMapper.xml"></mapper> <mapper resource="mappers/SlaveMapper.xml"></mapper> <mapper resource="mappers/SysLogMapper.xml"></mapper> <mapper resource="mappers/UserMapper.xml"></mapper> <mapper resource="mappers/UserRoleMapper.xml"></mapper> </mappers></configuration>
mapper.xml中命名空间对应相应mapper接口路径
主键返回语句:
<insert id="insert"> <selectKey keyProperty="id" order="AFTER" resultType="long"> SELECT LAST_INSERT_ID(); </selectKey> insert into user_role(user_id, role_id) values(#{userId},#{roleId}) </insert>
还可以使用<set>、<if>标签
:
<update id="updateByPrimaryKeySelective"> update user_role <set> <if test="userId != null"> user_id = #{userId} </if> <if test="roleId != null"> role_id = #{roleId} </if> </set> where id = #{id} </update>
**<sql>
标签的使用:**
<sql id="Base"> id, name, url, description, icon, pid, seq, status, resourcetype, createdate </sql> <select id="findResourceById"> select <include refid="Base"></include> from resource where id= #{id}; </select>
Dao层测试类:
public class UserRoleMapperTest { private UserRoleMapper mapper; @Before public void setUp() throws Exception { String resource = "SqlMapConfig.xml"; InputStream config = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config); SqlSession sqlSession = sqlSessionFactory.openSession(); mapper = sqlSession.getMapper(UserRoleMapper.class); } @Test public void testInsert() { UserRole userRole = new UserRole(); userRole.setRoleId((long) 3); userRole.setUserId((long) 2); int i = mapper.insert(userRole); }
spring整合mybatis:
spring-mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 加载资源文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 数据库连接池 使用c3p0 --> <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- SqlSessionFactory --> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加载mybatis配置 --> <property name="mapperLocations" value="classpath*:config/mappers/*.xml"></property> <property name="configLocation" value="classpath:/SqlMapConfig.xml"></property> <property name="dataSource" ref="DataSource"></property> </bean> <!-- <bean id="userRoleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.spring.shiro.main.java.mapper.UserRoleMapper"></property> <property name="sqlSessionFactory" ref="SqlSessionFactory"></property> </bean> --> <!-- mapper代理批量配置 --> <bean id="mapperScanConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.spring.shiro.main.java.mapper"></property> </bean></beans>
测试时一直报错找不到mapper接口中方法在mapper.xml中对应的id,
后将下面配置改动了一下,测试通过——
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加载mybatis配置 --> <property name="mapperLocations" value="classpath*:config/mappers/*.xml"></property> <property name="configLocation" value="classpath:/SqlMapConfig.xml"></property> <property name="dataSource" ref="DataSource"></property> </bean>
将classpath*:/mappers/*.xml改成了classpath*:config/mappers/*.xml
Service层:
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:component-scan base-package="com.spring.shiro.main.java.service。impl,com.spring.shiro.main.java.mapper"></context:component-scan> <import resource="spring/spring-mybatis.xml"></import></beans>
使用注解开发,service实现类:
(调用mapperBean,组合使用mapper操作数据库的方法实现业务逻辑处理)
@Servicepublic class UserServiceImpl implements UserService { public static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); private ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml"); //@Autowired private UserMapper userMapper = (UserMapper) apl.getBean("userMapper"); @Resource private UserRoleMapper userRoleMapper; @Override public User findUserByLoginName(String username) { return userMapper.findUserByLoginName(username); } @Override public User findUserById(Long id) { return userMapper.findUserById(id); } @Override public void findUserGrid(PageInfo pageInfo) { pageInfo.setRows(userMapper.findUserPageCondition(pageInfo)); pageInfo.setTotal(userMapper.findUserPageCount()); } @Override public void addUser(UserVo userVo) { User user = new User(); try{ PropertyUtils.copyProperties(user, userVo); }catch(Exception e) { LOGGER.error("类转换异常:{}", e); throw new RuntimeException("类转换异常:{}",e); } System.out.println(user); userMapper.insert(user); Long id = user.getId(); String[] roles = userVo.getRoleIds().split(","); UserRole userRole = new UserRole(); for(String roleId : roles) { userRole.setUserId(id); userRole.setRoleId(Long.valueOf(roleId)); userRoleMapper.insert(userRole); } } @Override public void updateUserPwdById(Long userId, String pwd) { userMapper.updateUserPasswordById(userId, pwd); } @Override public UserVo findUserVoById(Long id) { return userMapper.findUserVoById(id); } @Override public void updateUser(UserVo userVo) { User user = new User(); try{ PropertyUtils.copyProperties(user, userVo); }catch(Exception e) { LOGGER.error("类转换异常:{}", e); throw new RuntimeException("类转换异常:{}",e); } userMapper.updateUser(user); Long id = userVo.getId(); List<UserRole> userRoles = userRoleMapper.findUserRoleByUserId(id); if(userRoles != null && (!userRoles.isEmpty())) { for(UserRole userRole : userRoles) { userRoleMapper.deleteById(userRole.getId()); } } String[] roleIds = userVo.getRoleIds().split(","); UserRole userRole = new UserRole(); for(String roleId : roleIds) { userRole.setId(id); userRole.setRoleId(Long.parseLong(roleId)); userRoleMapper.insert(userRole); } } @Override public void deleteUserById(Long id) { int delete = userMapper.deleteById(id); if(delete != 1) { throw new RuntimeException("删除用户失败!"); } }
测试时,@Autowired注解不能自动装载mapperBean,mapperBean中始终为空值。最终改成了从容器中获取mapperBean。
@Autowiredprivate UserMapper userMapper;
改成了如上
private ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml"); //@Autowired private UserMapper userMapper = (UserMapper) apl.getBean("userMapper");
service测试类(导入了spring的Junit测试环境):
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"classpath:applicationContext.xml"})public class UserServiceImplTest extends AbstractJUnit4SpringContextTests{ @Before public void setUp() throws Exception { } @Test public void test() { UserVo userVo = new UserVo(); userVo.setAge(3); userVo.setCreatedate(new Date()); userVo.setId((long) 3); userVo.setLoginName("abcss"); userVo.setName("aaa"); userVo.setPassword("123"); userVo.setPhone("123466"); userVo.setRoleIds("4,6,7"); userVo.setSex(1); userVo.setStatus(3); userVo.setUserType(3); userVo.setOrganizationId(2); UserServiceImpl userServiceImpl = new UserServiceImpl(); userServiceImpl.addUser(userVo); } @Test public void testMapper() { ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = (UserMapper) apl.getBean("userMapper"); User user = new User(); user.setAge(12); user.setCreatedate(new Date()); user.setLoginName("abcd"); user.setName("name"); user.setOrganizationId(2); user.setPassword("123456"); user.setPhone("136"); user.setSex(1); user.setStatus(3); user.setUserType(2); int i = userMapper.insert(user); }}
0 0
- 简单权限系统基于shiro-springmvc-spring-mybatis(学习笔记 1)
- 简单权限系统基于shiro-springmvc-spring-mybatis(学习笔记2)
- springmvc-spring-mybatis-shiro-easyui权限系统
- spring+springmvc+mybatis shiro权限管理系统demo mysql数据库
- SpringMVC+Spring Data JPA+Shiro+EasyUI简单权限管理系统
- SpringMVC+Spring Data JPA+Shiro+EasyUI简单权限管理系统
- SpringMVC+Spring Data JPA+Shiro+EasyUI简单权限管理系统
- SpringMVC+Spring Data JPA+Shiro+EasyUI简单权限管理系统
- SpringMVC+Spring Data JPA+Shiro+EasyUI简单权限管理系统
- Spring+SpringMVC+Mybatis+shiro权限登录管理
- spring-shiro-springmvc-mybatis简单配置项目
- 【基于shiro的分布式权限管理系统】一个用Java、spring、mybatis和shiro开发的分布式权限管理系统
- Spring+Mybatis+Shiro开发权限管理系统
- spring,springmvc,mybatis,shiro,redis实现的通用权限管理系统
- 基于Spring-SpringMVC-Mybatis 的 Shiro 安全框架使用教程
- 基于Spring+SpringMVC+Mybatis分布式敏捷开发系统架构---权限管理系统
- 基于Spring+SpringMVC+Mybatis分布式敏捷开发系统架构---权限管理系统
- 基于Spring-SpringMVC-Mybatis的简单例子
- getDimension()、getDimensionPixelOffset()和getDimensionPixelSize()区别详解
- 对于linux下system()函数的深度理解
- form表单重复提交问题
- Atom编辑器中文设置 ,汉化Atom插件
- 关于TS流的封装和解析
- 简单权限系统基于shiro-springmvc-spring-mybatis(学习笔记 1)
- 242. Valid Anagram QuestionEditorial Solution
- spring配置文件的一些注重点
- thinkphp的日志管理
- 设计模式~适配器模式
- 完美解决ScrollView嵌套ListView或GridView冲突
- Android SDK版本号与API级别的对应关系
- quartz定时任务中常用的cron表达式
- Android 下 APK 捆绑器的实现