spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页

**

最近准备开发一个家庭财务管理系统,该系统后台采用目前比较流行的Spring4、Spring MVC、Mybatis三大MVC框架技术,并且加入了shiro权限框架登录认证,maven项目管理工具,在前台用目前比较流行的bootstrap+ajax+json技术渲染分页数据显示。下面给出整个项目的详细构建过程和代码配置。

**

首先创建数据库quick4j,一共有5张表,分别是user,role,permission,user_role和role_permission。结构如下:

spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页_第1张图片

该数据表对应的创建sql语句如下:

/*
Navicat MySQL Data Transfer

Source Server         : 本地数据库
Source Server Version : 50703
Source Host           : localhost:3306
Source Database       : quick4j

Target Server Type    : MYSQL
Target Server Version : 50703
File Encoding         : 65001

Date: 2016-08-21 09:43:02

先在本地创建quick4j数据库:
mysql>create database quick4j;
mysql>use quick4j;
mysql>set names utf8;
mysql>source D:/sql/quick4j.sql;   
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `permission`
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '权限id',
  `permission_name` varchar(32) DEFAULT NULL COMMENT '权限名',
  `permission_sign` varchar(128) DEFAULT NULL COMMENT '权限标识,程序中判断使用,如"user:create"',
  `description` varchar(256) DEFAULT NULL COMMENT '权限描述,UI界面显示使用',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='权限表';

-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES ('1', 'user:create', 'user:create', null);

-- ----------------------------
-- Table structure for `role`
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '角色id',
  `role_name` varchar(32) DEFAULT NULL COMMENT '角色名',
  `role_sign` varchar(128) DEFAULT NULL COMMENT '角色标识,程序中判断使用,如"admin"',
  `description` varchar(256) DEFAULT NULL COMMENT '角色描述,UI界面显示使用',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='角色表';

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'admin', 'admin', '管理员');
INSERT INTO `role` VALUES ('2', 'manager', 'manager', '管理者');

-- ----------------------------
-- Table structure for `role_permission`
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id',
  `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id',
  `permission_id` bigint(20) unsigned DEFAULT NULL COMMENT '权限id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='角色与权限关联表';

-- ----------------------------
-- Records of role_permission
-- ----------------------------
INSERT INTO `role_permission` VALUES ('1', '2', '1');

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `username` varchar(50) DEFAULT NULL COMMENT '用户名',
  `password` char(64) DEFAULT NULL COMMENT '密码',
  `state` varchar(32) DEFAULT NULL COMMENT '状态',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `test` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='用户表';

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('13', 'test3', 'test', '启用', '2016-08-18 21:59:17', 'test');
INSERT INTO `user` VALUES ('14', 'test4', 'test', '启用', '2016-08-18 21:59:17', 'test');
INSERT INTO `user` VALUES ('15', 'test44', 'test', '启用', '2016-08-18 21:59:17', 'test');
INSERT INTO `user` VALUES ('16', 'test333', 'test', '启用', '2016-08-18 21:59:17', 'test');
INSERT INTO `user` VALUES ('17', 'test33', 'test', '启用', '2016-08-18 21:59:17', 'test');
INSERT INTO `user` VALUES ('18', 'test55', 'test', '启用', '2016-08-18 21:59:17', 'test');

-- ----------------------------
-- Table structure for `user_role`
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id',
  `user_id` bigint(20) unsigned DEFAULT NULL COMMENT '用户id',
  `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='用户与角色关联表';

-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1', '1');
INSERT INTO `user_role` VALUES ('2', '13', '1');
INSERT INTO `user_role` VALUES ('3', '14', '2');

数据库创建完成后,接下来构建maven项目–家庭财务管理系统,名称为HelloHome,该项目代码结构图如下:
spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页_第2张图片
spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页_第3张图片

接下来给出maven配置文件pom.xml的详细配置(该文件主要用来管理jar包依赖关系和项目部署情况):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.kj.testgroupId>
    <artifactId>HelloHomeartifactId>
    <packaging>warpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>HelloHome Maven Webappname>
    <url>http://maven.apache.orgurl>

    <properties>
        
        <spring.version>4.0.6.RELEASEspring.version>
        
        <mybatis.version>3.3.0mybatis.version>
        
        <slf4j.version>1.7.7slf4j.version>
        <log4j.version>1.2.17log4j.version>
        <shiro.version>1.2.3shiro.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-oxmartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-mockartifactId>
            <version>2.0.8version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.2version>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>4.0.0version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.32version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.5version>
        dependency>

        
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.4version>
        dependency>
        <dependency>
            <groupId>commons-poolgroupId>
            <artifactId>commons-poolartifactId>
            <version>1.6version>
        dependency>
        
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.1version>
            <scope>providedscope>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>${log4j.version}version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.41version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${slf4j.version}version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${slf4j.version}version>
        dependency>

        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-coreartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>org.logback-extensionsgroupId>
            <artifactId>logback-ext-springartifactId>
            <version>0.1.1version>
        dependency>

        

        
        
        <dependency>
            <groupId>net.sf.json-libgroupId>
            <artifactId>json-libartifactId>
            <version>2.3version>
            <classifier>jdk15classifier>
        dependency>

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-commonsartifactId>
            <version>1.6.1.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>1.4.1.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.13version>
        dependency>
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>
        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
            <version>1.9version>
        dependency>
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>commons-langgroupId>
            <artifactId>commons-langartifactId>
            <version>2.6version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-collections4artifactId>
            <version>4.0version>
        dependency>

        <dependency>
            <groupId>net.sf.ehcachegroupId>
            <artifactId>ehcacheartifactId>
            <version>1.6.2version>
        dependency>
        <dependency>
            <groupId>javax.validationgroupId>
            <artifactId>validation-apiartifactId>
            <version>1.1.0.Finalversion>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>5.0.1.Finalversion>
        dependency>

        
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-springartifactId>
            <version>${shiro.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-ehcacheartifactId>
            <version>${shiro.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-coreartifactId>
            <version>${shiro.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-webartifactId>
            <version>${shiro.version}version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-quartzartifactId>
            <version>${shiro.version}version>
        dependency>

    dependencies>

    <build>
        
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <targetPath>${basedir}/target/classestargetPath>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <targetPath>${basedir}/target/resourcestargetPath>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>

        
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.6source>
                    <target>1.6target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-war-pluginartifactId>
                <version>2.1.1version>
                <configuration>
                    <warSourceExcludes>${basedir}/target/HelloHome.warwarSourceExcludes>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-surefire-pluginartifactId>
                <version>2.4.3version>
                <configuration>
                    <testFailureIgnore>truetestFailureIgnore>
                configuration>
            plugin>
            <plugin>
                <inherited>trueinherited>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-source-pluginartifactId>
                <executions>
                    <execution>
                        <id>attach-sourcesid>
                        <goals>
                            <goal>jargoal>
                        goals>
                    execution>
                executions>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-resources-pluginartifactId>
                <configuration>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
        plugins>
    build>
    <profiles>
        
        <profile>
            <id>devid>
            <activation>
                <activeByDefault>trueactiveByDefault>
            activation>
            
            <properties>
                
                <jdbc_driverClassName>com.mysql.jdbc.Driverjdbc_driverClassName>
                <jdbc_url>jdbc:mysql://localhost:3306/quick4jjdbc_url>
                <jdbc_username>rootjdbc_username>
                <jdbc_password>rootjdbc_password>
                
                <log.moduleName>HelloHomelog.moduleName>
                <log.base>logslog.base>
                <log.other.level>DEBUGlog.other.level>
                <log.root.level>DEBUGlog.root.level>
                <log.stdout.ref>]]>log.stdout.ref>
            properties>
        profile>
    profiles>
project>

下载好相关jar包后,使用mybatis工具代码自动生成实体类domain,接口类Mapper(Dao)和配置文件mapper.xml。generatorConfig.xml工具代码如下:



<generatorConfiguration>

    
    <classPathEntry
        location="D:\development\MavenRepository\maven_jar\mysql\mysql-connector-java\5.1.30\mysql-connector-java-5.1.30.jar" />

    <context id="mbgtest">

        
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
            <property name="suppressDate" value="true" />
        commentGenerator>

        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/quick4j" userId="root"
            password="root" />
        
        <javaModelGenerator targetPackage="com.kj.domain"
            targetProject="HelloHome/src/main/java" />
        
        <sqlMapGenerator targetPackage="com.kj.mapper"
            targetProject="HelloHome/src/main/java" />
        
        <javaClientGenerator targetPackage="com.kj.dao"
            targetProject="HelloHome/src/main/java" type="XMLMAPPER" />

        
        <table schema="quick4j" tableName="user" domainObjectName="User" 
               enableCountByExample="false" 
               enableUpdateByExample="false" 
               enableDeleteByExample="false"
            enableSelectByExample="false" 
            selectByExampleQueryId="false" >
            
            <property name="useActualColumnNames" value="true" />
            
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        table>
        <table schema="quick4j" tableName="role" domainObjectName="Role"
               enableCountByExample="false" 
               enableUpdateByExample="false" 
               enableDeleteByExample="false"
            enableSelectByExample="false" 
            selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="true" />
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        table>
        <table schema="quick4j" tableName="permission" domainObjectName="Permission"
               enableCountByExample="false" 
               enableUpdateByExample="false" 
               enableDeleteByExample="false"
            enableSelectByExample="false" 
            selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="true" />
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        table>
        <table schema="quick4j" tableName="role_permission" domainObjectName="RolePermission"
               enableCountByExample="false" 
               enableUpdateByExample="false" 
               enableDeleteByExample="false"
            enableSelectByExample="false" 
            selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="true" />
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        table>
        <table schema="quick4j" tableName="user_role" domainObjectName="UserRole"
               enableCountByExample="false" 
               enableUpdateByExample="false" 
               enableDeleteByExample="false"
            enableSelectByExample="false" 
            selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="true" />
            <generatedKey column="id" sqlStatement="MySql" identity="true" />
        table>
    context>

generatorConfiguration>

创建好工具代码后,安装eclipse插件,该插件安装方法请看mybatis逆向工程自动生成工具
安装插件启动eclipse后,右击generatorConfig.xml文件(该文件放在HelloHome目录下),点击generate MyBatis/iBATIS Artifacts即可自动生成数据库表对应的实体类,接口类以及对应的sql配置文件。

在com.kj.domain包下生成的类代码如下:

package com.kj.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户
 * @author KJ
 *
 */
