1. 程式人生 > >簡單許可權系統基於shiro-springmvc-spring-mybatis(學習筆記 1)

簡單許可權系統基於shiro-springmvc-spring-mybatis(學習筆記 1)

一個簡單的許可權管理系統,實現使用者、許可權、資源的增刪改查,這三者之間相互的授權和取消授權,如:一個使用者可以擁有多個許可權並且一個許可權可以擁有多個資源。

系統基於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\u6216ERROR
log4j.rootLogger=DEBUG, stdout # MyBatis logging configuration... # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.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操作資料庫的方法實現業務邏輯處理)

@Service
public 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。

@Autowired
private 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);

    }

}