public class User {

    /** 主键 */
    private Long id;

    /** 账号:唯一 */
    private String username;
    /** 密码 */
    private String password;
    /** 启用状态 */
    private String state;
    /** 创建时间 */
    private Date create_time;
    /** 测试字段 */
    private String test;
    /** 所拥有的角色 */
    private List roles;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Date getCreate_time() {
        return create_time;
    }

    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

    public List getRoles() {
        return roles;
    }

    public void setRoles(List roles) {
        this.roles = roles;
    }

    public Set getRolesName() {
        List roles = getRoles();
        Set set = new HashSet();
        if (roles != null) {
            for (Role role : roles) {
                set.add(role.getRole_name());
            }
        }
        return set;
    }

}
package com.kj.domain;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色
 * @author KJ
 *
 */
public class Role {

    /** 主键 */
    private Long id;
    /** 角色标识 */
    private String role_name;
    /** 角色名称 */
    private String role_sign;
    /** 角色描述 */
    private String description;
    /** 该角色的用户集 */
    private List users;
    /** 该角色对应的操作权限 */
    private List permissions;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRole_name() {
        return role_name;
    }

    public void setRole_name(String role_name) {
        this.role_name = role_name;
    }

    public String getRole_sign() {
        return role_sign;
    }

    public void setRole_sign(String role_sign) {
        this.role_sign = role_sign;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List getUsers() {
        return users;
    }

    public void setUsers(List users) {
        this.users = users;
    }

    public List getPermissions() {
        return permissions;
    }

    public void setPermissions(List permissions) {
        this.permissions = permissions;
    }

    public Set getPermissionsName() {
        List permissions = getPermissions();
        Set set = new HashSet();
        if (permissions != null) {
            for (Permission permission : permissions) {
                set.add(permission.getPermission_name());
            }
        }
        return set;
    }
}
package com.kj.domain;

import java.util.List;

/**
 * 操作权限
 * @author KJ
 *
 */
public class Permission {

    /** 主键 */
    private Long id;
    /** 操作权限标识 */
    private String permission_name;
    /** 操作权限名称 */
    private String permission_sign;
    /** 操作权限描述 */
    private String description;
    /** 操作权限对应的角色 */
    private List roles;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getPermission_name() {
        return permission_name;
    }

    public void setPermission_name(String permission_name) {
        this.permission_name = permission_name;
    }

    public String getPermission_sign() {
        return permission_sign;
    }

    public void setPermission_sign(String permission_sign) {
        this.permission_sign = permission_sign;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List getRoles() {
        return roles;
    }

    public void setRoles(List roles) {
        this.roles = roles;
    }

}
package com.kj.domain;

/**
 * 用户-角色关联类
 * @author KJ
 *
 */
public class UserRole {

    private Long id;

    private User user;

    private Role role;

    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 Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

}
package com.kj.domain;

/**
 * 角色-操作权限关联类
 * @author KJ
 *
 */
public class RolePermission {

    private Long id;

    private Role role;

    private Permission permission;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public Permission getPermission() {
        return permission;
    }

    public void setPermission(Permission permission) {
        this.permission = permission;
    }

}

com.kj.dao包下的类如下:

package com.kj.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.kj.domain.User;

/**
 * 用户Dao接口类
 * @author KJ
 *
 */
public interface UserMapper {

     /**
     * 根据主键删除用户记录
     * @param username
     * @return
     */
    int deleteByPrimaryKey(Long id);

    /**
     * 插入用户记录
     * @param username
     * @return
     */
    int insert(User record);

    /**
     * 插入非空字段的用户记录
     * @param username
     * @return
     */
    int insertSelective(User record);

    /**
     * 根据主键查询用户记录
     * @param username
     * @return
     */
    public User selectByPrimaryKey(Long id);

    /**
     * 更新用户非空字段记录
     * @param username
     * @return
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * 更新用户记录
     * @param username
     * @return
     */
    int updateByPrimaryKey(User record);

    /**
     * 根据用户登录账号查询用户信息(确保数据库中的账号唯一性)
     * @param username
     * @return
     */
    public User selectUserRoleByUserName(String username);

    /**
      * 根据用户名查询用户集合
      * @param userName
      * @return
      */
    public List selectUserByUserName(@Param("userName") String userName);
}
package com.kj.dao;

import com.kj.domain.Role;

/**
 * Role对应的Dao接口类
 * @author KJ
 *
 */
public interface RoleMapper {

    int deleteByPrimaryKey(Long id);

    int insert(Role record);

    int insertSelective(Role record);

    public Role selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Role record);

    int updateByPrimaryKey(Role record);

    public Role selectRolePermission(Long id);
}
package com.kj.dao;

import com.kj.domain.Permission;

public interface PermissionMapper {

    int deleteByPrimaryKey(Long id);

    int insert(Permission record);

    int insertSelective(Permission record);

    Permission selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Permission record);

    int updateByPrimaryKey(Permission record);
}
package com.kj.dao;

import com.kj.domain.UserRole;

public interface UserRoleMapper {

    int deleteByPrimaryKey(Long id);

    int insert(UserRole record);

    int insertSelective(UserRole record);

    UserRole selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(UserRole record);

    int updateByPrimaryKey(UserRole record);
}
package com.kj.dao;

import com.kj.domain.RolePermission;

public interface RolePermissionMapper {

    int deleteByPrimaryKey(Long id);

    int insert(RolePermission record);

    int insertSelective(RolePermission record);

    RolePermission selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(RolePermission record);

    int updateByPrimaryKey(RolePermission record);
}

com.kj.mapper包下的代码如下:

version="1.0" encoding="UTF-8" ?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
"com.kj.dao.UserMapper" >
  id="BaseResultMap" type="com.kj.domain.User" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="CHAR" />
    <result column="state" property="state" jdbcType="VARCHAR" />
    <result column="create_time" property="create_time" jdbcType="TIMESTAMP" />
    <result column="test" property="test" jdbcType="VARCHAR" />
  
  id="Base_Column_List" >
    id, username, password, state, create_time, test
  
  
  id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from user
    where id = #{id,jdbcType=BIGINT}
  
  id="insert" parameterType="com.kj.domain.User" >
    "java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    
    insert into user (username, password, state, 
      create_time, test)
    values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=CHAR}, #{state,jdbcType=VARCHAR}, 
      #{create_time,jdbcType=TIMESTAMP}, #{test,jdbcType=VARCHAR})
  
  id="insertSelective" parameterType="com.kj.domain.User" >
    "java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    
    insert into user
    "(" suffix=")" suffixOverrides="," >
      <if test="username != null" >
        username,
      if>
      <if test="password != null" >
        password,
      if>
      <if test="state != null" >
        state,
      if>
      <if test="create_time != null" >
        create_time,
      if>
      <if test="test != null" >
        test,
      if>
    
    "values (" suffix=")" suffixOverrides="," >
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        #{password,jdbcType=CHAR},
      if>
      <if test="state != null" >
        #{state,jdbcType=VARCHAR},
      if>
      <if test="create_time != null" >
        #{create_time,jdbcType=TIMESTAMP},
      if>
      <if test="test != null" >
        #{test,jdbcType=VARCHAR},
      if>
    
  
  id="updateByPrimaryKeySelective" parameterType="com.kj.domain.User" >
    update user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        password = #{password,jdbcType=CHAR},
      if>
      <if test="state != null" >
        state = #{state,jdbcType=VARCHAR},
      if>
      <if test="create_time != null" >
        create_time = #{create_time,jdbcType=TIMESTAMP},
      if>
      <if test="test != null" >
        test = #{test,jdbcType=VARCHAR},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  
  id="updateByPrimaryKey" parameterType="com.kj.domain.User" >
    update user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=CHAR},
      state = #{state,jdbcType=VARCHAR},
      create_time = #{create_time,jdbcType=TIMESTAMP},
      test = #{test,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  

    "com.kj.domain.User" id="userRoleMap" extends="BaseResultMap">  
        property="roles" ofType="com.kj.domain.Role">  
            <id property="id" column="roleId" />  
            <result property="role_name" column="role_name" />  
            <result property="role_sign" column="role_sign" />  
            <result property="description" column="description" />  
            property="permissions" ofType="com.kj.domain.Permission">  
                <id property="id" column="permissionId" />  
                <result property="permission_name" column="permission_name" />  
                <result property="permission_sign" column="permission_sign" />  
                <result property="description" column="permission_description" />   
              
          
      

    -- 根据user表中的username查询用户和角色信息 -->  
      

  



<mapper namespace="com.kj.dao.RoleMapper" >
  <resultMap id="BaseResultMap" type="com.kj.domain.Role" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="role_name" property="role_name" jdbcType="VARCHAR" />
    <result column="role_sign" property="role_sign" jdbcType="VARCHAR" />
    <result column="description" property="description" jdbcType="VARCHAR" />
  resultMap>
  <sql id="Base_Column_List" >
    id, role_name, role_sign, description
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from role
    where id = #{id,jdbcType=BIGINT}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from role
    where id = #{id,jdbcType=BIGINT}
  delete>
  <insert id="insert" parameterType="com.kj.domain.Role" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into role (role_name, role_sign, description
      )
    values (#{role_name,jdbcType=VARCHAR}, #{role_sign,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}
      )
  insert>
  <insert id="insertSelective" parameterType="com.kj.domain.Role" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into role
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="role_name != null" >
        role_name,
      if>
      <if test="role_sign != null" >
        role_sign,
      if>
      <if test="description != null" >
        description,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="role_name != null" >
        #{role_name,jdbcType=VARCHAR},
      if>
      <if test="role_sign != null" >
        #{role_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        #{description,jdbcType=VARCHAR},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.kj.domain.Role" >
    update role
    <set >
      <if test="role_name != null" >
        role_name = #{role_name,jdbcType=VARCHAR},
      if>
      <if test="role_sign != null" >
        role_sign = #{role_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        description = #{description,jdbcType=VARCHAR},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  update>
  <update id="updateByPrimaryKey" parameterType="com.kj.domain.Role" >
    update role
    set role_name = #{role_name,jdbcType=VARCHAR},
      role_sign = #{role_sign,jdbcType=VARCHAR},
      description = #{description,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  update>

    <resultMap type="com.kj.domain.Role" id="groupRolePermission" extends="BaseResultMap">  
        <collection property="permissions" ofType="com.kj.domain.Permission">  
            <id property="id" column="permissionId" />  
            <result property="permission_name" column="permission_name" />  
            <result property="permission_sign" column="permission_sign" />  
            <result property="description" column="permission_description" />  
        collection>  
    resultMap>  

      
    <select id="selectRolePermission" parameterType="com.kj.domain.Role" resultMap="groupRolePermission">  
        select r.id,r.role_name,r.role_sign,r.description,
        p.id as permissionId,p.permission_name,p.permission_sign,p.description as permission_description 
        from role r left join 
        role_permission rp on r.id=rp.role_id left join 
        permission p on p.id=rp.permission_id 
        <where>  
              
            <if test="id != 0">r.id=#{id}if>  
              
            <if test="name != null and name != ''">  
                or r.role_name = #{name}  
            if>  
        where>  
    select>  


mapper>


<mapper namespace="com.kj.dao.PermissionMapper" >
  <resultMap id="BaseResultMap" type="com.kj.domain.Permission" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="permission_name" property="permission_name" jdbcType="VARCHAR" />
    <result column="permission_sign" property="permission_sign" jdbcType="VARCHAR" />
    <result column="description" property="description" jdbcType="VARCHAR" />
  resultMap>
  <sql id="Base_Column_List" >
    id, permission_name, permission_sign, description
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from permission
    where id = #{id,jdbcType=BIGINT}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from permission
    where id = #{id,jdbcType=BIGINT}
  delete>
  <insert id="insert" parameterType="com.kj.domain.Permission" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into permission (permission_name, permission_sign, 
      description)
    values (#{permission_name,jdbcType=VARCHAR}, #{permission_sign,jdbcType=VARCHAR}, 
      #{description,jdbcType=VARCHAR})
  insert>
  <insert id="insertSelective" parameterType="com.kj.domain.Permission" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into permission
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="permission_name != null" >
        permission_name,
      if>
      <if test="permission_sign != null" >
        permission_sign,
      if>
      <if test="description != null" >
        description,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="permission_name != null" >
        #{permission_name,jdbcType=VARCHAR},
      if>
      <if test="permission_sign != null" >
        #{permission_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        #{description,jdbcType=VARCHAR},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.kj.domain.Permission" >
    update permission
    <set >
      <if test="permission_name != null" >
        permission_name = #{permission_name,jdbcType=VARCHAR},
      if>
      <if test="permission_sign != null" >
        permission_sign = #{permission_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        description = #{description,jdbcType=VARCHAR},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  update>
  <update id="updateByPrimaryKey" parameterType="com.kj.domain.Permission" >
    update permission
    set permission_name = #{permission_name,jdbcType=VARCHAR},
      permission_sign = #{permission_sign,jdbcType=VARCHAR},
      description = #{description,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  update>
mapper>


<mapper namespace="com.kj.dao.UserRoleMapper" >
  <resultMap id="BaseResultMap" type="com.kj.domain.UserRole" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="user_id" property="user_id" jdbcType="BIGINT" />
    <result column="role_id" property="role_id" jdbcType="BIGINT" />
  resultMap>
  <sql id="Base_Column_List" >
    id, user_id, role_id
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from user_role
    where id = #{id,jdbcType=BIGINT}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from user_role
    where id = #{id,jdbcType=BIGINT}
  delete>
  <insert id="insert" parameterType="com.kj.domain.UserRole" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into user_role (user_id, role_id)
    values (#{user_id,jdbcType=BIGINT}, #{role_id,jdbcType=BIGINT})
  insert>
  <insert id="insertSelective" parameterType="com.kj.domain.UserRole" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into user_role
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="user_id != null" >
        user_id,
      if>
      <if test="role_id != null" >
        role_id,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="user_id != null" >
        #{user_id,jdbcType=BIGINT},
      if>
      <if test="role_id != null" >
        #{role_id,jdbcType=BIGINT},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.kj.domain.UserRole" >
    update user_role
    <set >
      <if test="user_id != null" >
        user_id = #{user_id,jdbcType=BIGINT},
      if>
      <if test="role_id != null" >
        role_id = #{role_id,jdbcType=BIGINT},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  update>
  <update id="updateByPrimaryKey" parameterType="com.kj.domain.UserRole" >
    update user_role
    set user_id = #{user_id,jdbcType=BIGINT},
      role_id = #{role_id,jdbcType=BIGINT}
    where id = #{id,jdbcType=BIGINT}
  update>
mapper>


<mapper namespace="com.kj.dao.RoleMapper" >
  <resultMap id="BaseResultMap" type="com.kj.domain.Role" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="role_name" property="role_name" jdbcType="VARCHAR" />
    <result column="role_sign" property="role_sign" jdbcType="VARCHAR" />
    <result column="description" property="description" jdbcType="VARCHAR" />
  resultMap>
  <sql id="Base_Column_List" >
    id, role_name, role_sign, description
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from role
    where id = #{id,jdbcType=BIGINT}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from role
    where id = #{id,jdbcType=BIGINT}
  delete>
  <insert id="insert" parameterType="com.kj.domain.Role" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into role (role_name, role_sign, description
      )
    values (#{role_name,jdbcType=VARCHAR}, #{role_sign,jdbcType=VARCHAR}, #{description,jdbcType=VARCHAR}
      )
  insert>
  <insert id="insertSelective" parameterType="com.kj.domain.Role" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    selectKey>
    insert into role
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="role_name != null" >
        role_name,
      if>
      <if test="role_sign != null" >
        role_sign,
      if>
      <if test="description != null" >
        description,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="role_name != null" >
        #{role_name,jdbcType=VARCHAR},
      if>
      <if test="role_sign != null" >
        #{role_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        #{description,jdbcType=VARCHAR},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.kj.domain.Role" >
    update role
    <set >
      <if test="role_name != null" >
        role_name = #{role_name,jdbcType=VARCHAR},
      if>
      <if test="role_sign != null" >
        role_sign = #{role_sign,jdbcType=VARCHAR},
      if>
      <if test="description != null" >
        description = #{description,jdbcType=VARCHAR},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  update>
  <update id="updateByPrimaryKey" parameterType="com.kj.domain.Role" >
    update role
    set role_name = #{role_name,jdbcType=VARCHAR},
      role_sign = #{role_sign,jdbcType=VARCHAR},
      description = #{description,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  update>

    <resultMap type="com.kj.domain.Role" id="groupRolePermission" extends="BaseResultMap">  
        <collection property="permissions" ofType="com.kj.domain.Permission">  
            <id property="id" column="permissionId" />  
            <result property="permission_name" column="permission_name" />  
            <result property="permission_sign" column="permission_sign" />  
            <result property="description" column="permission_description" />  
        collection>  
    resultMap>  

      
    <select id="selectRolePermission" parameterType="com.kj.domain.Role" resultMap="groupRolePermission">  
        select r.id,r.role_name,r.role_sign,r.description,
        p.id as permissionId,p.permission_name,p.permission_sign,p.description as permission_description 
        from role r left join 
        role_permission rp on r.id=rp.role_id left join 
        permission p on p.id=rp.permission_id 
        <where>  
              
            <if test="id != 0">r.id=#{id}if>  
              
            <if test="name != null and name != ''">  
                or r.role_name = #{name}  
            if>  
        where>  
    select>  


mapper>

IUserService类代码如下:

package com.kj.service;

import com.kj.domain.User;
import com.kj.util.PagedResult;

/**
 * 功能概要:UserService接口类
 * 
 * @author KJ
 * @since 2016-08-15
 */
public interface IUserService {

    /**
     * 根据用户主键查询用户信息
     * @param userId
     * @return
     */
    public User selectUserById(Long userId);

    /**
     * 根据用户登录账号查询用户信息(确保数据库中的账号唯一性)
     * @param username
     * @return
     */
    public User selectUserRoleByUserName(String username);
    /**
     * 
     * @param userName 查询条件,可为空
     * @param pageNo 查询条件,可为空,默认取1
     * @param pageSize 查询条件,可为空,默认取10
     * @return
     */
    public PagedResult queryByPage(String userName,Integer pageNo,Integer pageSize);

}

UserServiceImpl类代码如下:

package com.kj.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.kj.dao.UserMapper;
import com.kj.domain.User;
import com.kj.service.IUserService;
import com.kj.util.BeanUtil;
import com.kj.util.PagedResult;

/**
 * 功能概要:UserService实现类
 * 
 * @author KJ
 * @since  2016-08-15
 */
@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户主键查询用户信息
     * @param userId
     * @return
     */
    public User selectUserById(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 根据用户登录账号查询用户信息(确保数据库中的账号唯一性)
     * @param username
     * @return
     */
    public User selectUserRoleByUserName(String username) {
        return userMapper.selectUserRoleByUserName(username);
    }

    /**
     * 分页查询用户记录
     * @param userName 查询条件,可为空
     * @param pageNo 查询条件,可为空,默认取1
     * @param pageSize 查询条件,可为空,默认取10
     * @return
     */
    public PagedResult queryByPage(String userName,Integer pageNo,Integer pageSize ) {
        pageNo = pageNo == null?1:pageNo;
        pageSize = pageSize == null?10:pageSize;
        PageHelper.startPage(pageNo,pageSize);  //startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
        return BeanUtil.toPagedResult(userMapper.selectUserByUserName(userName));
    }

}

PagedResult分页类代码

package com.kj.util;

import java.util.List;

import com.kj.dto.BaseEntity;

/**
 * 功能概要:
 * @author KJ
 * @since  2016-08-15
 */
public class PagedResult extends BaseEntity {

    /*serialVersionUID*/
    private static final long serialVersionUID = 1L;

    private List dataList;//数据

    private long pageNo;//当前页

    private long pageSize;//条数

    private long total;//总条数

    private long pages;//总页面数目

    public List getDataList() {
        return dataList;
    }

    public void setDataList(List dataList) {
        this.dataList = dataList;
    }

    public long getPageNo() {
        return pageNo;
    }

    public void setPageNo(long pageNo) {
        this.pageNo = pageNo;
    }

    public long getPageSize() {
        return pageSize;
    }

    public void setPageSize(long pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public long getPages() {
        return pages;
    }

    public void setPages(long pages) {
        this.pages = pages;
    }

}

BeanUtil分页工具类

package com.kj.util;

import java.util.List;

import com.github.pagehelper.Page;
import com.kj.util.PagedResult;

/**
 * 功能概要:
 * 
 * @author KJ
 * @since  2016-08-15
 */
public class BeanUtil {

    public static  PagedResult toPagedResult(List datas) {
        PagedResult result = new PagedResult();
        if (datas instanceof Page) {
            Page page = (Page) datas;
            result.setPageNo(page.getPageNum());
            result.setPageSize(page.getPageSize());
            result.setDataList(page.getResult());
            result.setTotal(page.getTotal());
            result.setPages(page.getPages());
        } else {
            result.setPageNo(1);
            result.setPageSize(datas.size());
            result.setDataList(datas);
            result.setTotal(datas.size());
        }
        return result;
    }

}

BaseEntity基础类

package com.kj.dto;


import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 类说明:bean基类
 * 
 * 

* 详细描述: * * @author KJ * @since 2016-08-15 */ public abstract class BaseEntity implements Serializable{ private static final long serialVersionUID = 1L; private static Map,PropertyInfo[]> class2Props = new HashMap,PropertyInfo[]>(128); @Override public String toString() { PropertyInfo[] props = class2Props.get(this.getClass()); if( props == null ){ props = getProps(this.getClass()); } StringBuilder builder = new StringBuilder(1024); boolean isFirst = true; for (int i = 0, n = props.length; i < n; i++) { try { PropertyInfo propInfo = props[i]; Object value = propInfo.getMethod.invoke(this, new Object[0]); if (isFirst) isFirst = false; else builder.append(","); builder.append(propInfo.propName); builder.append(":"); if (value instanceof String) builder.append("\""); builder.append(value); if (value instanceof String) builder.append("\""); } catch (Exception e) { // ignore } } return "{" + builder.toString() + "}"; } private static PropertyInfo[] getProps(Class clazz) { PropertyInfo[] props; Method[] allMethods = clazz.getMethods(); List propList = new ArrayList(); for (int i = 0, n = allMethods.length; i < n; i++) { try { Method method = allMethods[i]; if ((method.getModifiers() & Modifier.PUBLIC) == 1 && method.getDeclaringClass() != Object.class && (method.getParameterTypes() == null || method .getParameterTypes().length == 0)) { String methodName = method.getName(); if (methodName.startsWith("get") || methodName.startsWith("is") ) { PropertyInfo propInfo = new PropertyInfo(); propInfo.getMethod = method; if (methodName.startsWith("get")) { propInfo.propName = methodName.substring(3, 4).toLowerCase() + methodName.substring(4); } else if (methodName.startsWith("is")) { propInfo.propName = methodName.substring(2, 3).toLowerCase() + methodName.substring(3); } propList.add(propInfo); } } }catch(Exception e){ } } props = new PropertyInfo[propList.size()]; propList.toArray(props); class2Props.put(clazz, props); return props; } static class PropertyInfo{ Method getMethod; String propName; } }

HttpConstants公共类

package com.kj.common;

public class HttpConstants {

    public static final String SYSTEM_ERROR_MSG = "系统错误";

    public static final String REQUEST_PARAMS_NULL = "请求参数为空";

    public static final String SERVICE_RESPONSE_NULL = "服务端返回结果为空";

    // 服务端返回成功的标志
    public static final String SERVICE_RESPONSE_SUCCESS_CODE = "AMS00000";

    // 服务端返回结果的标志
    public static final String SERVICE_RESPONSE_RESULT_FLAG = "returnCode";

    // 服务端返回结果失败的标志
    public static final String SERVICE_RESPONSE_RESULT_MSG = "errorMsg";

    // 返回给前段页面成功或失败的标志
    public static final String RESPONSE_RESULT_FLAG_ISERROR = "isError";

    // 执行删除操作
    public static final String OPERATION_TYPE_DELETE = "D";

    public static final String ENUM_PATH = "com.mucfc.msm.enumeration.";

}

BaseController基础控制类

package com.kj.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kj.common.HttpConstants;
import com.kj.json.JsonDateValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * Controller基类
 */
public class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    protected final static String DATE_FORMATE = "yyyy-MM-dd";

    /**
     * 返回服务端处理结果
     * @param obj 服务端输出对象
     * @return 输出处理结果给前段JSON格式数据
     * @author KJ
     * @since 2016-08-15
     */
    public String responseResult(Object obj){
        JSONObject jsonObj = null;
        if(obj != null){
            //调试用,发布时清除
            logger.info("后端返回对象:{}", obj);
            JsonConfig jsonConfig = new JsonConfig(); 
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            jsonObj = JSONObject.fromObject(obj, jsonConfig);
            logger.info("后端返回数据:" + jsonObj);
            if(HttpConstants.SERVICE_RESPONSE_SUCCESS_CODE.equals(jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_FLAG))){
                jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
                jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
            }else{
                jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
                String errMsg = jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_MSG);
                jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errMsg==null?HttpConstants.SERVICE_RESPONSE_NULL:errMsg);
            }
        }
        logger.info("输出结果:{}", jsonObj.toString());
        return jsonObj.toString();
    }

    /**
     * 返回成功
     * @param obj 输出对象
     * @return 输出成功的JSON格式数据
     */
    public String responseSuccess(Object obj){
        JSONObject jsonObj = null;
        if(obj != null){
            logger.info("后端返回对象:{}", obj);
            JsonConfig jsonConfig = new JsonConfig(); 
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            jsonObj = JSONObject.fromObject(obj, jsonConfig);
            logger.info("后端返回数据:" + jsonObj);
            jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
            jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
        }
        logger.info("输出结果:{}", jsonObj.toString());
        return jsonObj.toString();
    }

    /**
     * 返回成功
     * @param obj 输出对象
     * @return 输出成功的JSON格式数据
     */
    public String responseArraySuccess(Object obj){
        JSONArray jsonObj = null;
        if(obj != null){
            logger.info("后端返回对象:{}", obj);
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            jsonObj = JSONArray.fromObject(obj, jsonConfig);
            logger.info("后端返回数据:" + jsonObj);
        }
        logger.info("输出结果:{}", jsonObj.toString());
        return jsonObj.toString();
    }

    /**
     * 返回成功
     * @param obj 输出对象
     * @return 输出成功的JSON格式数据
     */
    public String responseSuccess(Object obj, String msg){
        JSONObject jsonObj = null;
        if(obj != null){
            logger.info("后端返回对象:{}", obj);
            JsonConfig jsonConfig = new JsonConfig(); 
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            jsonObj = JSONObject.fromObject(obj, jsonConfig);
            logger.info("后端返回数据:" + jsonObj);
            jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
            jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, msg);
        }
        logger.info("输出结果:{}", jsonObj.toString());
        return jsonObj.toString();
    }

    /**
     * 返回失败
     * @param errorMsg 错误信息
     * @return 输出失败的JSON格式数据
     */
    public String responseFail(String errorMsg){
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
        jsonObj.put(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errorMsg);
        logger.info("输出结果:{}", jsonObj.toString());
        return jsonObj.toString();
    }

}

登录管理类HomeController

package com.kj.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 功能概要:HomeController
 * 
 * @author KJ
 * @since  2016-08-15
 */
@Controller  
public class HomeController {  

    @RequestMapping(value="/login",method=RequestMethod.GET)  
    public String loginForm(Model model){  
        return "login";  
    }  

    @RequestMapping(value="/login",method=RequestMethod.POST)  
    public String login(HttpServletRequest req, HttpServletResponse response, RedirectAttributes redirectAttributes){  
        try {  
            String username = req.getParameter("username");
            if (username == null || username.trim().length() == 0) {
                redirectAttributes.addFlashAttribute("message", "用户名不能为空");
                return "redirect:login";
            }
            String password = req.getParameter("password");
            if (password == null || password.trim().length() == 0) {
                redirectAttributes.addFlashAttribute("message", "密码不能为空");
                return "redirect:login";
            }
            Subject subject= SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(username, password));  
            return "redirect:/user/";  
        } catch (AuthenticationException e) {  
            redirectAttributes.addFlashAttribute("message","用户名或密码错误");
            e.printStackTrace();
            return "redirect:login";  
        }  
    }  

    @RequestMapping(value="/logout",method=RequestMethod.GET)    
    public String logout(HttpServletRequest req,RedirectAttributes redirectAttributes ){   
        //使用权限配置管理工具进行用户的退出,跳出登录,给出提示信息  
        redirectAttributes.addFlashAttribute("message", "您已安全退出");    
        return "redirect:login";  
    }   

    @RequestMapping("/unauthorizedUrl")  
    public String unauthorizedRole(){  
        //未授权角色用户跳转到unauthorizedTip.jsp页面
        return "unauthorizedTip";  
    }  
}  

用户控制类UserController

package com.kj.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kj.service.IUserService;
import com.kj.util.PagedResult;
import com.kj.domain.User;

/**
 * 功能概要:UserController
 * 
 * @author KJ
 * @since  2016-08-15
 */
@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IUserService userService;

    /**
     * 显示首页
     * @return
     */
    @RequestMapping("/")  
    public String userManage(){
        return "user/userList";
    }

    /**
     * 测试是否具有访问增加路径权限
     * @return
     */
    @RequestMapping("/add")  
    public String userAdd(){
        return "user/add/userList";
    }

    /**
     * 测试是否具有访问删除路径权限
     * @return
     */
    @RequestMapping("/del")  
    public String userDel(){
        return "user/del/userList";
    }

    /**
     * 测试是否具有访问编辑路径权限
     * @return
     */
    @RequestMapping("/edit")  
    public String userEdit(){
        return "user/edit/userList";
    }

    /**
     * 分页查询用户信息
     * @param page
     * @return
     */
    @RequestMapping(value="/list", method= RequestMethod.POST)
    @ResponseBody
    public String list(Integer pageNumber,Integer pageSize ,String userName) {
        logger.info("分页查询用户信息列表请求入参:pageNumber{},pageSize{}", pageNumber,pageSize);
        try {
            PagedResult pageResult = userService.queryByPage(userName, pageNumber,pageSize);
            return responseSuccess(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return responseFail(e.getMessage());
        }
    }
}

返回json数据封装类JsonDateValueProcessor

package com.kj.json;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author KJ
 * @since 2016-08-15
 */
public class JsonDateValueProcessor implements JsonValueProcessor {

    /**
     * datePattern
     */
    private String datePattern = "yyyy-MM-dd HH:mm:ss";

    /**
     * JsonDateValueProcessor
     */
    public JsonDateValueProcessor() {
        super();
    }

    /**
     * @param format
     */
    public JsonDateValueProcessor(String format) {
        super();
        this.datePattern = format;
    }

    /**
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * @param key
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * process
     *
     * @param value
     * @return
     */
    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK);
                return sdf.format((Date) value);
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }

    }

    /**
     * @return the datePattern
     */
    public String getDatePattern() {
        return datePattern;
    }

    /**
     * @param pDatePattern the datePattern to set
     */
    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;
    }

}

为了登录时候避免登录URL出现JSESSIONID后缀,对shiro框架filter类进行了重写,对应的两个类如下:
MyShiroHttpServletResponse类

package com.kj.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.ShiroHttpServletResponse;

public class MyShiroHttpServletResponse extends ShiroHttpServletResponse {
    public MyShiroHttpServletResponse(HttpServletResponse wrapped, ServletContext context, ShiroHttpServletRequest request) {
        super(wrapped, context, request);
    }

    @Override
    protected String toEncoded(String url, String sessionId) {
        if ((url == null) || (sessionId == null))
            return (url);
        String path = url;
        String query = "";
        String anchor = "";
        int question = url.indexOf('?');
        if (question >= 0) {
            path = url.substring(0, question);
            query = url.substring(question);
        }
        int pound = path.indexOf('#');
        if (pound >= 0) {
            anchor = path.substring(pound);
            path = path.substring(0, pound);
        }
        StringBuilder sb = new StringBuilder(path);
        // 重写toEncoded方法,注释掉这几行代码就不会再生成JESSIONID了。
        // if (sb.length() > 0) { // session id param can't be first.
        // sb.append(";");
        // sb.append(DEFAULT_SESSION_ID_PARAMETER_NAME);
        // sb.append("=");
        // sb.append(sessionId);
        // }
        sb.append(anchor);
        sb.append(query);
        return (sb.toString());
    }
}

MyShiroFilterFactoryBean类

package com.kj.filter;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.BeanInitializationException;

public class MyShiroFilterFactoryBean extends ShiroFilterFactoryBean { 

    @Override  
      public Class getObjectType() {  
            return MySpringShiroFilter.class;  
      } 

    @Override
    protected AbstractShiroFilter createInstance() throws Exception {

        SecurityManager securityManager = getSecurityManager();
        if (securityManager == null) {
            String msg = "SecurityManager property must be set.";
            throw new BeanInitializationException(msg);
        }

        if (!(securityManager instanceof WebSecurityManager)) {
            String msg = "The security manager does not implement the WebSecurityManager interface.";
            throw new BeanInitializationException(msg);
        }
        FilterChainManager manager = createFilterChainManager();

        PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
        chainResolver.setFilterChainManager(manager);

        return new MySpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
    }

    private static final class MySpringShiroFilter extends AbstractShiroFilter {  

        protected MySpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {  
          super();  
          if (webSecurityManager == null) {  
            throw new IllegalArgumentException("WebSecurityManager property cannot be null.");  
          }  
          setSecurityManager(webSecurityManager);  
          if (resolver != null) {  
            setFilterChainResolver(resolver);  
          }  
        }  

        @Override  
        protected ServletResponse wrapServletResponse(HttpServletResponse orig, ShiroHttpServletRequest request) {  
          return new MyShiroHttpServletResponse(orig, getServletContext(), request);  
        }  
    }
}

然后自定义一个权限控制类MyShiro,用来管理用户角色权限的。

package com.kj.filter;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kj.domain.Role;
import com.kj.domain.User;
import com.kj.service.IUserService;

/**
 * 
 * @author KJ
 * @since 2016-8-15
 */
@Service
@Transactional
public class MyShiro extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录时输入的用户名
        String loginName = (String) principalCollection.fromRealm(getName()).iterator().next();
        // 到数据库查是否有此对象
        User user = userService.selectUserRoleByUserName(loginName);
        if (user != null) {
            // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 用户的角色集合名字
            info.setRoles(user.getRolesName());
            // 用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要
            List roleList = user.getRoles();
            for (Role role : roleList) {
                info.addStringPermissions(role.getPermissionsName());
            }
            return info;
        }
        return null;
    }

    /**
     * 登录认证;
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 查出是否有此用户
        User user = userService.selectUserRoleByUserName(token.getUsername());
        if (user != null) {
            // 若存在,将此用户存放到登录认证info中
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        }
        return null;
    }

}

至此,所有的java代码都已经给出。下面来给出相应的配置文件

首先是web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Archetype Created Web Applicationdisplay-name>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>
            classpath:application.xml
            classpath:applicationContext-shiro.xml
        param-value>
    context-param>
    
    <context-param>
        <param-name>webAppRootKeyparam-name>
        <param-value>springmvc.rootparam-value>
    context-param>

    
    <filter>
        <filter-name>SpringEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <context-param>
        <param-name>logbackConfigLocationparam-name>
        <param-value>classpath:logback.xmlparam-value>
    context-param>
    <listener>
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListenerlistener-class>
    listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            
            <param-value>classpath:springmvc/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

        
    <filter>    
        <filter-name>shiroFilterfilter-name>    
        <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>    
    filter>    
    <filter-mapping>    
        <filter-name>shiroFilterfilter-name>    
        <url-pattern>/*url-pattern>    
    filter-mapping>  

    
    <error-page>
        
        <error-code>404error-code>
        <location>/WEB-INF/errorpage/404.jsplocation>
    error-page>
    <error-page>
        
        <error-code>405error-code>
        <location>/WEB-INF/errorpage/405.jsplocation>
    error-page>
    <error-page>
        
        <error-code>500error-code>
        <location>/WEB-INF/errorpage/500.jsplocation>
    error-page>
web-app>

然后是application.xml


<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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="  
           http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
           http://www.springframework.org/schema/aop  
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-4.0.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
           http://www.springframework.org/schema/cache  
           http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

    
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    bean>

       
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:properties/*.propertiesvalue>
                
            list>
        property>
    bean>

    
    <context:component-scan base-package="com.kj.service">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    
    <context:annotation-config />
    
    <context:spring-configured />
    

    
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>    

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
          
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>  
        <property name="username" value="${jdbc.username}"/>  
        <property name="password" value="${jdbc.password}"/>  

          
        <property name="initialSize" value="${ds.initialSize}"/>  
        <property name="minIdle" value="${ds.minIdle}"/>  
        <property name="maxActive" value="${ds.maxActive}"/>  

          
        <property name="maxWait" value="${ds.maxWait}"/>  

          
        <property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>  

          
        <property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>  

        <property name="validationQuery" value="SELECT 'x'"/>  
        <property name="testWhileIdle" value="true"/>  
        <property name="testOnBorrow" value="false"/>  
        <property name="testOnReturn" value="false"/>  

          
        <property name="poolPreparedStatements" value="false"/>  
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>  

          
        <property name="filters" value="stat"/>  
    bean>  

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"
            value="com.kj.dao" />
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:com/kj/mapper/*.xml"/>  
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
    bean>

  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
      
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
              
            <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>  
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>  
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>  
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>  
              
            <tx:method name="select*" read-only="true"/>  
            <tx:method name="count*" read-only="true"/>  
            <tx:method name="get*" read-only="true"/>  
              
            <tx:method name="*"/>  
        tx:attributes>  
    tx:advice>  

      
    <aop:config>  
        <aop:pointcut id="serviceMethods" expression="execution(* com.kj.service..*(..))"/>  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>  
    aop:config>  

      
    <aop:aspectj-autoproxy proxy-target-class="true"/>  

      
    <tx:annotation-driven transaction-manager="transactionManager"/>  

      
    <cache:annotation-driven cache-manager="cacheManagers"/> 
    <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache.xml" />  
    bean>  

    <bean id="cacheManagers" class="org.springframework.cache.ehcache.EhCacheCacheManager">      
        <property name="cacheManager"  ref="ehCacheManagerFactory"/>      
    bean>  
beans>

jdbc.properties数据库连接配置

##JDBC Global Setting  
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/quick4j?useUnicode=true&;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

##DataSource Global Setting  

#配置初始化大小、最小、最大  
ds.initialSize=1
ds.minIdle=1
ds.maxActive=20

#配置获取连接等待超时的时间   
ds.maxWait=60000

#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒  
ds.timeBetweenEvictionRunsMillis=60000

#配置一个连接在池中最小生存的时间,单位是毫秒  
ds.minEvictableIdleTimeMillis=300000

mybatis-config.xml 分页插件配置

  
  
<configuration>    

<plugins>
    
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <property name="dialect" value="mysql"/>
        
        
        
        <property name="offsetAsPageNum" value="true"/>
        
        
        <property name="rowBoundsWithCount" value="true"/>
        
        
        <property name="pageSizeZero" value="true"/>
        
        
        
        <property name="reasonable" value="true"/>
        
        
        
        
        <property name="params" value="pageNum=start;pageSize=limit;"/>
    plugin>
plugins>
configuration>

spring缓存配置ehcache.xml


<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

<diskStore path="java.io.tmpdir"/>



<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
ehcache>

applicationContext-shiro.xml shiro权限框架配置文件

  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    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/tx http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  

    <bean id="myShiro" class="com.kj.filter.MyShiro" />

      
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
          
        <property name="cacheManager" ref="cacheManager"/>   
        <property name="sessionMode" value="native"/>
          
        <property name="realm" ref="myShiro"/>    
        <property name="sessionManager" ref="sessionManager"/>
    bean>  
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        
       
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" />
        
    bean>
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionDAO" ref="sessionDAO"/>
    bean>
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
    bean>


    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    bean>

      
    <bean id="shiroFilter" class="com.kj.filter.MyShiroFilterFactoryBean">   
           
        <property name="securityManager" ref="securityManager"/>   
           
        <property name="loginUrl" value="/login"/>    
          
        <property name="successUrl" value="/user/"/>    
          
        <property name="unauthorizedUrl" value="/unauthorizedUrl"/>    
          
        <property name="filterChainDefinitions">    
            <value>    
              

                  
                /static/**=anon  
                /logout=logout
                  
               
                  
                /user/add/**=roles[admin,manager]  
                /user/del/**=perms[user:create]  
                /user/edit/**=roles[admin]  
                    
                /** = authc  
            value>    
        property>    
    bean>  

beans>  

shiro缓存配置文件ehcache-shiro.xml


    "java.io.tmpdir/tuan-oauth"/>


    "10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />
    -- We want eternal="true" (with no timeToIdle or timeToLive settings) because Shiro manages session
expirations explicitly.  If we set it to false and then set corresponding timeToIdle and timeToLive properties,
ehcache would evict sessions without Shiro's knowledge, which would cause many problems
(e.g. "My Shiro session timeout is 30 minutes - why isn't a session available after 2 minutes?"
Answer - ehcache expired it due to the timeToIdle property set to 120 seconds.)
diskPersistent=true since we want an enterprise session management feature - ability to use sessions after
even after a JVM restart.  -->
    name="shiro-activeSessionCache"
           maxElementsInMemory="10000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>
    name="shiro.authorizationCache"
           maxElementsInMemory="100"
           eternal="false"
           timeToLiveSeconds="600"
           overflowToDisk="false"/>

spring mvc配置文件spring-mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    
    <context:component-scan base-package="com.kj.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    context:component-scan>

    
    <mvc:annotation-driven validator="validator" conversion-service="conversionService" content-negotiation-manager="contentNegotiationManager">
        <mvc:message-converters register-defaults="true">
            
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
                <property name = "supportedMediaTypes">
                    <list>
                        <bean class="org.springframework.http.MediaType">
                            <constructor-arg index="0" value="text"/>
                            <constructor-arg index="1" value="plain"/>
                            <constructor-arg index="2" value="UTF-8"/>
                        bean>
                        <bean class="org.springframework.http.MediaType">
                            <constructor-arg index="0" value="*"/>
                            <constructor-arg index="1" value="*"/>
                            <constructor-arg index="2" value="UTF-8"/>
                        bean>
                    list>
                property>
            bean>
            
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8value>
                    list>
                property>
                
                
                
            bean>
        mvc:message-converters>

        <mvc:argument-resolvers>
            <bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver" />
        mvc:argument-resolvers>
    mvc:annotation-driven>


    
    
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        
        <property name="favorPathExtension" value="true"/>
        
        <property name="favorParameter" value="true"/>
        <property name="parameterName" value="format"/>
        
        <property name="ignoreAcceptHeader" value="false"/>

        <property name="mediaTypes"> 
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            value>
        property>
        
        <property name="defaultContentType" value="text/html"/>
    bean>

    
    <mvc:default-servlet-handler />  
    
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>


    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>


    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760000"/>
        <property name="maxInMemorySize" value="40960"/>
    bean>

    
    


beans>

日志输出 配置logback.xml


<configuration>
    
    <property name="log.root.level" value="${log.root.level}" /> 
    <property name="log.other.level" value="${log.other.level}" /> 
    <property name="log.base" value="${log.base}" /> 
    <property name="log.moduleName" value="${log.moduleName}" />  
    <property name="log.max.size" value="100MB" /> 

    
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%nPattern>
        encoder>
    appender>

    
    <appender name="file.all" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}.logFile>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
            FileNamePattern>
            
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}maxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%npattern>
        layout>
    appender>

    
    <appender name="file.all.other" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}_other.logFile>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_other_%d{yyyy-MM-dd}.%i.log.zip
            FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}maxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L -%msg%npattern>
        layout>
    appender>

    
    <appender name="file.error"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}_err.logFile>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_err_%d{yyyy-MM-dd}.%i.log.zip
            FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}maxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L - %msg%npattern>
        layout>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

   
    
    
    <appender name="file.async" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0discardingThreshold>
        <queueSize>256queueSize>
        <includeCallerData>trueincludeCallerData>
        <appender-ref ref="file.all" />
    appender>

    <appender name="file.async.other" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0discardingThreshold>
        <queueSize>256queueSize>
        <includeCallerData>trueincludeCallerData>
        <appender-ref ref="file.all.other" />
    appender>

    
    <logger name="com.kj" additivity="false">
        <level value="${log.root.level}" />
        <appender-ref ref="stdout" /> 
        <appender-ref ref="file.async" />
        <appender-ref ref="file.error" />
    logger>

    
    <root level="${log.root.level}">
        <appender-ref ref="stdout" /> 
        <appender-ref ref="file.async.other" />
        <appender-ref ref="file.error" />
    root>
configuration>

至此,所有的配置文件已给出,下面给出相应的jsp页面

首先是登录页面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  
<html>  
  <head>  
    <title>登录页面title>  
  head>  

  <body>  
    <h1>登录页面----${message }h1>  
    <img alt="" src="<%=request.getContextPath()%>/static/image/1.jpg"> 
    <br/><br/>
    <form action="<%=request.getContextPath()%>/login" method="post">  
        用户名:<input name="username" value="${username }"/><br/><br/> 
        密   码:<input type="password" name="password" value="${password }"/><br/><br/>
      <input type="submit" value="提交"/>
    form>  
  body>  
html>  

如果登录成功,跳转到view目录下的userList.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> 

<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap分页实例用户列表title>
<link href="${pageContext.request.contextPath}/static/js/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/static/js/jQuery/jquery-2.1.4.min.js">script>
<script src="${pageContext.request.contextPath}/static/js/bootstrap/js/bootstrap.min.js">script>
<script src="${pageContext.request.contextPath}/static/js/bootstrap/js/bootstrap-paginator.min.js">script>
<style type="text/css">
#queryDiv {
 margin-right: auto;
 margin-left: auto;
 width:600px;
}
#textInput {
 margin-top: 10px;
}
#tableResult {
 margin-right: auto;
 margin-left: auto;
 width:600px;
}
td {
 width:150px
}
style>
head>
<body>

    <h1>用户列表--<a href="${pageContext.request.contextPath}/user/add">添加用户a>---<a href="${pageContext.request.contextPath}/logout">退出登录a>    h1> 
    <h2>权限列表h2>  
    <shiro:authenticated>用户已经登录显示此内容<br/>shiro:authenticated>  
    <shiro:hasRole name="manager">manager角色登录显示此内容<br/>shiro:hasRole>  
    <shiro:hasRole name="admin">admin角色登录显示此内容<br/>shiro:hasRole>  
    <shiro:hasRole name="normal">normal角色登录显示此内容<br/>shiro:hasRole>  

    <shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用户登录显示此内容**<br/>shiro:hasAnyRoles>  
    <shiro:principal/>-显示当前登录用户名  <br/>
    <shiro:hasPermission name="add">add权限用户显示此内容<br/>shiro:hasPermission>  
    <shiro:hasPermission name="user:create">user:create权限用户显示此内容<br/><shiro:principal/>shiro:hasPermission>  
    <shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容<br/> shiro:lacksPermission>  

    <div id = "queryDiv">
        <input id = "textInput" type="text" placeholder="请输入用户名" >
        <button id = "queryButton" class="btn btn-primary" type="button">查询button>
    div>
    <form id="form1">
        <table class="table table-bordered" id = 'tableResult'>
            <caption>查询用户结果caption>
            <thead>
                <tr>
                    <th>序号th>
                    <th>用户名th>
                    <th>密码th>
                    <th>状态th>
                    <th width="200px">创建时间th>
                tr>
            thead>
            <tbody id="tableBody">
            tbody>
        table>
        
        <div id="bottomTab">div>
    form>
    <script type='text/javascript'>    
        var PAGESIZE = 10;
        var options = {  
            currentPage: 1,  //当前页数
            totalPages: 10,  //总页数,这里只是暂时的,后头会根据查出来的条件进行更改
            size:"normal",  
            alignment:"center",  
            itemTexts: function (type, page, current) {  
                switch (type) {  
                    case "first":  
                        return "第一页";  
                    case "prev":  
                        return "前一页";  
                    case "next":  
                        return "后一页";  
                    case "last":  
                        return "最后页";  
                    case "page":  
                        return  page;  
                }                 
            },  
            onPageClicked: function (e, originalEvent, type, page) {  
                var userName = $("#textInput").val(); //取内容
                buildTable(userName,page,PAGESIZE);//默认每页最多10条
            }  
        }  

        //获取当前项目的路径
        var urlRootContext = (function () {
            var strPath = window.document.location.pathname;
            var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
            return postPath;
        })();


        //生成表格
        function buildTable(userName,pageNumber,pageSize) {
             var url =  urlRootContext + "/user/list"; //请求的网址
             var reqParams = {'userName':userName, 'pageNumber':pageNumber,'pageSize':pageSize};//请求数据
             $(function () {   
                  $.ajax({
                        type:"POST",
                        url:url,
                        data:reqParams,
                        async:false,
                        dataType:"json",
                        success: function(data){
                            if(data.isError == false) {
                           // options.totalPages = data.pages;
                        var newoptions = {  
                        currentPage: data.pageNum < 1 ? 1 : data.pageNum,  //当前页数
                        totalPages: data.pages==0?1:data.pages,  //总页数
                        size:"normal",  
                        alignment:"center",  
                        itemTexts: function (type, page, current) {  
                        switch (type) {  
                            case "first":  
                            return "第一页";  
                            case "prev":  
                            return "前一页";  
                            case "next":  
                            return "后一页";  
                            case "last":  
                            return "最后页";  
                        case "page":  
                        return  page;  
                }                 
            },  
            onPageClicked: function (e, originalEvent, type, page) {  
                var userName = $("#textInput").val(); //取内容
                buildTable(userName,page,PAGESIZE);//默认每页最多10条
            }  
         }                         
         $('#bottomTab').bootstrapPaginator("setOptions",newoptions); //重新设置总页面数目
         var dataList = data.dataList;
         $("#tableBody").empty();//清空表格内容
         if (dataList.length > 0 ) {
             $(dataList).each(function(){//重新生成
                    $("#tableBody").append('');
                    $("#tableBody").append('' + this.id + '');
                    $("#tableBody").append('' + this.username + '');
                    $("#tableBody").append('' + this.password + '');
                    $("#tableBody").append('' + this.state + '');
                    $("#tableBody").append('' + this.create_time + '');
                    $("#tableBody").append('');
                    });  
                    } else {                                
                          $("#tableBody").append('
查询无数据
'
); } }else{ alert(data.errorMsg); } }, error: function(e){ alert("查询失败:" + e); } }); }); } //渲染完就执行 $(function() { //生成底部分页栏 $('#bottomTab').bootstrapPaginator(options); buildTable("",1,10);//默认空白查全部 //创建结算规则 $("#queryButton").bind("click",function(){ var userName = $("#textInput").val(); buildTable(userName,1,PAGESIZE); }); });
script> body> html>

当访问没有权限的路径,系统会自动跳转到没有权限的提示页面unauthorizedTip.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<script>

script>
<body>
<h2>对不起,您没有权限访问该资源路径,请联系管理授权。h2>
<a href="login">重新登录a>
body>
html>

至此,所有文件代码均已提供,运行tomcat,访问地址:http://localhost:8080/HelloHome/login即可看到登录页:
spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页_第4张图片

登录成功后跳转到用户分页列表如下:
spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页_第5张图片

你可能感兴趣的:(JAVA,Web编程宝典)