├── Redis-x64-3.0.500.zip ├── init └── sql │ └── init_shiro.sql ├── pom.xml ├── readme.md └── src └── main ├── java └── com │ └── sojson │ ├── common │ ├── controller │ │ ├── BaseController.java │ │ └── CommonController.java │ ├── dao │ │ ├── UPermissionMapper.java │ │ ├── URoleMapper.java │ │ ├── URolePermissionMapper.java │ │ ├── UUserMapper.java │ │ └── UUserRoleMapper.java │ ├── model │ │ ├── UPermission.java │ │ ├── URole.java │ │ ├── URolePermission.java │ │ ├── UUser.java │ │ └── UUserRole.java │ ├── timer │ │ └── ToTimer.java │ └── utils │ │ ├── CookieUtil.java │ │ ├── DateUtil.java │ │ ├── LoggerUtils.java │ │ ├── MathUtil.java │ │ ├── SerializeUtil.java │ │ ├── SpringContextUtil.java │ │ ├── StringUtils.java │ │ ├── UtilPath.java │ │ ├── VerifyCodeUtils.java │ │ ├── VinuxPostMethod.java │ │ └── vcode │ │ ├── Captcha.java │ │ ├── Encoder.java │ │ ├── GifCaptcha.java │ │ ├── GifEncoder.java │ │ ├── Quant.java │ │ ├── Randoms.java │ │ └── SpecCaptcha.java │ ├── core │ ├── config │ │ ├── IConfig.java │ │ ├── INI4j.java │ │ └── QQConfig.java │ ├── freemarker │ │ ├── extend │ │ │ ├── Ferrmarker.java │ │ │ ├── FreeMarkerConfigExtend.java │ │ │ └── FreeMarkerViewExtend.java │ │ └── utils │ │ │ └── FreemarkerTagUtil.java │ ├── mybatis │ │ ├── BaseMybatisDao.java │ │ └── page │ │ │ ├── Dialect.java │ │ │ ├── MysqlDialect.java │ │ │ ├── OracleDialect.java │ │ │ ├── Paginable.java │ │ │ ├── Pagination.java │ │ │ └── SimplePage.java │ ├── shiro │ │ ├── CustomShiroSessionDAO.java │ │ ├── cache │ │ │ ├── JedisManager.java │ │ │ ├── JedisShiroCache.java │ │ │ ├── JedisShiroSessionRepository.java │ │ │ ├── ShiroCacheManager.java │ │ │ ├── VCache.java │ │ │ └── impl │ │ │ │ ├── CustomShiroCacheManager.java │ │ │ │ └── JedisShiroCacheManager.java │ │ ├── filter │ │ │ ├── KickoutSessionFilter.java │ │ │ ├── LoginFilter.java │ │ │ ├── PermissionFilter.java │ │ │ ├── RoleFilter.java │ │ │ ├── ShiroFilterUtils.java │ │ │ └── SimpleAuthFilter.java │ │ ├── listenter │ │ │ └── CustomSessionListener.java │ │ ├── service │ │ │ ├── ShiroManager.java │ │ │ └── impl │ │ │ │ └── ShiroManagerImpl.java │ │ ├── session │ │ │ ├── CustomSessionManager.java │ │ │ ├── SessionStatus.java │ │ │ └── ShiroSessionRepository.java │ │ └── token │ │ │ ├── SampleRealm.java │ │ │ ├── ShiroToken.java │ │ │ └── manager │ │ │ └── TokenManager.java │ ├── statics │ │ ├── APPKEY.java │ │ └── Constant.java │ └── tags │ │ ├── APITemplateModel.java │ │ ├── SuperCustomTag.java │ │ └── WYFTemplateModel.java │ ├── permission │ ├── bo │ │ ├── RolePermissionAllocationBo.java │ │ ├── UPermissionBo.java │ │ ├── URoleBo.java │ │ └── UserRoleAllocationBo.java │ ├── controller │ │ ├── PermissionAllocationController.java │ │ ├── PermissionController.java │ │ ├── RoleController.java │ │ └── UserRoleAllocationController.java │ └── service │ │ ├── PermissionService.java │ │ ├── RoleService.java │ │ └── impl │ │ ├── PermissionServiceImpl.java │ │ └── RoleServiceImpl.java │ └── user │ ├── bo │ ├── SubmitDto.java │ └── UserOnlineBo.java │ ├── controller │ ├── DemoTestSubmitController.java │ ├── MemberController.java │ ├── UserCoreController.java │ └── UserLoginController.java │ ├── manager │ └── UserManager.java │ └── service │ ├── UUserService.java │ └── impl │ └── UUserServiceImpl.java ├── resources ├── config.properties ├── jdbc.properties ├── log4j.properties ├── mapper │ ├── UPermissionMapper.xml │ ├── URoleMapper.xml │ ├── URolePermissionMapper.xml │ ├── UUserMapper.xml │ └── UUserRoleMapper.xml ├── mybatis-config.xml ├── shiro-config.properties ├── shiro_base_auth.ini ├── spring-cache.xml ├── spring-mvc.xml ├── spring-mybatis.xml ├── spring-shiro.xml ├── spring-timer.xml └── spring.xml └── webapp ├── META-INF └── MANIFEST.MF ├── WEB-INF ├── ftl │ ├── common │ │ ├── 404.ftl │ │ ├── 500.ftl │ │ ├── config │ │ │ ├── left.ftl │ │ │ ├── menu.ftl │ │ │ └── top.ftl │ │ ├── kicked_out.ftl │ │ └── unauthorized.ftl │ ├── demo │ │ └── index.ftl │ ├── member │ │ ├── list.ftl │ │ ├── online.ftl │ │ └── onlineDetails.ftl │ ├── permission │ │ ├── allocation.ftl │ │ ├── index.ftl │ │ └── mypermission.ftl │ ├── role │ │ ├── allocation.ftl_bak │ │ └── index.ftl │ └── user │ │ ├── index.ftl │ │ ├── login.ftl │ │ ├── register.ftl │ │ ├── updatePswd.ftl │ │ └── updateSelf.ftl ├── views │ ├── common │ │ └── config │ │ │ └── top.jsp │ └── role │ │ └── allocation.jsp └── web.xml ├── css └── common │ └── base.css ├── favicon.ico ├── js ├── common │ ├── bootstrap │ │ ├── 3.3.5 │ │ │ ├── css │ │ │ │ └── bootstrap.min.css │ │ │ ├── fonts │ │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ │ └── glyphicons-halflings-regular.woff2 │ │ │ └── js │ │ │ │ └── bootstrap.min.js │ │ └── bootstrap-treeview.js │ └── layer │ │ ├── extend │ │ └── layer.ext.js │ │ ├── layer.js │ │ └── skin │ │ ├── default │ │ ├── icon-ext.png │ │ ├── icon.png │ │ ├── loading-0.gif │ │ ├── loading-1.gif │ │ └── loading-2.gif │ │ ├── layer.css │ │ └── layer.ext.css ├── shiro.demo.js └── user.login.js └── user └── index.shtml /Redis-x64-3.0.500.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/Redis-x64-3.0.500.zip -------------------------------------------------------------------------------- /init/sql/init_shiro.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SQLyog Enterprise v12.09 (64 bit) 3 | MySQL - 5.5.23 : Database - shiro 4 | ********************************************************************* 5 | */ 6 | 7 | 8 | /*!40101 SET NAMES utf8 */; 9 | 10 | /*!40101 SET SQL_MODE=''*/; 11 | 12 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 13 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 14 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 15 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 16 | CREATE DATABASE /*!32312 IF NOT EXISTS*/`shiro` /*!40100 DEFAULT CHARACTER SET utf8 */; 17 | 18 | USE `shiro`; 19 | 20 | /*Table structure for table `u_permission` */ 21 | 22 | DROP TABLE IF EXISTS `u_permission`; 23 | 24 | CREATE TABLE `u_permission` ( 25 | `id` bigint(20) NOT NULL AUTO_INCREMENT, 26 | `url` varchar(256) DEFAULT NULL COMMENT 'url地址', 27 | `name` varchar(64) DEFAULT NULL COMMENT 'url描述', 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; 30 | 31 | /*Data for the table `u_permission` */ 32 | 33 | insert into `u_permission`(`id`,`url`,`name`) values (4,'/permission/index.shtml','权限列表'),(6,'/permission/addPermission.shtml','权限添加'),(7,'/permission/deletePermissionById.shtml','权限删除'),(8,'/member/list.shtml','用户列表'),(9,'/member/online.shtml','在线用户'),(10,'/member/changeSessionStatus.shtml','用户Session踢出'),(11,'/member/forbidUserById.shtml','用户激活&禁止'),(12,'/member/deleteUserById.shtml','用户删除'),(13,'/permission/addPermission2Role.shtml','权限分配'),(14,'/role/clearRoleByUserIds.shtml','用户角色分配清空'),(15,'/role/addRole2User.shtml','角色分配保存'),(16,'/role/deleteRoleById.shtml','角色列表删除'),(17,'/role/addRole.shtml','角色列表添加'),(18,'/role/index.shtml','角色列表'),(19,'/permission/allocation.shtml','权限分配'),(20,'/role/allocation.shtml','角色分配'); 34 | 35 | /*Table structure for table `u_role` */ 36 | 37 | DROP TABLE IF EXISTS `u_role`; 38 | 39 | CREATE TABLE `u_role` ( 40 | `id` bigint(20) NOT NULL AUTO_INCREMENT, 41 | `name` varchar(32) DEFAULT NULL COMMENT '角色名称', 42 | `type` varchar(10) DEFAULT NULL COMMENT '角色类型', 43 | PRIMARY KEY (`id`) 44 | ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; 45 | 46 | /*Data for the table `u_role` */ 47 | 48 | insert into `u_role`(`id`,`name`,`type`) values (1,'系统管理员','888888'),(3,'权限角色','100003'),(4,'用户中心','100002'); 49 | 50 | /*Table structure for table `u_role_permission` */ 51 | 52 | DROP TABLE IF EXISTS `u_role_permission`; 53 | 54 | CREATE TABLE `u_role_permission` ( 55 | `rid` bigint(20) DEFAULT NULL COMMENT '角色ID', 56 | `pid` bigint(20) DEFAULT NULL COMMENT '权限ID' 57 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 58 | 59 | /*Data for the table `u_role_permission` */ 60 | 61 | insert into `u_role_permission`(`rid`,`pid`) values (4,8),(4,9),(4,10),(4,11),(4,12),(3,4),(3,6),(3,7),(3,13),(3,14),(3,15),(3,16),(3,17),(3,18),(3,19),(3,20),(1,4),(1,6),(1,7),(1,8),(1,9),(1,10),(1,11),(1,12),(1,13),(1,14),(1,15),(1,16),(1,17),(1,18),(1,19),(1,20); 62 | 63 | /*Table structure for table `u_user` */ 64 | 65 | DROP TABLE IF EXISTS `u_user`; 66 | 67 | CREATE TABLE `u_user` ( 68 | `id` bigint(20) NOT NULL AUTO_INCREMENT, 69 | `nickname` varchar(20) DEFAULT NULL COMMENT '用户昵称', 70 | `email` varchar(128) DEFAULT NULL COMMENT '邮箱|登录帐号', 71 | `pswd` varchar(32) DEFAULT NULL COMMENT '密码', 72 | `create_time` datetime DEFAULT NULL COMMENT '创建时间', 73 | `last_login_time` datetime DEFAULT NULL COMMENT '最后登录时间', 74 | `status` bigint(1) DEFAULT '1' COMMENT '1:有效,0:禁止登录', 75 | PRIMARY KEY (`id`) 76 | ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; 77 | 78 | /*Data for the table `u_user` */ 79 | 80 | insert into `u_user`(`id`,`nickname`,`email`,`pswd`,`create_time`,`last_login_time`,`status`) values (1,'管理员','admin','57dd03ed397eabaeaa395eb740b770fd','2016-06-16 11:15:33','2017-02-04 08:55:11',1),(11,'soso','8446666@qq.com','d57ffbe486910dd5b26d0167d034f9ad','2016-05-26 20:50:54','2016-06-16 11:24:35',1),(12,'8446666','8446666','4afdc875a67a55528c224ce088be2ab8','2016-05-27 22:34:19','2016-06-15 17:03:16',1); 81 | 82 | /*Table structure for table `u_user_role` */ 83 | 84 | DROP TABLE IF EXISTS `u_user_role`; 85 | 86 | CREATE TABLE `u_user_role` ( 87 | `uid` bigint(20) DEFAULT NULL COMMENT '用户ID', 88 | `rid` bigint(20) DEFAULT NULL COMMENT '角色ID' 89 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 90 | 91 | /*Data for the table `u_user_role` */ 92 | 93 | insert into `u_user_role`(`uid`,`rid`) values (12,4),(11,3),(11,4),(1,1); 94 | 95 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 96 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 97 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 98 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 99 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.controller; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.Map.Entry; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpSession; 12 | 13 | import org.apache.commons.beanutils.BeanUtils; 14 | import org.apache.log4j.Logger; 15 | import org.springframework.web.servlet.ModelAndView; 16 | import org.springframework.web.servlet.view.RedirectView; 17 | 18 | import com.sojson.common.utils.StringUtils; 19 | 20 | /** 21 | * 22 | * 开发公司:itboy.net
23 | * 版权:itboy.net
24 | *

25 | * 26 | * 27 | * 28 | *

29 | * 30 | * 区分 责任人 日期    说明
31 | * 创建 周柏成 2016年5月3日  
32 | *

33 | * ******* 34 | *

35 | * @author zhou-baicheng 36 | * @email i@itboy.net 37 | * @version 1.0,2016年5月3日
38 | * 39 | */ 40 | public class BaseController { 41 | 42 | 43 | protected int pageNo =1; 44 | public static int pageSize = 10; 45 | protected final static Logger logger = Logger.getLogger(BaseController.class); 46 | protected Map resultMap = new LinkedHashMap(); 47 | public static String URL404 = "/404.html"; 48 | 49 | private final static String PARAM_PAGE_NO = "pageNo"; 50 | 51 | protected String pageSizeName = "pageSize"; 52 | 53 | /** 54 | * 往Request里带值 55 | * @param request 56 | * @param key 57 | * @param value 58 | */ 59 | protected static void setValue2Request(HttpServletRequest request,String key,Object value){ 60 | request.setAttribute(key, value); 61 | } 62 | 63 | /** 64 | * [获取session] 65 | * @param request 66 | * @return 67 | */ 68 | public static HttpSession getSession(HttpServletRequest request){ 69 | return request.getSession(); 70 | } 71 | 72 | public int getPageNo() { 73 | return pageNo; 74 | } 75 | 76 | public void setPageNo(int pageNo) { 77 | this.pageNo = pageNo; 78 | } 79 | 80 | public int getPageSize() { 81 | return pageSize; 82 | } 83 | 84 | public void setPageSize(int pageSize) { 85 | BaseController.pageSize = pageSize; 86 | } 87 | 88 | public ModelAndView redirect(String redirectUrl,Map...parament){ 89 | ModelAndView view = new ModelAndView(new RedirectView(redirectUrl)); 90 | if(null != parament && parament.length > 0){ 91 | view.addAllObjects(parament[0]); 92 | } 93 | return view; 94 | } 95 | public ModelAndView redirect404(){ 96 | return new ModelAndView(new RedirectView(URL404)); 97 | } 98 | 99 | @SuppressWarnings("unchecked") 100 | protected Map prepareParams(Object obj, HttpServletRequest request) throws Exception { 101 | if (request != null) { 102 | String pageNoStr = (String)request.getParameter(PARAM_PAGE_NO), 103 | pageSizeStr = (String)request.getParameter(pageSizeName); 104 | if (StringUtils.isNotBlank(pageNoStr)) { 105 | pageNo = Integer.parseInt(pageNoStr); 106 | } 107 | if (StringUtils.isNotBlank(pageSizeStr)) { 108 | pageSize = Integer.parseInt(pageSizeStr); 109 | } 110 | } 111 | 112 | Map params = new HashMap(); 113 | params = BeanUtils.describe(obj); 114 | params = handleParams(params); 115 | // 回填值项 116 | //BeanUtils.populate(obj, params); 117 | return params; 118 | } 119 | private Map handleParams(Map params) { 120 | Map result = new HashMap(); 121 | if (null != params) { 122 | Set> entrySet = params.entrySet(); 123 | 124 | for (Iterator> it = entrySet.iterator(); it.hasNext(); ) { 125 | Entry entry = it.next(); 126 | if (entry.getValue() != null) { 127 | result.put(entry.getKey(), StringUtils.trimToEmpty((String)entry.getValue())); 128 | } 129 | } 130 | } 131 | return result; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/dao/UPermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.dao; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import com.sojson.common.model.UPermission; 7 | import com.sojson.permission.bo.UPermissionBo; 8 | 9 | public interface UPermissionMapper { 10 | int deleteByPrimaryKey(Long id); 11 | 12 | int insert(UPermission record); 13 | 14 | int insertSelective(UPermission record); 15 | 16 | UPermission selectByPrimaryKey(Long id); 17 | 18 | int updateByPrimaryKeySelective(UPermission record); 19 | 20 | int updateByPrimaryKey(UPermission record); 21 | 22 | List selectPermissionById(Long id); 23 | //根据用户ID获取权限的Set集合 24 | Set findPermissionByUserId(Long id); 25 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/dao/URoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import com.sojson.common.model.URole; 8 | 9 | public interface URoleMapper { 10 | int deleteByPrimaryKey(Long id); 11 | 12 | int insert(URole record); 13 | 14 | int insertSelective(URole record); 15 | 16 | URole selectByPrimaryKey(Long id); 17 | 18 | int updateByPrimaryKeySelective(URole record); 19 | 20 | int updateByPrimaryKey(URole record); 21 | 22 | Set findRoleByUserId(Long id); 23 | 24 | List findNowAllPermission(Map map); 25 | 26 | void initData(); 27 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/dao/URolePermissionMapper.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.sojson.common.model.URolePermission; 7 | 8 | public interface URolePermissionMapper { 9 | int insert(URolePermission record); 10 | 11 | int insertSelective(URolePermission record); 12 | 13 | List findRolePermissionByPid(Long id); 14 | 15 | List findRolePermissionByRid(Long id); 16 | 17 | List find(URolePermission entity); 18 | 19 | int deleteByPid(Long id); 20 | int deleteByRid(Long id); 21 | int delete(URolePermission entity); 22 | 23 | int deleteByRids(Map resultMap); 24 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/dao/UUserMapper.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.sojson.common.model.UUser; 7 | import com.sojson.permission.bo.URoleBo; 8 | 9 | public interface UUserMapper { 10 | int deleteByPrimaryKey(Long id); 11 | 12 | int insert(UUser record); 13 | 14 | int insertSelective(UUser record); 15 | 16 | UUser selectByPrimaryKey(Long id); 17 | 18 | int updateByPrimaryKeySelective(UUser record); 19 | 20 | int updateByPrimaryKey(UUser record); 21 | 22 | UUser login(Map map); 23 | 24 | UUser findUserByEmail(String email); 25 | 26 | List selectRoleByUserId(Long id); 27 | 28 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/dao/UUserRoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.sojson.common.model.UUserRole; 7 | 8 | public interface UUserRoleMapper { 9 | int insert(UUserRole record); 10 | 11 | int insertSelective(UUserRole record); 12 | 13 | int deleteByUserId(Long id); 14 | 15 | int deleteRoleByUserIds(Map resultMap); 16 | 17 | List findUserIdByRoleId(Long id); 18 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/model/UPermission.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import net.sf.json.JSONObject; 6 | 7 | /** 8 | * 9 | * 开发公司:itboy.net
10 | * 版权:itboy.net
11 | *

12 | * 13 | * 权限实体 14 | * 15 | *

16 | * 17 | * 区分 责任人 日期    说明
18 | * 创建 周柏成 2016年5月25日  
19 | *

20 | * ******* 21 | *

22 | * 23 | * @author zhou-baicheng 24 | * @email i@itboy.net 25 | * @version 1.0,2016年5月25日
26 | * 27 | */ 28 | public class UPermission implements Serializable { 29 | private static final long serialVersionUID = 1L; 30 | private Long id; 31 | /** 操作的url */ 32 | private String url; 33 | /** 操作的名称 */ 34 | private String name; 35 | 36 | public Long getId() { 37 | return id; 38 | } 39 | 40 | public void setId(Long id) { 41 | this.id = id; 42 | } 43 | 44 | public String getUrl() { 45 | return url; 46 | } 47 | 48 | public void setUrl(String url) { 49 | this.url = url; 50 | } 51 | 52 | public String getName() { 53 | return name; 54 | } 55 | 56 | public void setName(String name) { 57 | this.name = name; 58 | } 59 | 60 | public String toString() { 61 | return JSONObject.fromObject(this).toString(); 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/model/URole.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import net.sf.json.JSONObject; 8 | /** 9 | * 10 | * 开发公司:itboy.net
11 | * 版权:itboy.net
12 | *

13 | * 14 | * 权限角色 15 | * 16 | *

17 | * 18 | * 区分 责任人 日期    说明
19 | * 创建 周柏成 2016年5月25日  
20 | *

21 | * ******* 22 | *

23 | * @author zhou-baicheng 24 | * @email i@itboy.net 25 | * @version 1.0,2016年5月25日
26 | * 27 | */ 28 | public class URole implements Serializable{ 29 | private static final long serialVersionUID = 1L; 30 | private Long id; 31 | /**角色名称*/ 32 | private String name; 33 | /**角色类型*/ 34 | private String type; 35 | //***做 role --> permission 一对多处理 36 | private List permissions = new LinkedList(); 37 | 38 | public Long getId() { 39 | return id; 40 | } 41 | 42 | public void setId(Long id) { 43 | this.id = id; 44 | } 45 | 46 | public String getName() { 47 | return name; 48 | } 49 | 50 | public void setName(String name) { 51 | this.name = name; 52 | } 53 | 54 | public String getType() { 55 | return type; 56 | } 57 | 58 | public List getPermissions() { 59 | return permissions; 60 | } 61 | 62 | public void setPermissions(List permissions) { 63 | this.permissions = permissions; 64 | } 65 | 66 | public void setType(String type) { 67 | this.type = type; 68 | } 69 | public String toString(){ 70 | return JSONObject.fromObject(this).toString(); 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/model/URolePermission.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import net.sf.json.JSONObject; 6 | /** 7 | * 8 | * 开发公司:itboy.net
9 | * 版权:itboy.net
10 | *

11 | * 12 | * 角色{@link URole}和 权限{@link UPermission}中间表 13 | * 14 | *

15 | * 16 | * 区分 责任人 日期    说明
17 | * 创建 周柏成 2016年5月25日  
18 | *

19 | * ******* 20 | *

21 | * @author zhou-baicheng 22 | * @email i@itboy.net 23 | * @version 1.0,2016年5月25日
24 | * 25 | */ 26 | public class URolePermission implements Serializable{ 27 | private static final long serialVersionUID = 1L; 28 | /**{@link URole.id}*/ 29 | private Long rid; 30 | /**{@link UPermission.id}*/ 31 | private Long pid; 32 | 33 | public URolePermission() { 34 | } 35 | public URolePermission(Long rid,Long pid) { 36 | this.rid = rid; 37 | this.pid = pid; 38 | } 39 | public Long getRid() { 40 | return rid; 41 | } 42 | 43 | public void setRid(Long rid) { 44 | this.rid = rid; 45 | } 46 | 47 | public Long getPid() { 48 | return pid; 49 | } 50 | 51 | public void setPid(Long pid) { 52 | this.pid = pid; 53 | } 54 | public String toString(){ 55 | return JSONObject.fromObject(this).toString(); 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/model/UUser.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import net.sf.json.JSONObject; 7 | /** 8 | * 9 | * 开发公司:itboy.net
10 | * 版权:itboy.net
11 | *

12 | * 13 | * 用户 14 | * 15 | *

16 | * 17 | * 区分 责任人 日期    说明
18 | * 创建 周柏成 2016年5月25日  
19 | *

20 | * ******* 21 | *

22 | * @author zhou-baicheng 23 | * @email i@itboy.net 24 | * @version 1.0,2016年5月25日
25 | * 26 | */ 27 | public class UUser implements Serializable{ 28 | private static final long serialVersionUID = 1L; 29 | //0:禁止登录 30 | public static final Long _0 = new Long(0); 31 | //1:有效 32 | public static final Long _1 = new Long(1); 33 | private Long id; 34 | /**昵称*/ 35 | private String nickname; 36 | /**邮箱 | 登录帐号*/ 37 | private String email; 38 | /**密码*/ 39 | private transient String pswd; 40 | /**创建时间*/ 41 | private Date createTime; 42 | /**最后登录时间*/ 43 | private Date lastLoginTime; 44 | /**1:有效,0:禁止登录*/ 45 | private Long status; 46 | 47 | 48 | 49 | public UUser() {} 50 | public UUser(UUser user) { 51 | this.id = user.getId(); 52 | this.nickname = user.getNickname(); 53 | this.email = user.getEmail(); 54 | this.pswd = user.getPswd(); 55 | this.createTime = user.getCreateTime(); 56 | this.lastLoginTime = user.getLastLoginTime(); 57 | } 58 | 59 | public Long getId() { 60 | return id; 61 | } 62 | 63 | public void setId(Long id) { 64 | this.id = id; 65 | } 66 | 67 | public String getNickname() { 68 | return nickname; 69 | } 70 | 71 | public void setNickname(String nickname) { 72 | this.nickname = nickname; 73 | } 74 | 75 | public String getEmail() { 76 | return email; 77 | } 78 | 79 | public Long getStatus() { 80 | return status; 81 | } 82 | public void setStatus(Long status) { 83 | this.status = status; 84 | } 85 | public void setEmail(String email) { 86 | this.email = email; 87 | } 88 | 89 | public String getPswd() { 90 | return pswd; 91 | } 92 | 93 | public void setPswd(String pswd) { 94 | this.pswd = pswd; 95 | } 96 | 97 | public Date getCreateTime() { 98 | return createTime; 99 | } 100 | 101 | public void setCreateTime(Date createTime) { 102 | this.createTime = createTime; 103 | } 104 | 105 | public Date getLastLoginTime() { 106 | return lastLoginTime; 107 | } 108 | 109 | public void setLastLoginTime(Date lastLoginTime) { 110 | this.lastLoginTime = lastLoginTime; 111 | } 112 | public String toString(){ 113 | return JSONObject.fromObject(this).toString(); 114 | } 115 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/model/UUserRole.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.model; 2 | 3 | import java.io.Serializable; 4 | 5 | import net.sf.json.JSONObject; 6 | /** 7 | * 8 | * 开发公司:itboy.net
9 | * 版权:itboy.net
10 | *

11 | * 12 | * 用户{@link UUser} 和角色 {@link URole} 中间表 13 | * 14 | *

15 | * 16 | * 区分 责任人 日期    说明
17 | * 创建 周柏成 2016年5月25日  
18 | *

19 | * ******* 20 | *

21 | * @author zhou-baicheng 22 | * @email i@itboy.net 23 | * @version 1.0,2016年5月25日
24 | * 25 | */ 26 | public class UUserRole implements Serializable{ 27 | private static final long serialVersionUID = 1L; 28 | /**{@link UUser.id}*/ 29 | private Long uid; 30 | /**{@link URole.id}*/ 31 | private Long rid; 32 | 33 | public UUserRole(Long uid,Long rid) { 34 | this.uid = uid; 35 | this.rid = rid; 36 | } 37 | public UUserRole() { 38 | } 39 | public Long getUid() { 40 | return uid; 41 | } 42 | 43 | public void setUid(Long uid) { 44 | this.uid = uid; 45 | } 46 | 47 | public Long getRid() { 48 | return rid; 49 | } 50 | 51 | public void setRid(Long rid) { 52 | this.rid = rid; 53 | } 54 | public String toString(){ 55 | return JSONObject.fromObject(this).toString(); 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/timer/ToTimer.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.timer; 2 | 3 | import java.util.Date; 4 | 5 | import javax.annotation.Resource; 6 | 7 | import org.springframework.scheduling.annotation.Scheduled; 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.sojson.permission.service.RoleService; 11 | 12 | 13 | /** 14 | * 定时任务恢复数据 15 | * 16 | */ 17 | @Component 18 | public class ToTimer{ 19 | 20 | @Resource 21 | RoleService roleService; 22 | @Scheduled(cron = "0/20 * * * * ? ") 23 | public void run() { 24 | /** 25 | * 调用存储过程,重新创建表,插入初始化数据。 26 | */ 27 | roleService.initData(); 28 | System.out.println(new Date().getTime()); 29 | } 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/CookieUtil.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | /** 4 | * 5 | * 开发公司:SOJSON在线工具

6 | * 版权所有:© www.sojson.com

7 | * 博客地址:http://www.sojson.com/blog/

8 | *

9 | * 10 | * Cookie工具 11 | * 12 | *

13 | * 14 | * 区分 责任人 日期    说明
15 | * 创建 周柏成 2016年6月2日  
16 | * 17 | * @author zhou-baicheng 18 | * @email so@sojson.com 19 | * @version 1.0,2016年6月2日
20 | * 21 | */ 22 | import javax.servlet.http.Cookie; 23 | import javax.servlet.http.HttpServletRequest; 24 | import javax.servlet.http.HttpServletResponse; 25 | 26 | public class CookieUtil { 27 | 28 | /** 29 | * 设置cookie 30 | * 31 | * @param response 32 | * @param name 33 | * cookie名字 34 | * @param value 35 | * cookie值 36 | * @param maxAge 37 | * cookie生命周期 以秒为单位 38 | */ 39 | public static void addCookie(HttpServletResponse response, String name, 40 | String value, int maxAge) { 41 | try { 42 | Cookie cookie = new Cookie(name, value); 43 | if (maxAge > 0) 44 | cookie.setMaxAge(maxAge); 45 | cookie.setPath("/"); 46 | response.addCookie(cookie); 47 | } catch (Exception ex) { 48 | LoggerUtils.error(CookieUtil.class, "创建Cookies发生异常!", ex); 49 | } 50 | } 51 | 52 | /** 53 | * 清空Cookie操作 clearCookie 54 | * 55 | * @param request 56 | * @param response 57 | * @return boolean 58 | * @author JIANG FEI Jun 19, 2014 10:12:17 AM 59 | */ 60 | public static boolean clearCookie(HttpServletRequest request, 61 | HttpServletResponse response, String name) { 62 | boolean bool = false; 63 | Cookie[] cookies = request.getCookies(); 64 | if(null == cookies || cookies.length == 0) return bool; 65 | try { 66 | for (int i = 0; i < cookies.length; i++) { 67 | Cookie cookie = new Cookie(name, null); 68 | cookie.setMaxAge(0); 69 | cookie.setPath("/");// 根据你创建cookie的路径进行填写 70 | response.addCookie(cookie); 71 | bool = true; 72 | } 73 | } catch (Exception ex) { 74 | LoggerUtils.error(CookieUtil.class, "清空Cookies发生异常!", ex); 75 | } 76 | return bool; 77 | } 78 | 79 | /** 80 | * 清空Cookie操作 clearCookie 81 | * 82 | * @param request 83 | * @param response 84 | * @return boolean 85 | * @author JIANG FEI Jun 19, 2014 10:12:17 AM 86 | */ 87 | public static boolean clearCookie(HttpServletRequest request, 88 | HttpServletResponse response, String name, String domain) { 89 | boolean bool = false; 90 | Cookie[] cookies = request.getCookies(); 91 | if(null == cookies || cookies.length == 0) return bool; 92 | try { 93 | for (int i = 0; i < cookies.length; i++) { 94 | Cookie cookie = new Cookie(name, null); 95 | cookie.setMaxAge(0); 96 | cookie.setPath("/");// 根据你创建cookie的路径进行填写 97 | cookie.setDomain(domain); 98 | response.addCookie(cookie); 99 | bool = true; 100 | } 101 | } catch (Exception ex) { 102 | LoggerUtils.error(CookieUtil.class, "清空Cookies发生异常!", ex); 103 | } 104 | return bool; 105 | } 106 | 107 | /** 108 | * 获取指定cookies的值 findCookieByName 109 | * 110 | * @param request 111 | * @param name 112 | * @return String 113 | */ 114 | public static String findCookieByName(HttpServletRequest request, 115 | String name) { 116 | Cookie[] cookies = request.getCookies(); 117 | if(null == cookies || cookies.length == 0) return null; 118 | String string = null; 119 | try { 120 | for (int i = 0; i < cookies.length; i++) { 121 | Cookie cookie = cookies[i]; 122 | String cname = cookie.getName(); 123 | if (!StringUtils.isBlank(cname) && cname.equals(name)) { 124 | string = cookie.getValue(); 125 | } 126 | 127 | } 128 | } catch (Exception ex) { 129 | LoggerUtils.error(CookieUtil.class, "获取Cookies发生异常!", ex); 130 | } 131 | return string; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/LoggerUtils.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | import org.apache.log4j.Logger; 4 | /** 5 | * 6 | * 开发公司:SOJSON在线工具

7 | * 版权所有:© www.sojson.com

8 | * 博客地址:http://www.sojson.com/blog/

9 | *

10 | * 11 | * Log输出封装 12 | * 13 | *

14 | * 15 | * 区分 责任人 日期    说明
16 | * 创建 周柏成 2016年6月2日  
17 | * 18 | * @author zhou-baicheng 19 | * @email so@sojson.com 20 | * @version 1.0,2016年6月2日
21 | * 22 | */ 23 | public class LoggerUtils { 24 | /** 25 | * 是否开启Debug 26 | */ 27 | public static boolean isDebug = Logger.getLogger(LoggerUtils.class).isDebugEnabled(); 28 | 29 | /** 30 | * Debug 输出 31 | * @param clazz 目标.Class 32 | * @param message 输出信息 33 | */ 34 | public static void debug(Class clazz ,String message){ 35 | if(!isDebug)return ; 36 | Logger logger = Logger.getLogger(clazz); 37 | logger.debug(message); 38 | } 39 | /** 40 | * Debug 输出 41 | * @param clazz 目标.Class 42 | * @param fmtString 输出信息key 43 | * @param value 输出信息value 44 | */ 45 | public static void fmtDebug(Class clazz,String fmtString,Object...value){ 46 | if(!isDebug)return ; 47 | if(StringUtils.isBlank(fmtString)){ 48 | return ; 49 | } 50 | if(null != value && value.length != 0){ 51 | fmtString = String.format(fmtString, value); 52 | } 53 | debug(clazz, fmtString); 54 | } 55 | /** 56 | * Error 输出 57 | * @param clazz 目标.Class 58 | * @param message 输出信息 59 | * @param e 异常类 60 | */ 61 | public static void error(Class clazz ,String message,Exception e){ 62 | Logger logger = Logger.getLogger(clazz); 63 | if(null == e){ 64 | logger.error(message); 65 | return ; 66 | } 67 | logger.error(message, e); 68 | } 69 | /** 70 | * Error 输出 71 | * @param clazz 目标.Class 72 | * @param message 输出信息 73 | */ 74 | public static void error(Class clazz ,String message){ 75 | error(clazz, message, null); 76 | } 77 | /** 78 | * 异常填充值输出 79 | * @param clazz 目标.Class 80 | * @param fmtString 输出信息key 81 | * @param e 异常类 82 | * @param value 输出信息value 83 | */ 84 | public static void fmtError(Class clazz,Exception e,String fmtString,Object...value){ 85 | if(StringUtils.isBlank(fmtString)){ 86 | return ; 87 | } 88 | if(null != value && value.length != 0){ 89 | fmtString = String.format(fmtString, value); 90 | } 91 | error(clazz, fmtString, e); 92 | } 93 | /** 94 | * 异常填充值输出 95 | * @param clazz 目标.Class 96 | * @param fmtString 输出信息key 97 | * @param value 输出信息value 98 | */ 99 | public static void fmtError(Class clazz, 100 | String fmtString, Object...value) { 101 | if(StringUtils.isBlank(fmtString)){ 102 | return ; 103 | } 104 | if(null != value && value.length != 0){ 105 | fmtString = String.format(fmtString, value); 106 | } 107 | error(clazz, fmtString); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/MathUtil.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | import java.security.MessageDigest; 4 | import java.util.Random; 5 | 6 | public class MathUtil { 7 | /** 8 | * 获取随机的数值。 9 | * @param length 长度 10 | * @return 11 | */ 12 | public static String getRandom620(Integer length){ 13 | String result = ""; 14 | Random rand = new Random(); 15 | int n = 20; 16 | if(null != length && length > 0){ 17 | n = length; 18 | } 19 | boolean[] bool = new boolean[n]; 20 | int randInt = 0; 21 | for(int i = 0; i < length ; i++) { 22 | do { 23 | randInt = rand.nextInt(n); 24 | 25 | }while(bool[randInt]); 26 | 27 | bool[randInt] = true; 28 | result += randInt; 29 | } 30 | return result; 31 | } 32 | /** 33 | * MD5 加密 34 | * @param str 35 | * @return 36 | * @throws Exception 37 | */ 38 | public static String getMD5(String str) { 39 | MessageDigest messageDigest = null; 40 | try { 41 | messageDigest = MessageDigest.getInstance("MD5"); 42 | messageDigest.reset(); 43 | messageDigest.update(str.getBytes("UTF-8")); 44 | } catch (Exception e) { 45 | LoggerUtils.fmtError(MathUtil.class,e, "MD5转换异常!message:%s", e.getMessage()); 46 | } 47 | 48 | byte[] byteArray = messageDigest.digest(); 49 | StringBuffer md5StrBuff = new StringBuffer(); 50 | for (int i = 0; i < byteArray.length; i++) { 51 | if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) 52 | md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); 53 | else 54 | md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); 55 | } 56 | return md5StrBuff.toString(); 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/SerializeUtil.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.Closeable; 6 | import java.io.IOException; 7 | import java.io.ObjectInputStream; 8 | import java.io.ObjectOutputStream; 9 | 10 | import net.sf.json.JSONObject; 11 | 12 | /** 13 | * 14 | * 开发公司:SOJSON在线工具

15 | * 版权所有:© www.sojson.com

16 | * 博客地址:http://www.sojson.com/blog/

17 | *

18 | * 19 | * Java原生版的 Serialize 20 | * 21 | *

22 | * 23 | * 区分 责任人 日期    说明
24 | * 创建 周柏成 2016年6月2日  
25 | * 26 | * @author zhou-baicheng 27 | * @email so@sojson.com 28 | * @version 1.0,2016年6月2日
29 | * 30 | */ 31 | @SuppressWarnings("unchecked") 32 | public class SerializeUtil { 33 | static final Class CLAZZ = SerializeUtil.class; 34 | 35 | public static byte[] serialize(Object value) { 36 | if (value == null) { 37 | throw new NullPointerException("Can't serialize null"); 38 | } 39 | byte[] rv = null; 40 | ByteArrayOutputStream bos = null; 41 | ObjectOutputStream os = null; 42 | try { 43 | bos = new ByteArrayOutputStream(); 44 | os = new ObjectOutputStream(bos); 45 | os.writeObject(value); 46 | os.close(); 47 | bos.close(); 48 | rv = bos.toByteArray(); 49 | } catch (Exception e) { 50 | LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", JSONObject.fromObject(value)); 51 | } finally { 52 | close(os); 53 | close(bos); 54 | } 55 | return rv; 56 | } 57 | 58 | 59 | public static Object deserialize(byte[] in) { 60 | return deserialize(in, Object.class); 61 | } 62 | 63 | public static T deserialize(byte[] in, Class...requiredType) { 64 | Object rv = null; 65 | ByteArrayInputStream bis = null; 66 | ObjectInputStream is = null; 67 | try { 68 | if (in != null) { 69 | bis = new ByteArrayInputStream(in); 70 | is = new ObjectInputStream(bis); 71 | rv = is.readObject(); 72 | } 73 | } catch (Exception e) { 74 | LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", in); 75 | } finally { 76 | close(is); 77 | close(bis); 78 | } 79 | return (T) rv; 80 | } 81 | 82 | private static void close(Closeable closeable) { 83 | if (closeable != null) 84 | try { 85 | closeable.close(); 86 | } catch (IOException e) { 87 | LoggerUtils.fmtError(CLAZZ, "close stream error"); 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/SpringContextUtil.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ApplicationContextAware; 7 | 8 | /** 9 | * 10 | * 开发公司:itboy.net
11 | * 版权:itboy.net
12 | *

13 | * 14 | * 静态获取Bean 15 | * 16 | *

17 | * 18 | * 区分 责任人 日期    说明
19 | * 创建 周柏成 2016年4月4日  
20 | *

21 | * ******* 22 | *

23 | * @author zhou-baicheng 24 | * @email i@itboy.net 25 | * @version 1.0,2016年4月4日
26 | * 27 | */ 28 | public class SpringContextUtil implements ApplicationContextAware { 29 | private static ApplicationContext applicationContext; 30 | 31 | // 实现 32 | @Override 33 | public void setApplicationContext(ApplicationContext applicationContext) 34 | throws BeansException { 35 | SpringContextUtil.applicationContext = applicationContext; 36 | } 37 | 38 | public static ApplicationContext getApplicationContext() { 39 | return applicationContext; 40 | } 41 | 42 | public static Object getBean(String name) throws BeansException { 43 | try { 44 | return applicationContext.getBean(name); 45 | } catch (Exception e) { 46 | throw new RuntimeException("获取的Bean不存在!"); 47 | } 48 | } 49 | 50 | public static T getBean(String name, Class requiredType) 51 | throws BeansException { 52 | return applicationContext.getBean(name, requiredType); 53 | } 54 | 55 | public static boolean containsBean(String name) { 56 | return applicationContext.containsBean(name); 57 | } 58 | 59 | public static boolean isSingleton(String name) 60 | throws NoSuchBeanDefinitionException { 61 | return applicationContext.isSingleton(name); 62 | } 63 | 64 | public static Class getType(String name) 65 | throws NoSuchBeanDefinitionException { 66 | return applicationContext.getType(name); 67 | } 68 | 69 | public static String[] getAliases(String name) 70 | throws NoSuchBeanDefinitionException { 71 | return applicationContext.getAliases(name); 72 | } 73 | 74 | 75 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/UtilPath.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils; 2 | 3 | import java.io.File; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | import org.apache.commons.lang.StringUtils; 10 | 11 | 12 | /** 13 | * 14 | * 静态化路径工具类 15 | * 16 | *

17 | * 18 | *

19 | * 20 | * 区分 责任人 日期    说明
21 | * 创建 周柏成 2013-6-11 
22 | *

23 | * 24 | * @author 25 | * 26 | * @version 1.0, 2013-6-11 27 | * 28 | */ 29 | public class UtilPath { 30 | 31 | /** 32 | * 获取到classes目录 33 | * @return path 34 | */ 35 | public static String getClassPath(){ 36 | String systemName = System.getProperty("os.name"); 37 | 38 | //判断当前环境,如果是Windows 要截取路径的第一个 '/' 39 | if(!StringUtils.isBlank(systemName) && systemName.indexOf("Windows") !=-1){ 40 | return UtilPath.class.getResource("/").getFile().toString().substring(1); 41 | }else{ 42 | return UtilPath.class.getResource("/").getFile().toString(); 43 | } 44 | } 45 | /** 46 | * 获取当前对象的路径 47 | * @param object 48 | * @return path 49 | */ 50 | public static String getObjectPath(Object object){ 51 | return object.getClass().getResource(".").getFile().toString(); 52 | } 53 | /** 54 | * 获取到项目的路径 55 | * @return path 56 | */ 57 | public static String getProjectPath(){ 58 | return System.getProperty("user.dir"); 59 | } 60 | /** 61 | * 获取 root目录 62 | * @return path 63 | */ 64 | public static String getRootPath(){ 65 | return getWEB_INF().replace("WEB-INF/", ""); 66 | } 67 | /** 68 | * 获取输出HTML目录 69 | * @return 70 | */ 71 | public static String getHTMLPath(){ 72 | return getFreePath() + "html/html/"; 73 | } 74 | /** 75 | * 获取输出FTL目录 76 | * @return 77 | */ 78 | public static String getFTLPath(){ 79 | return getFreePath() + "html/ftl/"; 80 | } 81 | /** 82 | * 获取 web-inf目录 83 | * @return path 84 | */ 85 | public static String getWEB_INF(){ 86 | return getClassPath().replace("classes/", ""); 87 | } 88 | /** 89 | * 获取模版文件夹路径 90 | * @return path 91 | */ 92 | public static String getFreePath(){ 93 | return getWEB_INF() + "ftl/"; 94 | } 95 | /** 96 | * 获取一个目录下所有的文件 97 | * @param path 98 | * @return 99 | */ 100 | public static File[] getFiles(String path){ 101 | File file = new File(path); 102 | File[] files = file.listFiles(); 103 | return files; 104 | } 105 | /** 106 | * 获取当前时间 + 中国时区 107 | * @return 108 | */ 109 | public static String getDate(){ 110 | SimpleDateFormat sformart=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); 111 | String result = sformart.format(new Date()); 112 | result = result.replace("_", "T"); 113 | result += "+08:00"; 114 | return result; 115 | } 116 | /** 117 | * 不带结尾的XmlSitemap头部 118 | * @return 119 | */ 120 | public static String getXmlSitemap(){ 121 | StringBuffer sb = new StringBuffer() 122 | .append("" + nextLine()) 123 | .append(""+ nextLine()) 124 | .append(""+ nextLine()); 125 | return sb.toString(); 126 | } 127 | /** 128 | * 文本换行 129 | * @return 130 | */ 131 | public static String nextLine(){ 132 | String nextLine = System.getProperty("line.separator"); 133 | return nextLine; 134 | } 135 | /** 136 | * 获取domain 137 | * @param request 138 | * @return 139 | */ 140 | public static String getDomain(HttpServletRequest request) { 141 | return ((String) request.getSession().getAttribute("nowPath")).replaceAll("(www.)|(.com)|(.net)|(http://)", "").trim(); 142 | } 143 | /** 144 | * 获取images 路径 145 | * @return 146 | */ 147 | public static String getImages(){ 148 | return getRootPath() + "images/" ; 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/vcode/Captcha.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils.vcode; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.io.OutputStream; 6 | 7 | /** 8 | *

9 | * 验证码抽象类,暂时不支持中文 10 | *

11 | * 12 | * @author: wuhongjun 13 | * @version:1.0 14 | */ 15 | public abstract class Captcha extends Randoms { 16 | protected Font font = new Font("Verdana", Font.ITALIC | Font.BOLD, 28); // 字体 17 | protected int len = 5; // 验证码随机字符长度 18 | protected int width = 150; // 验证码显示跨度 19 | protected int height = 40; // 验证码显示高度 20 | private String chars = null; // 随机字符串 21 | 22 | /** 23 | * 生成随机字符数组 24 | * 25 | * @return 字符数组 26 | */ 27 | protected char[] alphas() { 28 | char[] cs = new char[len]; 29 | for (int i = 0; i < len; i++) { 30 | cs[i] = alpha(); 31 | } 32 | chars = new String(cs); 33 | return cs; 34 | } 35 | 36 | public Font getFont() { 37 | return font; 38 | } 39 | 40 | public void setFont(Font font) { 41 | this.font = font; 42 | } 43 | 44 | public int getLen() { 45 | return len; 46 | } 47 | 48 | public void setLen(int len) { 49 | this.len = len; 50 | } 51 | 52 | public int getWidth() { 53 | return width; 54 | } 55 | 56 | public void setWidth(int width) { 57 | this.width = width; 58 | } 59 | 60 | public int getHeight() { 61 | return height; 62 | } 63 | 64 | public void setHeight(int height) { 65 | this.height = height; 66 | } 67 | 68 | /** 69 | * 给定范围获得随机颜色 70 | * 71 | * @return Color 随机颜色 72 | */ 73 | protected Color color(int fc, int bc) { 74 | if (fc > 255) 75 | fc = 255; 76 | if (bc > 255) 77 | bc = 255; 78 | int r = fc + num(bc - fc); 79 | int g = fc + num(bc - fc); 80 | int b = fc + num(bc - fc); 81 | return new Color(r, g, b); 82 | } 83 | 84 | /** 85 | * 验证码输出,抽象方法,由子类实现 86 | * 87 | * @param os 88 | * 输出流 89 | */ 90 | public abstract void out(OutputStream os); 91 | 92 | /** 93 | * 获取随机字符串 94 | * 95 | * @return string 96 | */ 97 | public String text() { 98 | return chars; 99 | } 100 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/vcode/GifCaptcha.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils.vcode; 2 | import java.awt.AlphaComposite; 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.Graphics2D; 6 | import java.awt.image.BufferedImage; 7 | import java.io.IOException; 8 | import java.io.OutputStream; 9 | /** 10 | *

Gif验证码类

11 | * 12 | * @author: wuhongjun 13 | * @version:1.0 14 | */ 15 | public class GifCaptcha extends Captcha 16 | { 17 | public GifCaptcha() 18 | { 19 | } 20 | 21 | public GifCaptcha(int width,int height){ 22 | this.width = width; 23 | this.height = height; 24 | } 25 | 26 | public GifCaptcha(int width,int height,int len){ 27 | this(width,height); 28 | this.len = len; 29 | } 30 | 31 | public GifCaptcha(int width,int height,int len,Font font) 32 | { 33 | this(width,height,len); 34 | this.font = font; 35 | } 36 | 37 | @Override 38 | public void out(OutputStream os) 39 | { 40 | try 41 | { 42 | GifEncoder gifEncoder = new GifEncoder(); // gif编码类,这个利用了洋人写的编码类,所有类都在附件中 43 | //生成字符 44 | gifEncoder.start(os); 45 | gifEncoder.setQuality(180); 46 | gifEncoder.setDelay(100); 47 | gifEncoder.setRepeat(0); 48 | BufferedImage frame; 49 | char[] rands =alphas(); 50 | Color fontcolor[]=new Color[len]; 51 | for(int i=0;i>1) ; 92 | int w = width/len; 93 | g2d.setFont(font); 94 | for(int i=0;i len ? (num *r - s) : num * r; 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/vcode/Randoms.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils.vcode; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | *

随机工具类

7 | * 8 | * @author: wuhongjun 9 | * @version:1.0 10 | */ 11 | public class Randoms 12 | { 13 | private static final Random RANDOM = new Random(); 14 | //定义验证码字符.去除了O和I等容易混淆的字母 15 | public static final char ALPHA[]={'A','B','C','D','E','F','G','H','G','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z' 16 | ,'a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','8','9'}; 17 | 18 | /** 19 | * 产生两个数之间的随机数 20 | * @param min 小数 21 | * @param max 比min大的数 22 | * @return int 随机数字 23 | */ 24 | public static int num(int min, int max) 25 | { 26 | return min + RANDOM.nextInt(max - min); 27 | } 28 | 29 | /** 30 | * 产生0--num的随机数,不包括num 31 | * @param num 数字 32 | * @return int 随机数字 33 | */ 34 | public static int num(int num) 35 | { 36 | return RANDOM.nextInt(num); 37 | } 38 | 39 | public static char alpha() 40 | { 41 | return ALPHA[num(0, ALPHA.length)]; 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/sojson/common/utils/vcode/SpecCaptcha.java: -------------------------------------------------------------------------------- 1 | package com.sojson.common.utils.vcode; 2 | import java.awt.AlphaComposite; 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.Graphics2D; 6 | import java.awt.image.BufferedImage; 7 | import java.io.IOException; 8 | import java.io.OutputStream; 9 | 10 | import javax.imageio.ImageIO; 11 | /** 12 | *

png格式验证码

13 | * 14 | * @author: wuhongjun 15 | * @version:1.0 16 | */ 17 | public class SpecCaptcha extends Captcha 18 | { 19 | public SpecCaptcha() 20 | { 21 | } 22 | public SpecCaptcha(int width, int height) 23 | { 24 | this.width = width; 25 | this.height = height; 26 | } 27 | public SpecCaptcha(int width, int height, int len){ 28 | this(width,height); 29 | this.len = len; 30 | } 31 | public SpecCaptcha(int width, int height, int len, Font font){ 32 | this(width,height,len); 33 | this.font = font; 34 | } 35 | /** 36 | * 生成验证码 37 | * @throws java.io.IOException IO异常 38 | */ 39 | @Override 40 | public void out(OutputStream out){ 41 | graphicsImage(alphas(), out); 42 | } 43 | 44 | /** 45 | * 画随机码图 46 | * @param strs 文本 47 | * @param out 输出流 48 | */ 49 | private boolean graphicsImage(char[] strs, OutputStream out){ 50 | boolean ok = false; 51 | try 52 | { 53 | BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 54 | Graphics2D g = (Graphics2D)bi.getGraphics(); 55 | AlphaComposite ac3; 56 | Color color ; 57 | int len = strs.length; 58 | g.setColor(Color.WHITE); 59 | g.fillRect(0,0,width,height); 60 | // 随机画干扰的蛋蛋 61 | for(int i=0;i<15;i++){ 62 | color = color(150, 250); 63 | g.setColor(color); 64 | g.drawOval(num(width), num(height), 5+num(10), 5+num(10));// 画蛋蛋,有蛋的生活才精彩 65 | color = null; 66 | } 67 | g.setFont(font); 68 | int h = height - ((height - font.getSize()) >>1), 69 | w = width/len, 70 | size = w-font.getSize()+1; 71 | /* 画字符串 */ 72 | for(int i=0;i model, HttpServletRequest request){ 17 | 18 | try { 19 | super.exposeHelpers(model, request); 20 | } catch (Exception e) { 21 | LoggerUtils.fmtError(FreeMarkerViewExtend.class,e, "FreeMarkerViewExtend 加载父类出现异常。请检查。"); 22 | } 23 | model.put(Constant.CONTEXT_PATH, request.getContextPath()); 24 | model.putAll(Ferrmarker.initMap); 25 | UUser token = TokenManager.getToken(); 26 | //String ip = IPUtils.getIP(request); 27 | model.put("token", token);//登录的token 28 | model.put("_time", new Date().getTime()); 29 | model.put("NOW_YEAY", Constant.NOW_YEAY);//今年 30 | 31 | model.put("_v", Constant.VERSION);//版本号,重启的时间 32 | model.put("cdn", Constant.DOMAIN_CDN);//CDN域名 33 | model.put("basePath", request.getContextPath());//base目录。 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/freemarker/utils/FreemarkerTagUtil.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.freemarker.utils; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import freemarker.core.Environment; 8 | import freemarker.template.TemplateException; 9 | import freemarker.template.TemplateModel; 10 | import freemarker.template.TemplateModelException; 11 | 12 | 13 | 14 | 15 | /** 16 | * 17 | * 开发公司:SOJSON在线工具

18 | * 版权所有:© www.sojson.com

19 | * 博客地址:http://www.sojson.com/blog/

20 | *

21 | * 22 | * Freemarker Tag Utils 23 | * 24 | *

25 | * 26 | * 区分 责任人 日期    说明
27 | * 创建 周柏成 2016年6月2日  
28 | * 29 | * @author zhou-baicheng 30 | * @email so@sojson.com 31 | * @version 1.0,2016年6月2日
32 | * 33 | */ 34 | public class FreemarkerTagUtil { 35 | 36 | public static final String OUT_TAG_NAME = "outTagName" ; 37 | 38 | 39 | /** 40 | * 统一转换模型 41 | * @param env 42 | * @param maps 43 | * @return 44 | * @throws TemplateException 45 | */ 46 | public static Map convertToTemplateModel( 47 | Environment env, Map maps) 48 | throws TemplateException { 49 | Map origMap = new HashMap(); 50 | if (maps.size() <= 0) { 51 | return origMap; 52 | } 53 | Set> entrySet = maps.entrySet(); 54 | String key; 55 | TemplateModel value; 56 | for (Map.Entry entry : entrySet) { 57 | key = entry.getKey(); 58 | value = env.getVariable(key); 59 | if (null != value) { 60 | origMap.put(key, value); 61 | } 62 | env.setVariable(key, entry.getValue()); 63 | } 64 | return setTemplateModel(env, maps, origMap); 65 | } 66 | /** 67 | * 复制到新的Object 68 | * @param env 69 | * @param maps 70 | * @param origMap 71 | * @return 72 | * @throws TemplateModelException 73 | */ 74 | public static Map setTemplateModel(Environment env, Map maps,Map origMap) throws TemplateModelException{ 75 | Set> entrySet = maps.entrySet(); 76 | String key; 77 | TemplateModel value; 78 | for (Map.Entry entry : entrySet) { 79 | key = entry.getKey(); 80 | value = env.getVariable(key); 81 | if (null != value ) { 82 | origMap.put(key, value); 83 | } 84 | env.setVariable(key, entry.getValue()); 85 | } 86 | return origMap; 87 | 88 | } 89 | /** 90 | * 清除变量值 91 | * 92 | * @param env 93 | * @param params 94 | * @param origMap 95 | * @throws TemplateException 96 | */ 97 | public static void clearTempleModel(Environment env, 98 | Map params, 99 | Map origMap) throws TemplateException { 100 | if (params.size() <= 0) { 101 | return; 102 | } 103 | for (String key : params.keySet()) { 104 | env.setVariable(key, origMap.get(key)); 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/Dialect.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | public interface Dialect { 4 | 5 | public static final String RS_COLUMN = "totalCount"; 6 | 7 | public boolean supportsLimit(); 8 | 9 | /** 10 | * 以传入SQL为基础组装分页查询的SQL语句,传递给myBatis调用 11 | * @param sql 原始SQL 12 | * @param offset 分页查询的记录的偏移量 13 | * @param limit 每页限定记录数 14 | * @return 拼装好的SQL 15 | */ 16 | public String getLimitSqlString(String sql, int offset, int limit); 17 | 18 | /** 19 | * 以传入SQL为基础组装总记录数查询的SQL语句 20 | * @param sql 原始SQL 21 | * @return 拼装好的SQL 22 | */ 23 | public String getCountSqlString(String sql); 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/MysqlDialect.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | public class MysqlDialect implements Dialect { 4 | protected static final String SQL_END_DELIMITER = ";"; 5 | 6 | public String getLimitSqlString(String sql, int offset, int limit) { 7 | sql = sql.trim(); 8 | boolean isForUpdate = false; 9 | if ( sql.toLowerCase().endsWith(" for update") ) { 10 | sql = sql.substring( 0, sql.length()- 11 ); 11 | isForUpdate = true; 12 | } 13 | 14 | if(offset < 0){ 15 | offset = 0; 16 | } 17 | 18 | StringBuffer pagingSelect = new StringBuffer(); 19 | 20 | pagingSelect.append(sql +" limit "+offset+"," +limit); 21 | 22 | 23 | if ( isForUpdate ) { 24 | pagingSelect.append( " for update" ); 25 | } 26 | 27 | return pagingSelect.toString(); 28 | } 29 | 30 | public String getCountSqlString(String sql) { 31 | sql = trim(sql); 32 | StringBuffer sb = new StringBuffer(sql.length() + 10); 33 | sb.append("SELECT COUNT(1) AS " + RS_COLUMN + " FROM ( "); 34 | sb.append(sql); 35 | sb.append(")a"); 36 | return sb.toString(); 37 | } 38 | 39 | public boolean supportsLimit() { 40 | return true; 41 | } 42 | 43 | private static String trim(String sql) { 44 | sql = sql.trim(); 45 | if (sql.endsWith(SQL_END_DELIMITER)) { 46 | sql = sql.substring(0, sql.length() - 1 47 | - SQL_END_DELIMITER.length()); 48 | } 49 | return sql; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/OracleDialect.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | 4 | public class OracleDialect implements Dialect { 5 | protected static final String SQL_END_DELIMITER = ";"; 6 | 7 | public String getLimitSqlString(String sql, int offset, int limit) { 8 | sql = sql.trim(); 9 | boolean isForUpdate = false; 10 | if ( sql.toLowerCase().endsWith(" for update") ) { 11 | sql = sql.substring( 0, sql.length()- 11 ); 12 | isForUpdate = true; 13 | } 14 | 15 | if(offset < 0){ 16 | offset = 0; 17 | } 18 | 19 | StringBuffer pagingSelect = new StringBuffer(); 20 | pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); 21 | 22 | 23 | pagingSelect.append(" ) row_ ) where rownum_ <= "+(offset + limit)+" and rownum_ > "+(offset)+""); 24 | 25 | if ( isForUpdate ) { 26 | pagingSelect.append( " for update" ); 27 | } 28 | 29 | return pagingSelect.toString(); 30 | } 31 | 32 | public String getCountSqlString(String sql) { 33 | sql = trim(sql); 34 | StringBuffer sb = new StringBuffer(sql.length() + 10); 35 | sb.append("SELECT COUNT(1) AS " + RS_COLUMN + " FROM ( "); 36 | sb.append(sql); 37 | sb.append(")a"); 38 | return sb.toString(); 39 | } 40 | 41 | public boolean supportsLimit() { 42 | return true; 43 | } 44 | 45 | private static String trim(String sql) { 46 | sql = sql.trim(); 47 | if (sql.endsWith(SQL_END_DELIMITER)) { 48 | sql = sql.substring(0, sql.length() - 1 49 | - SQL_END_DELIMITER.length()); 50 | } 51 | return sql; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/Paginable.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | /** 4 | * 5 | * 开发公司:SOJSON在线工具

6 | * 版权所有:© www.sojson.com

7 | * 博客地址:http://www.sojson.com/blog/

8 | *

9 | * 10 | * 分页实体 11 | * 12 | *

13 | * 14 | * 区分 责任人 日期    说明
15 | * 创建 周柏成 2016年6月2日  
16 | * 17 | * @author zhou-baicheng 18 | * @email so@sojson.com 19 | * @version 1.0,2016年6月2日
20 | * 21 | */ 22 | public interface Paginable { 23 | 24 | 25 | /** 26 | * 总记录数 27 | * 28 | * @return 29 | */ 30 | public int getTotalCount(); 31 | 32 | /** 33 | * 总页数 34 | * 35 | * @return 36 | */ 37 | public int getTotalPage(); 38 | 39 | /** 40 | * 每页记录数 41 | * 42 | * @return 43 | */ 44 | public int getPageSize(); 45 | 46 | /** 47 | * 当前页号 48 | * 49 | * @return 50 | */ 51 | public int getPageNo(); 52 | 53 | /** 54 | * 是否第一页 55 | * 56 | * @return 57 | */ 58 | public boolean isFirstPage(); 59 | 60 | /** 61 | * 是否最后一页 62 | * 63 | * @return 64 | */ 65 | public boolean isLastPage(); 66 | 67 | /** 68 | * 返回下页的页号 69 | */ 70 | public int getNextPage(); 71 | 72 | /** 73 | * 返回上页的页号 74 | */ 75 | public int getPrePage(); 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/Pagination.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 7 | * 开发公司:SOJSON在线工具

8 | * 版权所有:© www.sojson.com

9 | * 博客地址:http://www.sojson.com/blog/

10 | *

11 | * 12 | * 分页的对象,以及分页页码输出 13 | * 14 | *

15 | * 16 | * 区分 责任人 日期    说明
17 | * 创建 周柏成 2016年6月2日  
18 | * 19 | * @author zhou-baicheng 20 | * @email so@sojson.com 21 | * @version 1.0,2016年6月2日
22 | * 23 | */ 24 | @SuppressWarnings("serial") 25 | public class Pagination extends SimplePage implements java.io.Serializable, 26 | Paginable { 27 | 28 | public Pagination() { 29 | } 30 | 31 | public Pagination(int pageNo, int pageSize, int totalCount) { 32 | super(pageNo, pageSize, totalCount); 33 | } 34 | 35 | @SuppressWarnings("unchecked") 36 | public Pagination(int pageNo, int pageSize, int totalCount, List list) { 37 | super(pageNo, pageSize, totalCount); 38 | this.list = list; 39 | } 40 | 41 | public int getFirstResult() { 42 | return (pageNo - 1) * pageSize; 43 | } 44 | 45 | /** 46 | * 当前页的数据 47 | */ 48 | private List list; 49 | 50 | public List getList() { 51 | return list; 52 | } 53 | 54 | public void setList(List list) { 55 | this.list = list; 56 | } 57 | 58 | 59 | /**SOJSON SEO 翻页版本*/ 60 | public String getWebPage(String page){ 61 | StringBuffer pageHtml = new StringBuffer("

    "); 62 | if(this.getPageNo()>1){ 63 | if(this.getPageNo()>5){ 64 | pageHtml.append("
  • 首页
  • "); 65 | } 66 | pageHtml.append("
  • 上一页
  • "); 67 | } 68 | for (int i = (this.getPageNo()-2<=0?1:this.getPageNo()-2),no = 1; i <= this.getTotalPage()&& no <6 ; i++,no++) { 69 | if (this.getPageNo() == i) { 70 | pageHtml.append("
  • "+i+"
  • "); 71 | }else{ 72 | pageHtml.append("
  • "+i+"
  • "); 73 | } 74 | } 75 | if(this.getPageNo() < this.getTotalPage()){ 76 | pageHtml.append("
  • 下一页
  • "); 77 | } 78 | pageHtml.append("
"); 79 | return pageHtml.toString(); 80 | } 81 | 82 | 83 | 84 | /**Ajxa翻页*/ 85 | public String getSiAjaxPageHtml(){ 86 | StringBuffer pageHtml = new StringBuffer("
    "); 87 | if(this.getPageNo()>1){ 88 | if(this.getPageNo()>5){ 89 | pageHtml.append("
  • 首页
  • "); 90 | } 91 | pageHtml.append("
  • 上一页
  • "); 92 | } 93 | for (int i = (this.getPageNo()-2<=0?1:this.getPageNo()-2),no = 1; i <= this.getTotalPage()&& no <6 ; i++,no++) { 94 | if (this.getPageNo() == i) { 95 | pageHtml.append("
  • "+i+"
  • "); 96 | }else{ 97 | pageHtml.append("
  • "+i+"
  • "); 98 | } 99 | } 100 | if(this.getPageNo() < this.getTotalPage()){ 101 | pageHtml.append("
  • 下一页
  • "); 102 | } 103 | pageHtml.append("
"); 104 | return pageHtml.toString(); 105 | } 106 | 107 | /**普通翻页*/ 108 | public String getPageHtml(){ 109 | StringBuffer pageHtml = new StringBuffer("
    "); 110 | if(this.getPageNo()>1){ 111 | if(this.getPageNo()>5){ 112 | pageHtml.append("
  • 首页
  • "); 113 | } 114 | pageHtml.append("
  • 上一页
  • "); 115 | } 116 | for (int i = (this.getPageNo()-2<=0?1:this.getPageNo()-2),no = 1; i <= this.getTotalPage()&& no <6 ; i++,no++) { 117 | if (this.getPageNo() == i) { 118 | pageHtml.append("
  • "+i+"
  • "); 119 | }else{ 120 | pageHtml.append("
  • "+i+"
  • "); 121 | } 122 | } 123 | if(this.getPageNo() < this.getTotalPage()){ 124 | pageHtml.append("
  • 下一页
  • "); 125 | } 126 | pageHtml.append("
"); 127 | pageHtml.append(""); 132 | 133 | return pageHtml.toString(); 134 | } 135 | 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/mybatis/page/SimplePage.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.mybatis.page; 2 | 3 | public class SimplePage implements Paginable { 4 | private static final long serialVersionUID = 1L; 5 | public static final int DEF_COUNT = 20; 6 | 7 | public SimplePage() { 8 | } 9 | 10 | public SimplePage(int pageNo, int pageSize, int totalCount) { 11 | if (totalCount <= 0) { 12 | this.totalCount = 0; 13 | } else { 14 | this.totalCount = totalCount; 15 | } 16 | if (pageSize <= 0) { 17 | this.pageSize = DEF_COUNT; 18 | } else { 19 | this.pageSize = pageSize; 20 | } 21 | if (pageNo <= 0) { 22 | this.pageNo = 1; 23 | } else { 24 | this.pageNo = pageNo; 25 | } 26 | if ((this.pageNo - 1) * this.pageSize >= totalCount) { 27 | this.pageNo = totalCount / pageSize; 28 | if(this.pageNo==0){ 29 | this.pageNo = 1 ; 30 | } 31 | } 32 | } 33 | 34 | /** 35 | * 调整分页参数,使合理化 36 | */ 37 | public void adjustPage() { 38 | if (totalCount <= 0) { 39 | totalCount = 0; 40 | } 41 | if (pageSize <= 0) { 42 | pageSize = DEF_COUNT; 43 | } 44 | if (pageNo <= 0) { 45 | pageNo = 1; 46 | } 47 | if ((pageNo - 1) * pageSize >= totalCount) { 48 | pageNo = totalCount / pageSize; 49 | } 50 | } 51 | 52 | public int getPageNo() { 53 | return pageNo; 54 | } 55 | 56 | public int getPageSize() { 57 | return pageSize; 58 | } 59 | 60 | public int getTotalCount() { 61 | return totalCount; 62 | } 63 | 64 | public int getTotalPage() { 65 | int totalPage = totalCount / pageSize; 66 | if (totalCount % pageSize != 0 || totalPage == 0) { 67 | totalPage++; 68 | } 69 | return totalPage; 70 | } 71 | 72 | public boolean isFirstPage() { 73 | return pageNo <= 1; 74 | } 75 | 76 | public boolean isLastPage() { 77 | return pageNo >= getTotalPage(); 78 | } 79 | 80 | public int getNextPage() { 81 | if (isLastPage()) { 82 | return pageNo; 83 | } else { 84 | return pageNo + 1; 85 | } 86 | } 87 | 88 | public int getPrePage() { 89 | if (isFirstPage()) { 90 | return pageNo; 91 | } else { 92 | return pageNo - 1; 93 | } 94 | } 95 | 96 | protected int totalCount = 0; 97 | protected int pageSize = 20; 98 | protected int pageNo = 1; 99 | 100 | public void setTotalCount(int totalCount) { 101 | this.totalCount = totalCount; 102 | } 103 | 104 | public void setPageSize(int pageSize) { 105 | this.pageSize = pageSize; 106 | } 107 | 108 | public void setPageNo(int pageNo) { 109 | this.pageNo = pageNo; 110 | } 111 | 112 | 113 | protected int filterNo; 114 | 115 | public int getFilterNo() { 116 | return filterNo; 117 | } 118 | 119 | public void setFilterNo(int filterNo) { 120 | this.filterNo = filterNo; 121 | } 122 | 123 | 124 | 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/CustomShiroSessionDAO.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro; 2 | 3 | import java.io.Serializable; 4 | import java.util.Collection; 5 | 6 | import org.apache.shiro.session.Session; 7 | import org.apache.shiro.session.UnknownSessionException; 8 | import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; 9 | 10 | import com.sojson.common.utils.LoggerUtils; 11 | import com.sojson.core.shiro.session.ShiroSessionRepository; 12 | /** 13 | * 14 | * 开发公司:SOJSON在线工具

15 | * 版权所有:© www.sojson.com

16 | * 博客地址:http://www.sojson.com/blog/

17 | *

18 | * 19 | * Session 操作 20 | * 21 | *

22 | * 23 | * 区分 责任人 日期    说明
24 | * 创建 周柏成 2016年6月2日  
25 | * 26 | * @author zhou-baicheng 27 | * @email so@sojson.com 28 | * @version 1.0,2016年6月2日
29 | * 30 | */ 31 | public class CustomShiroSessionDAO extends AbstractSessionDAO{ 32 | 33 | private ShiroSessionRepository shiroSessionRepository; 34 | 35 | public ShiroSessionRepository getShiroSessionRepository() { 36 | return shiroSessionRepository; 37 | } 38 | 39 | public void setShiroSessionRepository( 40 | ShiroSessionRepository shiroSessionRepository) { 41 | this.shiroSessionRepository = shiroSessionRepository; 42 | } 43 | 44 | @Override 45 | public void update(Session session) throws UnknownSessionException { 46 | getShiroSessionRepository().saveSession(session); 47 | } 48 | 49 | @Override 50 | public void delete(Session session) { 51 | if (session == null) { 52 | LoggerUtils.error(getClass(), "Session 不能为null"); 53 | return; 54 | } 55 | Serializable id = session.getId(); 56 | if (id != null) 57 | getShiroSessionRepository().deleteSession(id); 58 | } 59 | 60 | @Override 61 | public Collection getActiveSessions() { 62 | return getShiroSessionRepository().getAllSessions(); 63 | } 64 | 65 | @Override 66 | protected Serializable doCreate(Session session) { 67 | Serializable sessionId = this.generateSessionId(session); 68 | this.assignSessionId(session, sessionId); 69 | getShiroSessionRepository().saveSession(session); 70 | return sessionId; 71 | } 72 | 73 | @Override 74 | protected Session doReadSession(Serializable sessionId) { 75 | return getShiroSessionRepository().getSession(sessionId); 76 | } } 77 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/cache/JedisShiroCache.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.cache; 2 | 3 | import java.util.Collection; 4 | import java.util.Set; 5 | 6 | import org.apache.shiro.cache.Cache; 7 | import org.apache.shiro.cache.CacheException; 8 | 9 | import com.sojson.common.utils.LoggerUtils; 10 | import com.sojson.common.utils.SerializeUtil; 11 | 12 | /** 13 | * 14 | * 开发公司:sojson.com
15 | * 版权:sojson.com
16 | *

17 | * 18 | * 缓存获取Manager 19 | * 20 | *

21 | * 22 | * 区分 责任人 日期    说明
23 | * 创建 周柏成 2016年4月29日  
24 | *

25 | * ******* 26 | *

27 | * @author zhou-baicheng 28 | * @email json@sojson.com 29 | * @version 1.0,2016年4月29日
30 | * 31 | */ 32 | @SuppressWarnings("unchecked") 33 | public class JedisShiroCache implements Cache { 34 | 35 | /** 36 | * 为了不和其他的缓存混淆,采用追加前缀方式以作区分 37 | */ 38 | private static final String REDIS_SHIRO_CACHE = "shiro-demo-cache:"; 39 | /** 40 | * Redis 分片(分区),也可以在配置文件中配置 41 | */ 42 | private static final int DB_INDEX = 1; 43 | 44 | private JedisManager jedisManager; 45 | 46 | private String name; 47 | 48 | 49 | static final Class SELF = JedisShiroCache.class; 50 | public JedisShiroCache(String name, JedisManager jedisManager) { 51 | this.name = name; 52 | this.jedisManager = jedisManager; 53 | } 54 | 55 | /** 56 | * 自定义relm中的授权/认证的类名加上授权/认证英文名字 57 | */ 58 | public String getName() { 59 | if (name == null) 60 | return ""; 61 | return name; 62 | } 63 | 64 | public void setName(String name) { 65 | this.name = name; 66 | } 67 | 68 | @Override 69 | public V get(K key) throws CacheException { 70 | byte[] byteKey = SerializeUtil.serialize(buildCacheKey(key)); 71 | byte[] byteValue = new byte[0]; 72 | try { 73 | byteValue = jedisManager.getValueByKey(DB_INDEX, byteKey); 74 | } catch (Exception e) { 75 | LoggerUtils.error(SELF, "get value by cache throw exception",e); 76 | } 77 | return (V) SerializeUtil.deserialize(byteValue); 78 | } 79 | 80 | @Override 81 | public V put(K key, V value) throws CacheException { 82 | V previos = get(key); 83 | try { 84 | jedisManager.saveValueByKey(DB_INDEX, SerializeUtil.serialize(buildCacheKey(key)), 85 | SerializeUtil.serialize(value), -1); 86 | } catch (Exception e) { 87 | LoggerUtils.error(SELF, "put cache throw exception",e); 88 | } 89 | return previos; 90 | } 91 | 92 | @Override 93 | public V remove(K key) throws CacheException { 94 | V previos = get(key); 95 | try { 96 | jedisManager.deleteByKey(DB_INDEX, SerializeUtil.serialize(buildCacheKey(key))); 97 | } catch (Exception e) { 98 | LoggerUtils.error(SELF, "remove cache throw exception",e); 99 | } 100 | return previos; 101 | } 102 | 103 | @Override 104 | public void clear() throws CacheException { 105 | //TODO-- 106 | } 107 | 108 | @Override 109 | public int size() { 110 | if (keys() == null) 111 | return 0; 112 | return keys().size(); 113 | } 114 | 115 | @Override 116 | public Set keys() { 117 | //TODO 118 | return null; 119 | } 120 | 121 | @Override 122 | public Collection values() { 123 | //TODO 124 | return null; 125 | } 126 | 127 | private String buildCacheKey(Object key) { 128 | return REDIS_SHIRO_CACHE + getName() + ":" + key; 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/cache/JedisShiroSessionRepository.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.cache; 2 | 3 | import java.io.Serializable; 4 | import java.util.Collection; 5 | 6 | import org.apache.shiro.session.Session; 7 | 8 | import com.sojson.common.utils.LoggerUtils; 9 | import com.sojson.common.utils.SerializeUtil; 10 | import com.sojson.core.shiro.session.CustomSessionManager; 11 | import com.sojson.core.shiro.session.SessionStatus; 12 | import com.sojson.core.shiro.session.ShiroSessionRepository; 13 | /** 14 | * Session 管理 15 | * @author sojson.com 16 | * 17 | */ 18 | @SuppressWarnings("unchecked") 19 | public class JedisShiroSessionRepository implements ShiroSessionRepository { 20 | public static final String REDIS_SHIRO_SESSION = "sojson-shiro-demo-session:"; 21 | //这里有个小BUG,因为Redis使用序列化后,Key反序列化回来发现前面有一段乱码,解决的办法是存储缓存不序列化 22 | public static final String REDIS_SHIRO_ALL = "*sojson-shiro-demo-session:*"; 23 | private static final int SESSION_VAL_TIME_SPAN = 18000; 24 | private static final int DB_INDEX = 1; 25 | 26 | private JedisManager jedisManager; 27 | 28 | @Override 29 | public void saveSession(Session session) { 30 | if (session == null || session.getId() == null) 31 | throw new NullPointerException("session is empty"); 32 | try { 33 | byte[] key = SerializeUtil.serialize(buildRedisSessionKey(session.getId())); 34 | 35 | 36 | //不存在才添加。 37 | if(null == session.getAttribute(CustomSessionManager.SESSION_STATUS)){ 38 | //Session 踢出自存存储。 39 | SessionStatus sessionStatus = new SessionStatus(); 40 | session.setAttribute(CustomSessionManager.SESSION_STATUS, sessionStatus); 41 | } 42 | 43 | byte[] value = SerializeUtil.serialize(session); 44 | long sessionTimeOut = session.getTimeout() / 1000; 45 | Long expireTime = sessionTimeOut + SESSION_VAL_TIME_SPAN + (5 * 60); 46 | getJedisManager().saveValueByKey(DB_INDEX, key, value, expireTime.intValue()); 47 | } catch (Exception e) { 48 | LoggerUtils.fmtError(getClass(), e, "save session error,id:[%s]",session.getId()); 49 | } 50 | } 51 | 52 | @Override 53 | public void deleteSession(Serializable id) { 54 | if (id == null) { 55 | throw new NullPointerException("session id is empty"); 56 | } 57 | try { 58 | getJedisManager().deleteByKey(DB_INDEX, 59 | SerializeUtil.serialize(buildRedisSessionKey(id))); 60 | } catch (Exception e) { 61 | LoggerUtils.fmtError(getClass(), e, "删除session出现异常,id:[%s]",id); 62 | } 63 | } 64 | 65 | 66 | @Override 67 | public Session getSession(Serializable id) { 68 | if (id == null) 69 | throw new NullPointerException("session id is empty"); 70 | Session session = null; 71 | try { 72 | byte[] value = getJedisManager().getValueByKey(DB_INDEX, SerializeUtil 73 | .serialize(buildRedisSessionKey(id))); 74 | session = SerializeUtil.deserialize(value, Session.class); 75 | } catch (Exception e) { 76 | LoggerUtils.fmtError(getClass(), e, "获取session异常,id:[%s]",id); 77 | } 78 | return session; 79 | } 80 | 81 | @Override 82 | public Collection getAllSessions() { 83 | Collection sessions = null; 84 | try { 85 | sessions = getJedisManager().AllSession(DB_INDEX,REDIS_SHIRO_SESSION); 86 | } catch (Exception e) { 87 | LoggerUtils.fmtError(getClass(), e, "获取全部session异常"); 88 | } 89 | 90 | return sessions; 91 | } 92 | 93 | private String buildRedisSessionKey(Serializable sessionId) { 94 | return REDIS_SHIRO_SESSION + sessionId; 95 | } 96 | 97 | public JedisManager getJedisManager() { 98 | return jedisManager; 99 | } 100 | 101 | public void setJedisManager(JedisManager jedisManager) { 102 | this.jedisManager = jedisManager; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/cache/ShiroCacheManager.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.cache; 2 | 3 | import org.apache.shiro.cache.Cache; 4 | 5 | /** 6 | * 7 | * 开发公司:SOJSON在线工具

8 | * 版权所有:© www.sojson.com

9 | * 博客地址:http://www.sojson.com/blog/

10 | *

11 | * 12 | * shiro cache manager 接口 13 | * 14 | *

15 | * 16 | * 区分 责任人 日期    说明
17 | * 创建 周柏成 2016年6月2日  
18 | * 19 | * @author zhou-baicheng 20 | * @email so@sojson.com 21 | * @version 1.0,2016年6月2日
22 | * 23 | */ 24 | public interface ShiroCacheManager { 25 | 26 | Cache getCache(String name); 27 | 28 | void destroy(); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/cache/impl/CustomShiroCacheManager.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.cache.impl; 2 | 3 | import org.apache.shiro.cache.Cache; 4 | import org.apache.shiro.cache.CacheException; 5 | import org.apache.shiro.cache.CacheManager; 6 | import org.apache.shiro.util.Destroyable; 7 | 8 | import com.sojson.core.shiro.cache.ShiroCacheManager; 9 | 10 | /** 11 | * 12 | * 开发公司:sojson.com
13 | * 版权:sojson.com
14 | *

15 | * 16 | * shiro Custom Cache 17 | * 18 | *

19 | * 20 | * 区分 责任人 日期    说明
21 | * 创建 周柏成 2016年4月29日  
22 | *

23 | * ******* 24 | *

25 | * @author zhou-baicheng 26 | * @email json@sojson.com 27 | * @version 1.0,2016年4月29日
28 | * 29 | */ 30 | public class CustomShiroCacheManager implements CacheManager, Destroyable { 31 | 32 | private ShiroCacheManager shiroCacheManager; 33 | 34 | @Override 35 | public Cache getCache(String name) throws CacheException { 36 | return getShiroCacheManager().getCache(name); 37 | } 38 | 39 | @Override 40 | public void destroy() throws Exception { 41 | shiroCacheManager.destroy(); 42 | } 43 | 44 | public ShiroCacheManager getShiroCacheManager() { 45 | return shiroCacheManager; 46 | } 47 | 48 | public void setShiroCacheManager(ShiroCacheManager shiroCacheManager) { 49 | this.shiroCacheManager = shiroCacheManager; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/cache/impl/JedisShiroCacheManager.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.cache.impl; 2 | 3 | import org.apache.shiro.cache.Cache; 4 | 5 | import com.sojson.core.shiro.cache.JedisManager; 6 | import com.sojson.core.shiro.cache.JedisShiroCache; 7 | import com.sojson.core.shiro.cache.ShiroCacheManager; 8 | 9 | /** 10 | * 11 | * 开发公司:SOJSON在线工具

12 | * 版权所有:© www.sojson.com

13 | * 博客地址:http://www.sojson.com/blog/

14 | *

15 | * 16 | * JRedis管理 17 | * 18 | *

19 | * 20 | * 区分 责任人 日期    说明
21 | * 创建 周柏成 2016年6月2日  
22 | * 23 | * @author zhou-baicheng 24 | * @email so@sojson.com 25 | * @version 1.0,2016年6月2日
26 | * 27 | */ 28 | public class JedisShiroCacheManager implements ShiroCacheManager { 29 | 30 | private JedisManager jedisManager; 31 | 32 | @Override 33 | public Cache getCache(String name) { 34 | return new JedisShiroCache(name, getJedisManager()); 35 | } 36 | 37 | @Override 38 | public void destroy() { 39 | //如果和其他系统,或者应用在一起就不能关闭 40 | //getJedisManager().getJedis().shutdown(); 41 | } 42 | 43 | public JedisManager getJedisManager() { 44 | return jedisManager; 45 | } 46 | 47 | public void setJedisManager(JedisManager jedisManager) { 48 | this.jedisManager = jedisManager; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/filter/LoginFilter.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.filter; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import javax.servlet.ServletRequest; 7 | import javax.servlet.ServletResponse; 8 | 9 | import org.apache.shiro.web.filter.AccessControlFilter; 10 | 11 | import com.sojson.common.model.UUser; 12 | import com.sojson.common.utils.LoggerUtils; 13 | import com.sojson.core.shiro.token.manager.TokenManager; 14 | /** 15 | * 16 | * 开发公司:SOJSON在线工具

17 | * 版权所有:© www.sojson.com

18 | * 博客地址:http://www.sojson.com/blog/

19 | *

20 | * 21 | * 判断登录 22 | * 23 | *

24 | * 25 | * 区分 责任人 日期    说明
26 | * 创建 周柏成 2016年6月2日  
27 | * 28 | * @author zhou-baicheng 29 | * @email so@sojson.com 30 | * @version 1.0,2016年6月2日
31 | * 32 | */ 33 | public class LoginFilter extends AccessControlFilter { 34 | final static Class CLASS = LoginFilter.class; 35 | @Override 36 | protected boolean isAccessAllowed(ServletRequest request, 37 | ServletResponse response, Object mappedValue) throws Exception { 38 | 39 | UUser token = TokenManager.getToken(); 40 | 41 | if(null != token || isLoginRequest(request, response)){// && isEnabled() 42 | return Boolean.TRUE; 43 | } 44 | if (ShiroFilterUtils.isAjax(request)) {// ajax请求 45 | Map resultMap = new HashMap(); 46 | LoggerUtils.debug(getClass(), "当前用户没有登录,并且是Ajax请求!"); 47 | resultMap.put("login_status", "300"); 48 | resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");//当前用户没有登录! 49 | ShiroFilterUtils.out(response, resultMap); 50 | } 51 | return Boolean.FALSE ; 52 | 53 | } 54 | 55 | @Override 56 | protected boolean onAccessDenied(ServletRequest request, ServletResponse response) 57 | throws Exception { 58 | //保存Request和Response 到登录后的链接 59 | saveRequestAndRedirectToLogin(request, response); 60 | return Boolean.FALSE ; 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/filter/PermissionFilter.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.filter; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import javax.servlet.ServletRequest; 7 | import javax.servlet.ServletResponse; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | import org.apache.shiro.subject.Subject; 12 | import org.apache.shiro.util.StringUtils; 13 | import org.apache.shiro.web.filter.AccessControlFilter; 14 | import org.apache.shiro.web.util.WebUtils; 15 | 16 | import com.sojson.common.utils.LoggerUtils; 17 | /** 18 | * 19 | * 开发公司:SOJSON在线工具

20 | * 版权所有:© www.sojson.com

21 | * 博客地址:http://www.sojson.com/blog/

22 | *

23 | * 24 | * 权限校验 Filter 25 | * 26 | *

27 | * 28 | * 区分 责任人 日期    说明
29 | * 创建 周柏成 2016年6月2日  
30 | * 31 | * @author zhou-baicheng 32 | * @email so@sojson.com 33 | * @version 1.0,2016年6月2日
34 | * 35 | */ 36 | public class PermissionFilter extends AccessControlFilter { 37 | @Override 38 | protected boolean isAccessAllowed(ServletRequest request, 39 | ServletResponse response, Object mappedValue) throws Exception { 40 | 41 | //先判断带参数的权限判断 42 | Subject subject = getSubject(request, response); 43 | if(null != mappedValue){ 44 | String[] arra = (String[])mappedValue; 45 | for (String permission : arra) { 46 | if(subject.isPermitted(permission)){ 47 | return Boolean.TRUE; 48 | } 49 | } 50 | } 51 | HttpServletRequest httpRequest = ((HttpServletRequest)request); 52 | /** 53 | * 此处是改版后,为了兼容项目不需要部署到root下,也可以正常运行,但是权限没设置目前必须到root 的URI, 54 | * 原因:如果你把这个项目叫 ShiroDemo,那么路径就是 /ShiroDemo/xxxx.shtml ,那另外一个人使用,又叫Shiro_Demo,那么就要这么控制/Shiro_Demo/xxxx.shtml 55 | * 理解了吗? 56 | * 所以这里替换了一下,使用根目录开始的URI 57 | */ 58 | 59 | String uri = httpRequest.getRequestURI();//获取URI 60 | String basePath = httpRequest.getContextPath();//获取basePath 61 | if(null != uri && uri.startsWith(basePath)){ 62 | uri = uri.replace(basePath, ""); 63 | } 64 | if(subject.isPermitted(uri)){ 65 | return Boolean.TRUE; 66 | } 67 | if(ShiroFilterUtils.isAjax(request)){ 68 | Map resultMap = new HashMap(); 69 | LoggerUtils.debug(getClass(), "当前用户没有登录,并且是Ajax请求!"); 70 | resultMap.put("login_status", "300"); 71 | resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");//当前用户没有登录! 72 | ShiroFilterUtils.out(response, resultMap); 73 | } 74 | return Boolean.FALSE; 75 | } 76 | 77 | @Override 78 | protected boolean onAccessDenied(ServletRequest request, 79 | ServletResponse response) throws Exception { 80 | 81 | Subject subject = getSubject(request, response); 82 | if (null == subject.getPrincipal()) {//表示没有登录,重定向到登录页面 83 | saveRequest(request); 84 | WebUtils.issueRedirect(request, response, ShiroFilterUtils.LOGIN_URL); 85 | } else { 86 | if (StringUtils.hasText(ShiroFilterUtils.UNAUTHORIZED)) {//如果有未授权页面跳转过去 87 | WebUtils.issueRedirect(request, response, ShiroFilterUtils.UNAUTHORIZED); 88 | } else {//否则返回401未授权状态码 89 | WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED); 90 | } 91 | } 92 | return Boolean.FALSE; 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/filter/RoleFilter.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.filter; 2 | 3 | import javax.servlet.ServletRequest; 4 | import javax.servlet.ServletResponse; 5 | import javax.servlet.http.HttpServletResponse; 6 | 7 | import org.apache.shiro.subject.Subject; 8 | import org.apache.shiro.util.StringUtils; 9 | import org.apache.shiro.web.filter.AccessControlFilter; 10 | import org.apache.shiro.web.util.WebUtils; 11 | /** 12 | * 13 | * 开发公司:SOJSON在线工具

14 | * 版权所有:© www.sojson.com

15 | * 博客地址:http://www.sojson.com/blog/

16 | *

17 | * 18 | * 角色判断校验 19 | * 20 | *

21 | * 22 | * 区分 责任人 日期    说明
23 | * 创建 周柏成 2016年6月2日  
24 | * 25 | * @author zhou-baicheng 26 | * @email so@sojson.com 27 | * @version 1.0,2016年6月2日
28 | * 29 | */ 30 | public class RoleFilter extends AccessControlFilter { 31 | 32 | static final String LOGIN_URL = "http://www.sojson.com/user/open/toLogin.shtml"; 33 | static final String UNAUTHORIZED_URL = "http://www.sojson.com/unauthorized.html"; 34 | 35 | @Override 36 | protected boolean isAccessAllowed(ServletRequest request, 37 | ServletResponse response, Object mappedValue) throws Exception { 38 | String[] arra = (String[])mappedValue; 39 | 40 | Subject subject = getSubject(request, response); 41 | for (String role : arra) { 42 | if(subject.hasRole("role:" + role)){ 43 | return true; 44 | } 45 | } 46 | return false; 47 | } 48 | 49 | @Override 50 | protected boolean onAccessDenied(ServletRequest request, 51 | ServletResponse response) throws Exception { 52 | 53 | Subject subject = getSubject(request, response); 54 | if (subject.getPrincipal() == null) {//表示没有登录,重定向到登录页面 55 | saveRequest(request); 56 | WebUtils.issueRedirect(request, response, LOGIN_URL); 57 | } else { 58 | if (StringUtils.hasText(UNAUTHORIZED_URL)) {//如果有未授权页面跳转过去 59 | WebUtils.issueRedirect(request, response, UNAUTHORIZED_URL); 60 | } else {//否则返回401未授权状态码 61 | WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED); 62 | } 63 | } 64 | return false; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/filter/ShiroFilterUtils.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.filter; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.util.Map; 6 | 7 | import javax.servlet.ServletRequest; 8 | import javax.servlet.ServletResponse; 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | import com.sojson.common.utils.LoggerUtils; 12 | 13 | import net.sf.json.JSONObject; 14 | 15 | /** 16 | * 17 | * 开发公司:itboy.net
18 | * 版权:itboy.net
19 | *

20 | * 21 | * Shiro Filter 工具类 22 | * 23 | *

24 | * 25 | * 区分 责任人 日期    说明
26 | * 创建 周柏成 2016年5月27日  
27 | *

28 | * ******* 29 | *

30 | * 31 | * @author zhou-baicheng 32 | * @email i@itboy.net 33 | * @version 1.0,2016年5月27日
34 | * 35 | */ 36 | public class ShiroFilterUtils { 37 | final static Class CLAZZ = ShiroFilterUtils.class; 38 | //登录页面 39 | static final String LOGIN_URL = "/u/login.shtml"; 40 | //踢出登录提示 41 | final static String KICKED_OUT = "/open/kickedOut.shtml"; 42 | //没有权限提醒 43 | final static String UNAUTHORIZED = "/open/unauthorized.shtml"; 44 | /** 45 | * 是否是Ajax请求 46 | * @param request 47 | * @return 48 | */ 49 | public static boolean isAjax(ServletRequest request){ 50 | return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With")); 51 | } 52 | 53 | /** 54 | * response 输出JSON 55 | * @param hresponse 56 | * @param resultMap 57 | * @throws IOException 58 | */ 59 | public static void out(ServletResponse response, Map resultMap){ 60 | 61 | PrintWriter out = null; 62 | try { 63 | response.setCharacterEncoding("UTF-8"); 64 | out = response.getWriter(); 65 | out.println(JSONObject.fromObject(resultMap).toString()); 66 | } catch (Exception e) { 67 | LoggerUtils.fmtError(CLAZZ, e, "输出JSON报错。"); 68 | }finally{ 69 | if(null != out){ 70 | out.flush(); 71 | out.close(); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/filter/SimpleAuthFilter.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.filter; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import javax.servlet.ServletRequest; 9 | import javax.servlet.ServletResponse; 10 | import javax.servlet.http.HttpServletRequest; 11 | 12 | import net.sf.json.JSONObject; 13 | 14 | import org.apache.shiro.session.Session; 15 | import org.apache.shiro.subject.Subject; 16 | import org.apache.shiro.web.filter.AccessControlFilter; 17 | import org.apache.shiro.web.util.WebUtils; 18 | 19 | import com.sojson.common.utils.LoggerUtils; 20 | import com.sojson.core.shiro.session.CustomSessionManager; 21 | import com.sojson.core.shiro.session.SessionStatus; 22 | 23 | /** 24 | * 25 | * 开发公司:SOJSON在线工具

26 | * 版权所有:© www.sojson.com

27 | * 博客地址:http://www.sojson.com/blog/

28 | *

29 | * 30 | * 判断是否踢出 31 | * 32 | *

33 | * 34 | * 区分 责任人 日期    说明
35 | * 创建 周柏成 2016年6月2日  
36 | * 37 | * @author zhou-baicheng 38 | * @email so@sojson.com 39 | * @version 1.0,2016年6月2日
40 | * 41 | */ 42 | public class SimpleAuthFilter extends AccessControlFilter { 43 | 44 | @Override 45 | protected boolean isAccessAllowed(ServletRequest request, 46 | ServletResponse response, Object mappedValue) throws Exception { 47 | 48 | HttpServletRequest httpRequest = ((HttpServletRequest)request); 49 | String url = httpRequest.getRequestURI(); 50 | if(url.startsWith("/open/")){ 51 | return Boolean.TRUE; 52 | } 53 | Subject subject = getSubject(request, response); 54 | Session session = subject.getSession(); 55 | Map resultMap = new HashMap(); 56 | SessionStatus sessionStatus = (SessionStatus) session.getAttribute(CustomSessionManager.SESSION_STATUS); 57 | if (null != sessionStatus && !sessionStatus.isOnlineStatus()) { 58 | //判断是不是Ajax请求 59 | if (ShiroFilterUtils.isAjax(request) ) { 60 | LoggerUtils.debug(getClass(), "当前用户已经被踢出,并且是Ajax请求!"); 61 | resultMap.put("user_status", "300"); 62 | resultMap.put("message", "您已经被踢出,请重新登录!"); 63 | out(response, resultMap); 64 | } 65 | return Boolean.FALSE; 66 | } 67 | return Boolean.TRUE; 68 | } 69 | 70 | @Override 71 | protected boolean onAccessDenied(ServletRequest request, 72 | ServletResponse response) throws Exception { 73 | 74 | //先退出 75 | Subject subject = getSubject(request, response); 76 | subject.logout(); 77 | /** 78 | * 保存Request,用来保存当前Request,然后登录后可以跳转到当前浏览的页面。 79 | * 比如: 80 | * 我要访问一个URL地址,/admin/index.html,这个页面是要登录。然后要跳转到登录页面,但是登录后要跳转回来到/admin/index.html这个地址,怎么办? 81 | * 传统的解决方法是变成/user/login.shtml?redirectUrl=/admin/index.html。 82 | * shiro的解决办法不是这样的。需要:WebUtils.getSavedRequest(request); 83 | * 然后:{@link UserLoginController.submitLogin(...)}中的String url = WebUtils.getSavedRequest(request).getRequestUrl(); 84 | * 如果还有问题,请咨询我。 85 | */ 86 | WebUtils.saveRequest(request); 87 | //再重定向 88 | WebUtils.issueRedirect(request, response, "/open/kickedOut.shtml"); 89 | return false; 90 | } 91 | 92 | private void out(ServletResponse hresponse, Map resultMap) 93 | throws IOException { 94 | hresponse.setCharacterEncoding("UTF-8"); 95 | PrintWriter out = hresponse.getWriter(); 96 | out.println(JSONObject.fromObject(resultMap).toString()); 97 | out.flush(); 98 | out.close(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/listenter/CustomSessionListener.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.listenter; 2 | 3 | 4 | import org.apache.shiro.session.Session; 5 | import org.apache.shiro.session.SessionListener; 6 | 7 | import com.sojson.core.shiro.session.ShiroSessionRepository; 8 | /** 9 | * 10 | * 开发公司:SOJSON在线工具

11 | * 版权所有:© www.sojson.com

12 | * 博客地址:http://www.sojson.com/blog/

13 | *

14 | * 15 | * shiro 回话 监听 16 | * 17 | *

18 | * 19 | * 区分 责任人 日期    说明
20 | * 创建 周柏成 2016年6月2日  
21 | * 22 | * @author zhou-baicheng 23 | * @email so@sojson.com 24 | * @version 1.0,2016年6月2日
25 | * 26 | */ 27 | public class CustomSessionListener implements SessionListener { 28 | 29 | private ShiroSessionRepository shiroSessionRepository; 30 | 31 | /** 32 | * 一个回话的生命周期开始 33 | */ 34 | @Override 35 | public void onStart(Session session) { 36 | //TODO 37 | System.out.println("on start"); 38 | } 39 | /** 40 | * 一个回话的生命周期结束 41 | */ 42 | @Override 43 | public void onStop(Session session) { 44 | //TODO 45 | System.out.println("on stop"); 46 | } 47 | 48 | @Override 49 | public void onExpiration(Session session) { 50 | shiroSessionRepository.deleteSession(session.getId()); 51 | } 52 | 53 | public ShiroSessionRepository getShiroSessionRepository() { 54 | return shiroSessionRepository; 55 | } 56 | 57 | public void setShiroSessionRepository(ShiroSessionRepository shiroSessionRepository) { 58 | this.shiroSessionRepository = shiroSessionRepository; 59 | } 60 | 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/service/ShiroManager.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.service; 2 | 3 | public interface ShiroManager { 4 | 5 | /** 6 | * 加载过滤配置信息 7 | * @return 8 | */ 9 | public String loadFilterChainDefinitions(); 10 | 11 | /** 12 | * 重新构建权限过滤器 13 | * 一般在修改了用户角色、用户等信息时,需要再次调用该方法 14 | */ 15 | public void reCreateFilterChains(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/service/impl/ShiroManagerImpl.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.service.impl; 2 | 3 | import java.io.IOException; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import javax.annotation.Resource; 8 | 9 | import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 10 | import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager; 11 | import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver; 12 | import org.apache.shiro.web.servlet.AbstractShiroFilter; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.core.io.ClassPathResource; 15 | 16 | import com.sojson.common.utils.LoggerUtils; 17 | import com.sojson.core.config.INI4j; 18 | import com.sojson.core.shiro.service.ShiroManager; 19 | /** 20 | * 21 | * 开发公司:SOJSON在线工具

22 | * 版权所有:© www.sojson.com

23 | * 博客地址:http://www.sojson.com/blog/

24 | *

25 | * 26 | * 动态加载权限 Service 27 | * 28 | *

29 | * 30 | * 区分 责任人 日期    说明
31 | * 创建 周柏成 2016年6月2日  
32 | * 33 | * @author zhou-baicheng 34 | * @email so@sojson.com 35 | * @version 1.0,2016年6月2日
36 | * 37 | */ 38 | public class ShiroManagerImpl implements ShiroManager { 39 | 40 | // 注意/r/n前不能有空格 41 | private static final String CRLF = "\r\n"; 42 | 43 | @Resource 44 | @Autowired 45 | private ShiroFilterFactoryBean shiroFilterFactoryBean; 46 | 47 | 48 | @Override 49 | public String loadFilterChainDefinitions() { 50 | StringBuffer sb = new StringBuffer(); 51 | sb.append(getFixedAuthRule());//固定权限,采用读取配置文件 52 | return sb.toString(); 53 | } 54 | 55 | /** 56 | * 从配额文件获取固定权限验证规则串 57 | */ 58 | private String getFixedAuthRule(){ 59 | String fileName = "shiro_base_auth.ini"; 60 | ClassPathResource cp = new ClassPathResource(fileName); 61 | INI4j ini = null; 62 | try { 63 | ini = new INI4j(cp.getFile()); 64 | } catch (IOException e) { 65 | LoggerUtils.fmtError(getClass(), e, "加载文件出错。file:[%s]", fileName); 66 | } 67 | String section = "base_auth"; 68 | Set keys = ini.get(section).keySet(); 69 | StringBuffer sb = new StringBuffer(); 70 | for (String key : keys) { 71 | String value = ini.get(section, key); 72 | sb.append(key).append(" = ") 73 | .append(value).append(CRLF); 74 | } 75 | 76 | return sb.toString(); 77 | 78 | } 79 | 80 | // 此方法加同步锁 81 | @Override 82 | public synchronized void reCreateFilterChains() { 83 | // ShiroFilterFactoryBean shiroFilterFactoryBean = (ShiroFilterFactoryBean) SpringContextUtil.getBean("shiroFilterFactoryBean"); 84 | AbstractShiroFilter shiroFilter = null; 85 | try { 86 | shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject(); 87 | } catch (Exception e) { 88 | LoggerUtils.error(getClass(),"getShiroFilter from shiroFilterFactoryBean error!", e); 89 | throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!"); 90 | } 91 | 92 | PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter 93 | .getFilterChainResolver(); 94 | DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver 95 | .getFilterChainManager(); 96 | 97 | // 清空老的权限控制 98 | manager.getFilterChains().clear(); 99 | 100 | shiroFilterFactoryBean.getFilterChainDefinitionMap().clear(); 101 | shiroFilterFactoryBean.setFilterChainDefinitions(loadFilterChainDefinitions()); 102 | // 重新构建生成 103 | Map chains = shiroFilterFactoryBean 104 | .getFilterChainDefinitionMap(); 105 | for (Map.Entry entry : chains.entrySet()) { 106 | String url = entry.getKey(); 107 | String chainDefinition = entry.getValue().trim().replace(" ", ""); 108 | manager.createChain(url, chainDefinition); 109 | } 110 | 111 | } 112 | public void setShiroFilterFactoryBean( 113 | ShiroFilterFactoryBean shiroFilterFactoryBean) { 114 | this.shiroFilterFactoryBean = shiroFilterFactoryBean; 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/session/SessionStatus.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.session; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 7 | * 开发公司:SOJSON在线工具

8 | * 版权所有:© www.sojson.com

9 | * 博客地址:http://www.sojson.com/blog/

10 | *

11 | * 12 | * Session 状态 VO 13 | * 14 | *

15 | * 16 | * 区分 责任人 日期    说明
17 | * 创建 周柏成 2016年6月2日  
18 | * 19 | * @author zhou-baicheng 20 | * @email so@sojson.com 21 | * @version 1.0,2016年6月2日
22 | * 23 | */ 24 | public class SessionStatus implements Serializable { 25 | private static final long serialVersionUID = 1L; 26 | 27 | //是否踢出 true:有效,false:踢出。 28 | private Boolean onlineStatus = Boolean.TRUE; 29 | 30 | 31 | public Boolean isOnlineStatus(){ 32 | return onlineStatus; 33 | } 34 | 35 | public Boolean getOnlineStatus() { 36 | return onlineStatus; 37 | } 38 | public void setOnlineStatus(Boolean onlineStatus) { 39 | this.onlineStatus = onlineStatus; 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/session/ShiroSessionRepository.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.session; 2 | 3 | import org.apache.shiro.session.Session; 4 | 5 | import java.io.Serializable; 6 | import java.util.Collection; 7 | 8 | /** 9 | * 10 | * 开发公司:SOJSON在线工具

11 | * 版权所有:© www.sojson.com

12 | * 博客地址:http://www.sojson.com/blog/

13 | *

14 | * 15 | * Session操作 16 | * 17 | *

18 | * 19 | * 区分 责任人 日期    说明
20 | * 创建 周柏成 2016年6月2日  
21 | * 22 | * @author zhou-baicheng 23 | * @email so@sojson.com 24 | * @version 1.0,2016年6月2日
25 | * 26 | */ 27 | public interface ShiroSessionRepository { 28 | 29 | /** 30 | * 存储Session 31 | * @param session 32 | */ 33 | void saveSession(Session session); 34 | /** 35 | * 删除session 36 | * @param sessionId 37 | */ 38 | void deleteSession(Serializable sessionId); 39 | /** 40 | * 获取session 41 | * @param sessionId 42 | * @return 43 | */ 44 | Session getSession(Serializable sessionId); 45 | /** 46 | * 获取所有sessoin 47 | * @return 48 | */ 49 | Collection getAllSessions(); 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/token/SampleRealm.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.token; 2 | 3 | import java.util.Date; 4 | import java.util.Set; 5 | 6 | import org.apache.shiro.SecurityUtils; 7 | import org.apache.shiro.authc.AccountException; 8 | import org.apache.shiro.authc.AuthenticationException; 9 | import org.apache.shiro.authc.AuthenticationInfo; 10 | import org.apache.shiro.authc.AuthenticationToken; 11 | import org.apache.shiro.authc.DisabledAccountException; 12 | import org.apache.shiro.authc.SimpleAuthenticationInfo; 13 | import org.apache.shiro.authz.AuthorizationInfo; 14 | import org.apache.shiro.authz.SimpleAuthorizationInfo; 15 | import org.apache.shiro.realm.AuthorizingRealm; 16 | import org.apache.shiro.subject.PrincipalCollection; 17 | import org.apache.shiro.subject.SimplePrincipalCollection; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | 20 | import com.sojson.common.model.UUser; 21 | import com.sojson.core.shiro.token.manager.TokenManager; 22 | import com.sojson.permission.service.PermissionService; 23 | import com.sojson.permission.service.RoleService; 24 | import com.sojson.user.service.UUserService; 25 | 26 | 27 | /** 28 | * 29 | * 开发公司:SOJSON在线工具

30 | * 版权所有:© www.sojson.com

31 | * 博客地址:http://www.sojson.com/blog/

32 | *

33 | * 34 | * shiro 认证 + 授权 重写 35 | * 36 | *

37 | * 38 | * 区分 责任人 日期    说明
39 | * 创建 周柏成 2016年6月2日  
40 | * 41 | * @author zhou-baicheng 42 | * @email so@sojson.com 43 | * @version 1.0,2016年6月2日
44 | * 45 | */ 46 | public class SampleRealm extends AuthorizingRealm { 47 | 48 | @Autowired 49 | UUserService userService; 50 | @Autowired 51 | PermissionService permissionService; 52 | @Autowired 53 | RoleService roleService; 54 | 55 | public SampleRealm() { 56 | super(); 57 | } 58 | /** 59 | * 认证信息,主要针对用户登录, 60 | */ 61 | protected AuthenticationInfo doGetAuthenticationInfo( 62 | AuthenticationToken authcToken) throws AuthenticationException { 63 | 64 | ShiroToken token = (ShiroToken) authcToken; 65 | UUser user = userService.login(token.getUsername(),token.getPswd()); 66 | if(null == user){ 67 | throw new AccountException("帐号或密码不正确!"); 68 | /** 69 | * 如果用户的status为禁用。那么就抛出DisabledAccountException 70 | */ 71 | }else if(UUser._0.equals(user.getStatus())){ 72 | throw new DisabledAccountException("帐号已经禁止登录!"); 73 | }else{ 74 | //更新登录时间 last login time 75 | user.setLastLoginTime(new Date()); 76 | userService.updateByPrimaryKeySelective(user); 77 | } 78 | return new SimpleAuthenticationInfo(user,user.getPswd(), getName()); 79 | } 80 | 81 | /** 82 | * 授权 83 | */ 84 | @Override 85 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 86 | 87 | Long userId = TokenManager.getUserId(); 88 | SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 89 | //根据用户ID查询角色(role),放入到Authorization里。 90 | Set roles = roleService.findRoleByUserId(userId); 91 | info.setRoles(roles); 92 | //根据用户ID查询权限(permission),放入到Authorization里。 93 | Set permissions = permissionService.findPermissionByUserId(userId); 94 | info.setStringPermissions(permissions); 95 | return info; 96 | } 97 | /** 98 | * 清空当前用户权限信息 99 | */ 100 | public void clearCachedAuthorizationInfo() { 101 | PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals(); 102 | SimplePrincipalCollection principals = new SimplePrincipalCollection( 103 | principalCollection, getName()); 104 | super.clearCachedAuthorizationInfo(principals); 105 | } 106 | /** 107 | * 指定principalCollection 清除 108 | */ 109 | public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) { 110 | SimplePrincipalCollection principals = new SimplePrincipalCollection( 111 | principalCollection, getName()); 112 | super.clearCachedAuthorizationInfo(principals); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/shiro/token/ShiroToken.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.shiro.token; 2 | 3 | import org.apache.shiro.authc.UsernamePasswordToken; 4 | /** 5 | * 6 | * 开发公司:SOJSON在线工具

7 | * 版权所有:© www.sojson.com

8 | * 博客地址:http://www.sojson.com/blog/

9 | *

10 | * 11 | * Shiro token 12 | * 13 | *

14 | * 15 | * 区分 责任人 日期    说明
16 | * 创建 周柏成 2016年6月2日  
17 | * 18 | * @author zhou-baicheng 19 | * @email so@sojson.com 20 | * @version 1.0,2016年6月2日
21 | * 22 | */ 23 | public class ShiroToken extends UsernamePasswordToken implements java.io.Serializable{ 24 | 25 | private static final long serialVersionUID = -6451794657814516274L; 26 | 27 | public ShiroToken(String username, String pswd) { 28 | super(username,pswd); 29 | this.pswd = pswd ; 30 | } 31 | 32 | 33 | /** 登录密码[字符串类型] 因为父类是char[] ] **/ 34 | private String pswd ; 35 | 36 | public String getPswd() { 37 | return pswd; 38 | } 39 | 40 | 41 | public void setPswd(String pswd) { 42 | this.pswd = pswd; 43 | } 44 | 45 | 46 | 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/statics/APPKEY.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.statics; 2 | /** 3 | * 不可变参数定义 4 | * 第三方参数 5 | * @author zhou-baicheng 6 | * 7 | */ 8 | public interface APPKEY { 9 | /**豆瓣*/ 10 | String DOUBAN_API_KEY = ""; 11 | String DOUBAN_SECRET_KEY = ""; 12 | /**豆瓣*/ 13 | 14 | /**新浪*/ 15 | String SINA_API_KEY = ""; 16 | String SINA_SECRET_KEY = ""; 17 | String SINA_TOKEN = ""; 18 | /**新浪*/ 19 | /**QQ*/ 20 | String QQ_OPEN_ID = ""; 21 | String QQ_SECRET_KEY = ""; 22 | String QQ_TOKEN = ""; 23 | /**QQ*/ 24 | 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/statics/Constant.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.statics; 2 | 3 | import java.util.Calendar; 4 | 5 | import com.sojson.common.utils.DateUtil; 6 | import com.sojson.core.config.IConfig; 7 | 8 | /** 9 | * 10 | * 开发公司:SOJSON在线工具

11 | * 版权所有:© www.sojson.com

12 | * 博客地址:http://www.sojson.com/blog/

13 | *

14 | * 15 | * 静态变量 16 | * 17 | *

18 | * 19 | * 区分 责任人 日期    说明
20 | * 创建 周柏成 2016年6月2日  
21 | * 22 | * @author zhou-baicheng 23 | * @email so@sojson.com 24 | * @version 1.0,2016年6月2日
25 | * 26 | */ 27 | public interface Constant { 28 | 29 | static final String CONTEXT_PATH = "contextPath";/***项目根路径*/ 30 | 31 | /***Freemarker 使用的变量 begin**/ 32 | 33 | static final String TARGET = "target";//标签使用目标 34 | 35 | static final String OUT_TAG_NAME = "outTagName";//输出标签Name 36 | 37 | /***Freemarker 使用的变量 end**/ 38 | 39 | 40 | /**其他常用变量 begin**/ 41 | static final String NAME = "name" ; 42 | static final String ID = "id" ; 43 | static final String TOKEN = "token" ; 44 | static final String LOING_USER = "loing_user" ; 45 | /**Long */ 46 | static final Long ZERO = new Long(0); 47 | static final Long ONE = new Long(1); 48 | static final Long TWO = new Long(2); 49 | static final Long THREE = new Long(3); 50 | static final Long EIGHT = new Long(8); 51 | 52 | /**String */ 53 | static final String S_ZERO = "0"; 54 | static final String S_ONE = "1"; 55 | static final String S_TOW = "2"; 56 | static final String S_THREE = "3"; 57 | 58 | /**Integer */ 59 | static final Integer I_ZERO = 0; 60 | static final Integer I_ONE = 1; 61 | static final Integer I_TOW = 2; 62 | static final Integer I_THREE = 3; 63 | /**其他常用变量 end**/ 64 | 65 | /**cache常用变量 begin**/ 66 | static final String CACHE_NAME = "shiro_cache"; 67 | static final String CACHE_MANAGER = "cacheManager" ;//cacheManager bean name 68 | /**cache常用变量 end**/ 69 | 70 | /**当前年份**/ 71 | static final int NOW_YEAY = Calendar.getInstance().get(Calendar.YEAR); 72 | 73 | 74 | /**地址**/ 75 | static final String DOMAIN_WWW = IConfig.get("domain.www");//前端域名 76 | static final String DOMAIN_CDN = IConfig.get("domain.cdn");//后台域名 77 | static String VERSION = DateUtil.dateToStringWithTime();//版本号,重启的时间 78 | 79 | 80 | //存储到缓存,标识用户的禁止状态,解决在线用户踢出的问题 81 | final static String EXECUTE_CHANGE_USER = "SOJSON_EXECUTE_CHANGE_USER"; 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/tags/APITemplateModel.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.tags; 2 | 3 | import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import com.sojson.common.utils.LoggerUtils; 9 | import com.sojson.common.utils.SpringContextUtil; 10 | import com.sojson.core.statics.Constant; 11 | 12 | import freemarker.template.TemplateModel; 13 | import freemarker.template.TemplateModelException; 14 | 15 | /** 16 | * 17 | * 开发公司:SOJSON在线工具

18 | * 版权所有:© www.sojson.com

19 | * 博客地址:http://www.sojson.com/blog/

20 | *

21 | * 22 | * Freemarker 自定义标签 API公共入口 23 | * 24 | *

25 | * 26 | * 区分 责任人 日期    说明
27 | * 创建 周柏成 2016年6月2日  
28 | * 29 | * @author zhou-baicheng 30 | * @email so@sojson.com 31 | * @version 1.0,2016年6月2日
32 | * 33 | */ 34 | 35 | public class APITemplateModel extends WYFTemplateModel { 36 | 37 | @Override 38 | @SuppressWarnings({ "unchecked" }) 39 | protected Map putValue(Map params) 40 | throws TemplateModelException { 41 | 42 | Map paramWrap = null ; 43 | if(null != params && params.size() != 0 || null != params.get(Constant.TARGET)){ 44 | String name = params.get(Constant.TARGET).toString() ; 45 | paramWrap = new HashMap(params); 46 | 47 | /** 48 | * 获取子类,用父类接收, 49 | */ 50 | SuperCustomTag tag = SpringContextUtil.getBean(name,SuperCustomTag.class); 51 | //父类调用子类方法 52 | Object result = tag.result(params); 53 | 54 | //输出 55 | paramWrap.put(Constant.OUT_TAG_NAME, DEFAULT_WRAPPER.wrap(result)); 56 | }else{ 57 | LoggerUtils.error(getClass(), "Cannot be null, must include a 'name' attribute!"); 58 | } 59 | return paramWrap; 60 | } 61 | 62 | 63 | 64 | 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/tags/SuperCustomTag.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.tags; 2 | 3 | import java.util.Map; 4 | 5 | import com.sojson.common.utils.StringUtils; 6 | /** 7 | * 8 | * 开发公司:SOJSON在线工具

9 | * 版权所有:© www.sojson.com

10 | * 博客地址:http://www.sojson.com/blog/

11 | *

12 | * 13 | * 自定义标签的父类。 14 | * 15 | *

16 | * 17 | * 区分 责任人 日期    说明
18 | * 创建 周柏成 2016年6月2日  
19 | * 20 | * @author zhou-baicheng 21 | * @email so@sojson.com 22 | * @version 1.0,2016年6月2日
23 | * 24 | */ 25 | @SuppressWarnings("unchecked") 26 | public abstract class SuperCustomTag { 27 | 28 | /** 29 | * 本方法采用多态集成的方式,然后用父类接收,用父类调用子类的 {@link result(...)} 方法。 30 | * @param params 31 | * @return 32 | */ 33 | protected abstract Object result(Map params); 34 | 35 | 36 | /** 37 | * 直接强转报错,需要用Object过度一下 38 | * @param e 39 | * @return 40 | */ 41 | protected Long getLong(Map params,String key){ 42 | Object i = params.get(key); 43 | return StringUtils.isBlank(i)?null:new Long(i.toString()); 44 | } 45 | protected String getString(Map params,String key){ 46 | Object i = params.get(key); 47 | return StringUtils.isBlank(i)?null:i.toString(); 48 | } 49 | protected Integer getInt(Map params,String key){ 50 | Object i = params.get(key); 51 | return StringUtils.isBlank(i)?null:Integer.parseInt(i.toString()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/core/tags/WYFTemplateModel.java: -------------------------------------------------------------------------------- 1 | package com.sojson.core.tags; 2 | 3 | 4 | import java.io.IOException; 5 | import java.util.Map; 6 | 7 | import com.sojson.core.freemarker.utils.FreemarkerTagUtil; 8 | 9 | import freemarker.core.Environment; 10 | import freemarker.template.TemplateDirectiveBody; 11 | import freemarker.template.TemplateDirectiveModel; 12 | import freemarker.template.TemplateException; 13 | import freemarker.template.TemplateModel; 14 | import freemarker.template.TemplateModelException; 15 | 16 | 17 | /** 18 | * 19 | * 开发公司:WENYIFAN.NET
20 | * 版权:WENYIFAN.NET
21 | *

22 | * 基础标签类 23 | *

24 | * 25 | * 区分 责任人 日期    说明
26 | * 创建 周柏成 2014年4月28日  
27 | *

28 | * ******* 29 | *

30 | * @author zhou-baicheng 31 | * 32 | * @version 1.0,2014年4月28日
33 | * 34 | */ 35 | @SuppressWarnings("unchecked") 36 | public abstract class WYFTemplateModel implements TemplateDirectiveModel{ 37 | 38 | 39 | @Override 40 | public void execute(Environment env, Map params, TemplateModel[] loopVars, 41 | TemplateDirectiveBody body) throws TemplateException, IOException { 42 | 43 | 44 | /** 45 | * 模版方法模式,把变化委派下去,交给子类实现! 46 | */ 47 | Map paramWrap = putValue(params); 48 | 49 | 50 | Map origMap = FreemarkerTagUtil.convertToTemplateModel(env, paramWrap); 51 | body.render(env.getOut()); 52 | FreemarkerTagUtil.clearTempleModel(env, paramWrap, origMap); 53 | } 54 | 55 | /** 56 | * 子类实现 57 | * @param params 58 | * @return 59 | * @throws TemplateModelException 60 | */ 61 | protected abstract Map putValue(Map params) throws TemplateModelException; 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/bo/RolePermissionAllocationBo.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.bo; 2 | 3 | import java.io.Serializable; 4 | /** 5 | * 权限分配 查询列表BO 6 | * @author zhou-baicheng 7 | * 8 | */ 9 | public class RolePermissionAllocationBo implements Serializable { 10 | private static final long serialVersionUID = 1L; 11 | //角色ID 12 | private Long id; 13 | //角色type 14 | private String type; 15 | //角色Name 16 | private String name; 17 | //权限Name列转行,以,分割 18 | private String permissionNames; 19 | //权限Id列转行,以‘,’分割 20 | private String permissionIds; 21 | 22 | public Long getId() { 23 | return id; 24 | } 25 | 26 | public void setId(Long id) { 27 | this.id = id; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public String getType() { 39 | return type; 40 | } 41 | 42 | public void setType(String type) { 43 | this.type = type; 44 | } 45 | 46 | public String getPermissionNames() { 47 | return permissionNames; 48 | } 49 | 50 | public void setPermissionNames(String permissionNames) { 51 | this.permissionNames = permissionNames; 52 | } 53 | 54 | public String getPermissionIds() { 55 | return permissionIds; 56 | } 57 | 58 | public void setPermissionIds(String permissionIds) { 59 | this.permissionIds = permissionIds; 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/bo/UPermissionBo.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.bo; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.sojson.common.model.UPermission; 6 | import com.sojson.common.utils.StringUtils; 7 | 8 | /** 9 | * 10 | * 权限选择 11 | * @author zhou-baicheng 12 | * 13 | */ 14 | public class UPermissionBo extends UPermission implements Serializable { 15 | private static final long serialVersionUID = 1L; 16 | /** 17 | * 是否勾选 18 | */ 19 | private String marker; 20 | /** 21 | * role Id 22 | */ 23 | private String roleId; 24 | 25 | public boolean isCheck(){ 26 | return StringUtils.equals(roleId,marker); 27 | } 28 | public String getMarker() { 29 | return marker; 30 | } 31 | 32 | public void setMarker(String marker) { 33 | this.marker = marker; 34 | } 35 | public String getRoleId() { 36 | return roleId; 37 | } 38 | public void setRoleId(String roleId) { 39 | this.roleId = roleId; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/bo/URoleBo.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.bo; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.sojson.common.model.URole; 6 | import com.sojson.common.utils.StringUtils; 7 | 8 | public class URoleBo extends URole implements Serializable{ 9 | private static final long serialVersionUID = 1L; 10 | /** 11 | * 用户ID (用String, 考虑多个ID,现在只有一个ID) 12 | */ 13 | private String userId; 14 | /** 15 | * 是否勾选 16 | */ 17 | private String marker; 18 | 19 | public boolean isCheck(){ 20 | return StringUtils.equals(userId,marker); 21 | } 22 | public String getMarker() { 23 | return marker; 24 | } 25 | 26 | public void setMarker(String marker) { 27 | this.marker = marker; 28 | } 29 | public String getUserId() { 30 | return userId; 31 | } 32 | public void setUserId(String userId) { 33 | this.userId = userId; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/bo/UserRoleAllocationBo.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.bo; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.sojson.common.model.UUser; 6 | /** 7 | * 用户角色分配 查询列表BO 8 | * @author zhou-baicheng 9 | * 10 | */ 11 | public class UserRoleAllocationBo extends UUser implements Serializable { 12 | private static final long serialVersionUID = 1L; 13 | 14 | //Role Name列转行,以,分割 15 | private String roleNames; 16 | //Role Id列转行,以‘,’分割 17 | private String roleIds; 18 | public String getRoleNames() { 19 | return roleNames; 20 | } 21 | public void setRoleNames(String roleNames) { 22 | this.roleNames = roleNames; 23 | } 24 | public String getRoleIds() { 25 | return roleIds; 26 | } 27 | public void setRoleIds(String roleIds) { 28 | this.roleIds = roleIds; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/controller/PermissionAllocationController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.controller; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.ModelMap; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | import org.springframework.web.servlet.ModelAndView; 13 | 14 | import com.sojson.common.controller.BaseController; 15 | import com.sojson.core.mybatis.page.Pagination; 16 | import com.sojson.permission.bo.RolePermissionAllocationBo; 17 | import com.sojson.permission.bo.UPermissionBo; 18 | import com.sojson.permission.service.PermissionService; 19 | import com.sojson.permission.service.RoleService; 20 | /** 21 | * 22 | * 开发公司:itboy.net
23 | * 版权:itboy.net
24 | *

25 | * 26 | * 用户权限分配 27 | * 28 | *

29 | * 30 | * 区分 责任人 日期    说明
31 | * 创建 周柏成 2016年5月26日  
32 | *

33 | * ******* 34 | *

35 | * @author zhou-baicheng 36 | * @email i@itboy.net 37 | * @version 1.0,2016年5月26日
38 | * 39 | */ 40 | @Controller 41 | @Scope(value="prototype") 42 | @RequestMapping("permission") 43 | public class PermissionAllocationController extends BaseController { 44 | 45 | @Autowired 46 | PermissionService permissionService; 47 | @Autowired 48 | RoleService roleService; 49 | /** 50 | * 权限分配 51 | * @param modelMap 52 | * @param pageNo 53 | * @param findContent 54 | * @return 55 | */ 56 | @RequestMapping(value="allocation") 57 | public ModelAndView allocation(ModelMap modelMap,Integer pageNo,String findContent){ 58 | modelMap.put("findContent", findContent); 59 | Pagination boPage = roleService.findRoleAndPermissionPage(modelMap,pageNo,pageSize); 60 | modelMap.put("page", boPage); 61 | return new ModelAndView("permission/allocation"); 62 | } 63 | 64 | /** 65 | * 根据角色ID查询权限 66 | * @param id 67 | * @return 68 | */ 69 | @RequestMapping(value="selectPermissionById") 70 | @ResponseBody 71 | public List selectPermissionById(Long id){ 72 | List permissionBos = permissionService.selectPermissionById(id); 73 | return permissionBos; 74 | } 75 | /** 76 | * 操作角色的权限 77 | * @param roleId 角色ID 78 | * @param ids 权限ID,以‘,’间隔 79 | * @return 80 | */ 81 | @RequestMapping(value="addPermission2Role") 82 | @ResponseBody 83 | public Map addPermission2Role(Long roleId,String ids){ 84 | return permissionService.addPermission2Role(roleId,ids); 85 | } 86 | /** 87 | * 根据角色id清空权限。 88 | * @param roleIds 角色ID ,以‘,’间隔 89 | * @return 90 | */ 91 | @RequestMapping(value="clearPermissionByRoleIds") 92 | @ResponseBody 93 | public Map clearPermissionByRoleIds(String roleIds){ 94 | return permissionService.deleteByRids(roleIds); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/controller/PermissionController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.controller; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Scope; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.ui.ModelMap; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | import org.springframework.web.servlet.ModelAndView; 13 | 14 | import com.sojson.common.controller.BaseController; 15 | import com.sojson.common.model.UPermission; 16 | import com.sojson.common.utils.LoggerUtils; 17 | import com.sojson.core.mybatis.page.Pagination; 18 | import com.sojson.permission.service.PermissionService; 19 | /** 20 | * 21 | * 开发公司:itboy.net
22 | * 版权:itboy.net
23 | *

24 | * 25 | * 用户权限管理 26 | * 27 | *

28 | * 29 | * 区分 责任人 日期    说明
30 | * 创建 周柏成 2016年5月26日  
31 | *

32 | * ******* 33 | *

34 | * @author zhou-baicheng 35 | * @email i@itboy.net 36 | * @version 1.0,2016年5月26日
37 | * 38 | */ 39 | @Controller 40 | @Scope(value="prototype") 41 | @RequestMapping("permission") 42 | public class PermissionController extends BaseController { 43 | 44 | @Autowired 45 | PermissionService permissionService; 46 | /** 47 | * 权限列表 48 | * @param findContent 查询内容 49 | * @param pageNo 页码 50 | * @param modelMap 参数回显 51 | * @return 52 | */ 53 | @RequestMapping(value="index") 54 | public ModelAndView index(String findContent,ModelMap modelMap,Integer pageNo){ 55 | modelMap.put("findContent", findContent); 56 | Pagination permissions = permissionService.findPage(modelMap,pageNo,pageSize); 57 | return new ModelAndView("permission/index","page",permissions); 58 | } 59 | /** 60 | * 权限添加 61 | * @param role 62 | * @return 63 | */ 64 | @RequestMapping(value="addPermission",method=RequestMethod.POST) 65 | @ResponseBody 66 | public Map addPermission(UPermission psermission){ 67 | try { 68 | UPermission entity = permissionService.insertSelective(psermission); 69 | resultMap.put("status", 200); 70 | resultMap.put("entity", entity); 71 | } catch (Exception e) { 72 | resultMap.put("status", 500); 73 | resultMap.put("message", "添加失败,请刷新后再试!"); 74 | LoggerUtils.fmtError(getClass(), e, "添加权限报错。source[%s]", psermission.toString()); 75 | } 76 | return resultMap; 77 | } 78 | /** 79 | * 删除权限,根据ID,但是删除权限的时候,需要查询是否有赋予给角色,如果有角色在使用,那么就不能删除。 80 | * @param id 81 | * @return 82 | */ 83 | @RequestMapping(value="deletePermissionById",method=RequestMethod.POST) 84 | @ResponseBody 85 | public Map deleteRoleById(String ids){ 86 | return permissionService.deletePermissionById(ids); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/controller/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.controller; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.ModelMap; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | import org.springframework.web.servlet.ModelAndView; 14 | 15 | import com.sojson.common.controller.BaseController; 16 | import com.sojson.common.model.URole; 17 | import com.sojson.common.utils.LoggerUtils; 18 | import com.sojson.core.mybatis.page.Pagination; 19 | import com.sojson.permission.service.RoleService; 20 | import com.sojson.user.manager.UserManager; 21 | /** 22 | * 23 | * 开发公司:itboy.net
24 | * 版权:itboy.net
25 | *

26 | * 27 | * 用户角色管理 28 | * 29 | *

30 | * 31 | * 区分 责任人 日期    说明
32 | * 创建 周柏成 2016年5月26日  
33 | *

34 | * ******* 35 | *

36 | * @author zhou-baicheng 37 | * @email i@itboy.net 38 | * @version 1.0,2016年5月26日
39 | * 40 | */ 41 | @Controller 42 | @Scope(value="prototype") 43 | @RequestMapping("role") 44 | public class RoleController extends BaseController { 45 | @Autowired 46 | RoleService roleService; 47 | /** 48 | * 角色列表 49 | * @return 50 | */ 51 | @RequestMapping(value="index") 52 | public ModelAndView index(String findContent,ModelMap modelMap){ 53 | modelMap.put("findContent", findContent); 54 | Pagination role = roleService.findPage(modelMap,pageNo,pageSize); 55 | return new ModelAndView("role/index","page",role); 56 | } 57 | /** 58 | * 角色添加 59 | * @param role 60 | * @return 61 | */ 62 | @RequestMapping(value="addRole",method=RequestMethod.POST) 63 | @ResponseBody 64 | public Map addRole(URole role){ 65 | try { 66 | int count = roleService.insertSelective(role); 67 | resultMap.put("status", 200); 68 | resultMap.put("successCount", count); 69 | } catch (Exception e) { 70 | resultMap.put("status", 500); 71 | resultMap.put("message", "添加失败,请刷新后再试!"); 72 | LoggerUtils.fmtError(getClass(), e, "添加角色报错。source[%s]",role.toString()); 73 | } 74 | return resultMap; 75 | } 76 | /** 77 | * 删除角色,根据ID,但是删除角色的时候,需要查询是否有赋予给用户,如果有用户在使用,那么就不能删除。 78 | * @param id 79 | * @return 80 | */ 81 | @RequestMapping(value="deleteRoleById",method=RequestMethod.POST) 82 | @ResponseBody 83 | public Map deleteRoleById(String ids){ 84 | return roleService.deleteRoleById(ids); 85 | } 86 | /** 87 | * 我的权限页面 88 | * @return 89 | */ 90 | @RequestMapping(value="mypermission",method=RequestMethod.GET) 91 | public ModelAndView mypermission(){ 92 | return new ModelAndView("permission/mypermission"); 93 | } 94 | /** 95 | * 我的权限 bootstrap tree data 96 | * @return 97 | */ 98 | @RequestMapping(value="getPermissionTree",method=RequestMethod.POST) 99 | @ResponseBody 100 | public List> getPermissionTree(){ 101 | //查询我所有的角色 ---> 权限 102 | List roles = roleService.findNowAllPermission(); 103 | //把查询出来的roles 转换成bootstarp 的 tree数据 104 | List> data = UserManager.toTreeData(roles); 105 | return data; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/controller/UserRoleAllocationController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.controller; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.ModelMap; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | import org.springframework.web.servlet.ModelAndView; 13 | 14 | import com.sojson.common.controller.BaseController; 15 | import com.sojson.core.mybatis.page.Pagination; 16 | import com.sojson.permission.bo.URoleBo; 17 | import com.sojson.permission.bo.UserRoleAllocationBo; 18 | import com.sojson.permission.service.PermissionService; 19 | import com.sojson.user.service.UUserService; 20 | /** 21 | * 22 | * 开发公司:SOJSON在线工具

23 | * 版权所有:© www.sojson.com

24 | * 博客地址:http://www.sojson.com/blog/

25 | *

26 | * 27 | * 用户角色分配 28 | * 29 | *

30 | * 31 | * 区分 责任人 日期    说明
32 | * 创建 周柏成 2016年6月2日  
33 | * 34 | * @author zhou-baicheng 35 | * @email so@sojson.com 36 | * @version 1.0,2016年6月2日
37 | * 38 | */ 39 | @Controller 40 | @Scope(value="prototype") 41 | @RequestMapping("role") 42 | public class UserRoleAllocationController extends BaseController { 43 | @Autowired 44 | UUserService userService; 45 | @Autowired 46 | PermissionService permissionService; 47 | /** 48 | * 用户角色权限分配 49 | * @param modelMap 50 | * @param pageNo 51 | * @param findContent 52 | * @return 53 | */ 54 | @RequestMapping(value="allocation") 55 | public ModelAndView allocation(ModelMap modelMap,Integer pageNo,String findContent){ 56 | modelMap.put("findContent", findContent); 57 | Pagination boPage = userService.findUserAndRole(modelMap,pageNo,pageSize); 58 | modelMap.put("page", boPage); 59 | return new ModelAndView("role/allocation"); 60 | } 61 | 62 | /** 63 | * 根据用户ID查询权限 64 | * @param id 65 | * @return 66 | */ 67 | @RequestMapping(value="selectRoleByUserId") 68 | @ResponseBody 69 | public List selectRoleByUserId(Long id){ 70 | List bos = userService.selectRoleByUserId(id); 71 | return bos; 72 | } 73 | /** 74 | * 操作用户的角色 75 | * @param userId 用户ID 76 | * @param ids 角色ID,以‘,’间隔 77 | * @return 78 | */ 79 | @RequestMapping(value="addRole2User") 80 | @ResponseBody 81 | public Map addRole2User(Long userId,String ids){ 82 | return userService.addRole2User(userId,ids); 83 | } 84 | /** 85 | * 根据用户id清空角色。 86 | * @param userIds 用户ID ,以‘,’间隔 87 | * @return 88 | */ 89 | @RequestMapping(value="clearRoleByUserIds") 90 | @ResponseBody 91 | public Map clearRoleByUserIds(String userIds){ 92 | return userService.deleteRoleByUserIds(userIds); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/service/PermissionService.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.service; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import com.sojson.common.model.UPermission; 8 | import com.sojson.core.mybatis.page.Pagination; 9 | import com.sojson.permission.bo.UPermissionBo; 10 | 11 | public interface PermissionService { 12 | 13 | int deleteByPrimaryKey(Long id); 14 | 15 | UPermission insert(UPermission record); 16 | 17 | UPermission insertSelective(UPermission record); 18 | 19 | UPermission selectByPrimaryKey(Long id); 20 | 21 | int updateByPrimaryKeySelective(UPermission record); 22 | 23 | int updateByPrimaryKey(UPermission record); 24 | 25 | Map deletePermissionById(String ids); 26 | 27 | Pagination findPage(Map resultMap, Integer pageNo, 28 | Integer pageSize); 29 | List selectPermissionById(Long id); 30 | 31 | Map addPermission2Role(Long roleId,String ids); 32 | 33 | Map deleteByRids(String roleIds); 34 | //根据用户ID查询权限(permission),放入到Authorization里。 35 | Set findPermissionByUserId(Long userId); 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.service; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import com.sojson.common.model.URole; 8 | import com.sojson.core.mybatis.page.Pagination; 9 | import com.sojson.permission.bo.RolePermissionAllocationBo; 10 | 11 | public interface RoleService { 12 | 13 | int deleteByPrimaryKey(Long id); 14 | 15 | int insert(URole record); 16 | 17 | int insertSelective(URole record); 18 | 19 | URole selectByPrimaryKey(Long id); 20 | 21 | int updateByPrimaryKeySelective(URole record); 22 | 23 | int updateByPrimaryKey(URole record); 24 | 25 | Pagination findPage(Map resultMap, Integer pageNo, 26 | Integer pageSize); 27 | 28 | Map deleteRoleById(String ids); 29 | 30 | Pagination findRoleAndPermissionPage( 31 | Map resultMap, Integer pageNo, Integer pageSize); 32 | //根据用户ID查询角色(role),放入到Authorization里。 33 | Set findRoleByUserId(Long userId); 34 | 35 | List findNowAllPermission(); 36 | //初始化数据 37 | void initData(); 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/permission/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.sojson.permission.service.impl; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | import com.sojson.common.dao.URoleMapper; 13 | import com.sojson.common.dao.URolePermissionMapper; 14 | import com.sojson.common.dao.UUserMapper; 15 | import com.sojson.common.model.URole; 16 | import com.sojson.common.utils.LoggerUtils; 17 | import com.sojson.core.mybatis.BaseMybatisDao; 18 | import com.sojson.core.mybatis.page.Pagination; 19 | import com.sojson.core.shiro.token.manager.TokenManager; 20 | import com.sojson.permission.bo.RolePermissionAllocationBo; 21 | import com.sojson.permission.service.RoleService; 22 | 23 | @Service 24 | @SuppressWarnings("unchecked") 25 | public class RoleServiceImpl extends BaseMybatisDao implements RoleService { 26 | 27 | @Autowired 28 | URoleMapper roleMapper; 29 | @Autowired 30 | UUserMapper userMapper; 31 | @Autowired 32 | URolePermissionMapper rolePermissionMapper; 33 | 34 | @Override 35 | public int deleteByPrimaryKey(Long id) { 36 | return roleMapper.deleteByPrimaryKey(id); 37 | } 38 | 39 | @Override 40 | public int insert(URole record) { 41 | return roleMapper.insert(record); 42 | } 43 | 44 | @Override 45 | public int insertSelective(URole record) { 46 | return roleMapper.insertSelective(record); 47 | } 48 | 49 | @Override 50 | public URole selectByPrimaryKey(Long id) { 51 | return roleMapper.selectByPrimaryKey(id); 52 | } 53 | 54 | @Override 55 | public int updateByPrimaryKey(URole record) { 56 | return roleMapper.updateByPrimaryKey(record); 57 | } 58 | 59 | @Override 60 | public int updateByPrimaryKeySelective(URole record) { 61 | return roleMapper.updateByPrimaryKeySelective(record); 62 | } 63 | 64 | 65 | @Override 66 | public Pagination findPage(Map resultMap, 67 | Integer pageNo, Integer pageSize) { 68 | return super.findPage(resultMap, pageNo, pageSize); 69 | } 70 | @Override 71 | public Pagination findRoleAndPermissionPage( 72 | Map resultMap, Integer pageNo, Integer pageSize) { 73 | return super.findPage("findRoleAndPermission", "findCount", resultMap, pageNo, pageSize); 74 | } 75 | @Override 76 | public Map deleteRoleById(String ids) { 77 | Map resultMap = new HashMap(); 78 | try { 79 | int count=0; 80 | String resultMsg = "删除成功。"; 81 | String[] idArray = new String[]{}; 82 | if(StringUtils.contains(ids, ",")){ 83 | idArray = ids.split(","); 84 | }else{ 85 | idArray = new String[]{ids}; 86 | } 87 | 88 | c:for (String idx : idArray) { 89 | Long id = new Long(idx); 90 | if(new Long(1).equals(id)){ 91 | resultMsg = "操作成功,But'系统管理员不能删除。"; 92 | continue c; 93 | }else{ 94 | count+=this.deleteByPrimaryKey(id); 95 | } 96 | } 97 | resultMap.put("status", 200); 98 | resultMap.put("count", count); 99 | resultMap.put("resultMsg", resultMsg); 100 | } catch (Exception e) { 101 | LoggerUtils.fmtError(getClass(), e, "根据IDS删除用户出现错误,ids[%s]", ids); 102 | resultMap.put("status", 500); 103 | resultMap.put("message", "删除出现错误,请刷新后再试!"); 104 | } 105 | return resultMap; 106 | } 107 | 108 | @Override 109 | public Set findRoleByUserId(Long userId) { 110 | return roleMapper.findRoleByUserId(userId); 111 | } 112 | 113 | @Override 114 | public List findNowAllPermission() { 115 | Map map = new HashMap(); 116 | map.put("userId", TokenManager.getUserId()); 117 | return roleMapper.findNowAllPermission(map); 118 | } 119 | /** 120 | * 每20分钟执行一次 121 | */ 122 | @Override 123 | public void initData() { 124 | roleMapper.initData(); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/bo/SubmitDto.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.bo; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | import org.apache.commons.beanutils.BeanUtils; 9 | import org.apache.commons.codec.binary.StringUtils; 10 | 11 | 12 | 13 | /** 14 | * 模拟的数据对象 15 | * @author Administrator 16 | * 17 | */ 18 | public class SubmitDto { 19 | 20 | private String phone; 21 | 22 | private String loginName; 23 | 24 | private transient String password; 25 | 26 | public SubmitDto() { 27 | 28 | } 29 | /** 30 | * 从Request里取到信息,和outMap匹配 31 | * @param outMap 32 | * @param request 33 | */ 34 | public SubmitDto(Map outMap, HttpServletRequest request) { 35 | Map requestMap = request.getParameterMap(); 36 | 37 | for (String key : requestMap.keySet()) { 38 | if(outMap.containsValue(key)){ 39 | try { 40 | BeanUtils.setProperty(this, getKeyByValue(outMap, key), requestMap.get(key)); 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | 45 | } 46 | } 47 | } 48 | /** 49 | * 根据value 找 Key ,这里的前提是生成的value不重复 50 | * @param outMap 51 | * @param value 52 | * @return 53 | */ 54 | public String getKeyByValue(Map outMap,String value){ 55 | for (String key : outMap.keySet()) { 56 | String v = outMap.get(key); 57 | if(StringUtils.equals(v, value)){ 58 | return key; 59 | } 60 | } 61 | return null; 62 | } 63 | 64 | /** 65 | * 把字段用随机字母替代 66 | * @return 67 | */ 68 | public Map securitySelf(){ 69 | Map map = new LinkedHashMap(); 70 | map.put("phone", getRandom()); 71 | map.put("loginName", getRandom()); 72 | map.put("password", getRandom()); 73 | return map; 74 | } 75 | 76 | /** 77 | * 随机字母作为字段替代的name 78 | * @return 79 | */ 80 | public static String getRandom(){ 81 | String az = "abcdefghijklmnopqrstuvwxyz"; 82 | return String.valueOf(az.charAt((int)(Math.random() * 26))); 83 | } 84 | 85 | public String getPhone() { 86 | return phone; 87 | } 88 | 89 | public void setPhone(String phone) { 90 | this.phone = phone; 91 | } 92 | 93 | public String getLoginName() { 94 | return loginName; 95 | } 96 | 97 | public void setLoginName(String loginName) { 98 | this.loginName = loginName; 99 | } 100 | 101 | public String getPassword() { 102 | return password; 103 | } 104 | 105 | public void setPassword(String password) { 106 | this.password = password; 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/bo/UserOnlineBo.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.bo; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import com.sojson.common.model.UUser; 7 | /** 8 | * Session + User Bo 9 | * @author sojson.com 10 | * 11 | */ 12 | public class UserOnlineBo extends UUser implements Serializable { 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | //Session Id 17 | private String sessionId; 18 | //Session Host 19 | private String host; 20 | //Session创建时间 21 | private Date startTime; 22 | //Session最后交互时间 23 | private Date lastAccess; 24 | //Session timeout 25 | private long timeout; 26 | //session 是否踢出 27 | private boolean sessionStatus = Boolean.TRUE; 28 | 29 | public UserOnlineBo() { 30 | } 31 | 32 | public UserOnlineBo(UUser user) { 33 | super(user); 34 | } 35 | 36 | 37 | public String getSessionId() { 38 | return sessionId; 39 | } 40 | 41 | public void setSessionId(String sessionId) { 42 | this.sessionId = sessionId; 43 | } 44 | 45 | public String getHost() { 46 | return host; 47 | } 48 | 49 | public void setHost(String host) { 50 | this.host = host; 51 | } 52 | 53 | public Date getStartTime() { 54 | return startTime; 55 | } 56 | 57 | public void setStartTime(Date startTime) { 58 | this.startTime = startTime; 59 | } 60 | 61 | public Date getLastAccess() { 62 | return lastAccess; 63 | } 64 | 65 | public void setLastAccess(Date lastAccess) { 66 | this.lastAccess = lastAccess; 67 | } 68 | 69 | public long getTimeout() { 70 | return timeout; 71 | } 72 | 73 | public void setTimeout(long timeout) { 74 | this.timeout = timeout; 75 | } 76 | 77 | public boolean isSessionStatus() { 78 | return sessionStatus; 79 | } 80 | 81 | public void setSessionStatus(boolean sessionStatus) { 82 | this.sessionStatus = sessionStatus; 83 | } 84 | 85 | 86 | 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/controller/DemoTestSubmitController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.controller; 2 | 3 | import java.util.Map; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpSession; 7 | 8 | import org.springframework.context.annotation.Scope; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.ui.ModelMap; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.servlet.ModelAndView; 14 | 15 | import com.sojson.common.controller.BaseController; 16 | import com.sojson.common.utils.MathUtil; 17 | import com.sojson.user.bo.SubmitDto; 18 | 19 | @Controller 20 | @Scope(value="prototype") 21 | @RequestMapping("demo") 22 | public class DemoTestSubmitController extends BaseController { 23 | 24 | final static String OUT_MAP = DemoTestSubmitController.class.getCanonicalName() + "_outMap"; 25 | final static String URL_PART = DemoTestSubmitController.class.getCanonicalName() + "_url"; 26 | 27 | 28 | @RequestMapping(value="index") 29 | public ModelAndView list(ModelMap map,HttpServletRequest request){ 30 | //页面输出map构建。 31 | Map outMap = new SubmitDto().securitySelf(); 32 | //存储Session , 或者存储缓存(带时效). 33 | HttpSession session = request.getSession(); 34 | session.setAttribute(OUT_MAP, outMap); 35 | //输出到页面使用 36 | map.putAll(outMap); 37 | //url 动态输出Session, 或者存储缓存(带时效). 38 | String urlPart = MathUtil.getRandom620(10); 39 | session.setAttribute(URL_PART, urlPart); 40 | //页面显示 41 | map.put("urlPart", urlPart); 42 | return new ModelAndView("demo/index"); 43 | } 44 | /** 45 | * 提交 46 | * @param request 47 | * @return 48 | */ 49 | @RequestMapping(value="submit/{urlPart}") 50 | public SubmitDto submit(@PathVariable("urlPart")String urlPart,HttpServletRequest request){ 51 | 52 | HttpSession session = request.getSession(); 53 | //从Session获取URL信息 54 | String sessionUrlPart = (String) session.getAttribute(URL_PART); 55 | //如果地址为null 或者和Session中取到的信息不一样 56 | if(null == urlPart || !urlPart.equals(sessionUrlPart)){ 57 | return null;//提示错误 58 | } 59 | 60 | Map outMap = (Map ) session.getAttribute(OUT_MAP); 61 | //设置属性 62 | SubmitDto dto = new SubmitDto(outMap,request); 63 | //各种业务完成后,删除相关信息。保证只能有效用一次 64 | session.removeAttribute(URL_PART); 65 | session.removeAttribute(OUT_MAP); 66 | 67 | 68 | return dto ; 69 | } 70 | 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/controller/MemberController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.controller; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Scope; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.ModelMap; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | import org.springframework.web.servlet.ModelAndView; 15 | 16 | import com.sojson.common.controller.BaseController; 17 | import com.sojson.common.model.UUser; 18 | import com.sojson.core.mybatis.page.Pagination; 19 | import com.sojson.core.shiro.session.CustomSessionManager; 20 | import com.sojson.user.bo.UserOnlineBo; 21 | import com.sojson.user.service.UUserService; 22 | /** 23 | * 24 | * 开发公司:itboy.net
25 | * 版权:itboy.net
26 | *

27 | * 28 | * 用户会员管理 29 | * 30 | *

31 | * 32 | * 区分 责任人 日期    说明
33 | * 创建 周柏成 2016年5月26日  
34 | *

35 | * ******* 36 | *

37 | * @author zhou-baicheng 38 | * @email i@itboy.net 39 | * @version 1.0,2016年5月26日
40 | * 41 | */ 42 | @Controller 43 | @Scope(value="prototype") 44 | @RequestMapping("member") 45 | public class MemberController extends BaseController { 46 | /*** 47 | * 用户手动操作Session 48 | * */ 49 | @Autowired 50 | CustomSessionManager customSessionManager; 51 | @Autowired 52 | UUserService userService; 53 | /** 54 | * 用户列表管理 55 | * @return 56 | */ 57 | @RequestMapping(value="list") 58 | public ModelAndView list(ModelMap map,Integer pageNo,String findContent){ 59 | 60 | map.put("findContent", findContent); 61 | Pagination page = userService.findByPage(map,pageNo,pageSize); 62 | map.put("page", page); 63 | return new ModelAndView("member/list"); 64 | } 65 | /** 66 | * 在线用户管理 67 | * @return 68 | */ 69 | @RequestMapping(value="online") 70 | public ModelAndView online(){ 71 | List list = customSessionManager.getAllUser(); 72 | return new ModelAndView("member/online","list",list); 73 | } 74 | /** 75 | * 在线用户详情 76 | * @return 77 | */ 78 | @RequestMapping(value="onlineDetails/{sessionId}",method=RequestMethod.GET) 79 | public ModelAndView onlineDetails(@PathVariable("sessionId")String sessionId){ 80 | UserOnlineBo bo = customSessionManager.getSession(sessionId); 81 | return new ModelAndView("member/onlineDetails","bo",bo); 82 | } 83 | /** 84 | * 改变Session状态 85 | * @param status 86 | * @param sessionId 87 | * @return 88 | */ 89 | @RequestMapping(value="changeSessionStatus",method=RequestMethod.POST) 90 | @ResponseBody 91 | public Map changeSessionStatus(Boolean status,String sessionIds){ 92 | return customSessionManager.changeSessionStatus(status,sessionIds); 93 | } 94 | /** 95 | * 根据ID删除, 96 | * @param ids 如果有多个,以“,”间隔。 97 | * @return 98 | */ 99 | @RequestMapping(value="deleteUserById",method=RequestMethod.POST) 100 | @ResponseBody 101 | public Map deleteUserById(String ids){ 102 | return userService.deleteUserById(ids); 103 | } 104 | /** 105 | * 禁止登录 106 | * @param id 用户ID 107 | * @param status 1:有效,0:禁止登录 108 | * @return 109 | */ 110 | @RequestMapping(value="forbidUserById",method=RequestMethod.POST) 111 | @ResponseBody 112 | public Map forbidUserById(Long id,Long status){ 113 | return userService.updateForbidUserById(id,status); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/controller/UserCoreController.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.controller; 2 | 3 | import java.util.Map; 4 | 5 | import javax.annotation.Resource; 6 | 7 | import net.sf.json.JSONObject; 8 | 9 | import org.springframework.context.annotation.Scope; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RequestMethod; 14 | import org.springframework.web.bind.annotation.ResponseBody; 15 | import org.springframework.web.servlet.ModelAndView; 16 | 17 | import com.sojson.common.controller.BaseController; 18 | import com.sojson.common.model.UUser; 19 | import com.sojson.common.utils.LoggerUtils; 20 | import com.sojson.core.shiro.token.manager.TokenManager; 21 | import com.sojson.user.manager.UserManager; 22 | import com.sojson.user.service.UUserService; 23 | 24 | /** 25 | * 26 | * 开发公司:itboy.net
27 | * 版权:itboy.net
28 | *

29 | * 30 | * 用户管理 31 | * 32 | *

33 | * 34 | * 区分 责任人 日期    说明
35 | * 创建 周柏成 2016年5月3日  
36 | *

37 | * ******* 38 | *

39 | * @author zhou-baicheng 40 | * @email i@itboy.net 41 | * @version 1.0,2016年5月3日
42 | * 43 | */ 44 | @Controller 45 | @Scope(value="prototype") 46 | @RequestMapping("user") 47 | public class UserCoreController extends BaseController { 48 | 49 | @Resource 50 | UUserService userService; 51 | /** 52 | * 个人资料 53 | * @return 54 | */ 55 | @RequestMapping(value="index",method=RequestMethod.GET) 56 | public ModelAndView userIndex(){ 57 | 58 | return new ModelAndView("user/index"); 59 | } 60 | 61 | 62 | /** 63 | * 偷懒一下,通用页面跳转 64 | * @param page 65 | * @return 66 | */ 67 | @RequestMapping(value="{page}",method=RequestMethod.GET) 68 | public ModelAndView toPage(@PathVariable("page")String page){ 69 | return new ModelAndView(String.format("user/%s", page)); 70 | } 71 | /** 72 | * 密码修改 73 | * @return 74 | */ 75 | @RequestMapping(value="updatePswd",method=RequestMethod.POST) 76 | @ResponseBody 77 | public Map updatePswd(String pswd,String newPswd){ 78 | //根据当前登录的用户帐号 + 老密码,查询。 79 | String email = TokenManager.getToken().getEmail(); 80 | pswd = UserManager.md5Pswd(email, pswd); 81 | UUser user = userService.login(email, pswd); 82 | 83 | if("admin".equals(email)){ 84 | resultMap.put("status", 300); 85 | resultMap.put("message", "管理员不准修改密码。"); 86 | return resultMap; 87 | } 88 | 89 | if(null == user){ 90 | resultMap.put("status", 300); 91 | resultMap.put("message", "密码不正确!"); 92 | }else{ 93 | user.setPswd(newPswd); 94 | //加工密码 95 | user = UserManager.md5Pswd(user); 96 | //修改密码 97 | userService.updateByPrimaryKeySelective(user); 98 | resultMap.put("status", 200); 99 | resultMap.put("message", "修改成功!"); 100 | //重新登录一次 101 | TokenManager.login(user, Boolean.TRUE); 102 | } 103 | return resultMap; 104 | } 105 | /** 106 | * 个人资料修改 107 | * @return 108 | */ 109 | @RequestMapping(value="updateSelf",method=RequestMethod.POST) 110 | @ResponseBody 111 | public Map updateSelf(UUser entity){ 112 | try { 113 | userService.updateByPrimaryKeySelective(entity); 114 | resultMap.put("status", 200); 115 | resultMap.put("message", "修改成功!"); 116 | } catch (Exception e) { 117 | resultMap.put("status", 500); 118 | resultMap.put("message", "修改失败!"); 119 | LoggerUtils.fmtError(getClass(), e, "修改个人资料出错。[%s]", JSONObject.fromObject(entity).toString()); 120 | } 121 | return resultMap; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/manager/UserManager.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.manager; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import com.sojson.common.model.UPermission; 9 | import com.sojson.common.model.URole; 10 | import com.sojson.common.model.UUser; 11 | import com.sojson.common.utils.MathUtil; 12 | 13 | public class UserManager { 14 | 15 | /** 16 | * 加工密码,和登录一致。 17 | * @param user 18 | * @return 19 | */ 20 | public static UUser md5Pswd(UUser user){ 21 | //密码为 email + '#' + pswd,然后MD5 22 | user.setPswd(md5Pswd(user.getEmail(),user.getPswd())); 23 | return user; 24 | } 25 | /** 26 | * 字符串返回值 27 | * @param email 28 | * @param pswd 29 | * @return 30 | */ 31 | public static String md5Pswd(String email ,String pswd){ 32 | pswd = String.format("%s#%s", email,pswd); 33 | pswd = MathUtil.getMD5(pswd); 34 | return pswd; 35 | } 36 | /** 37 | * 把查询出来的roles 转换成bootstarp 的 tree数据 38 | * @param roles 39 | * @return 40 | */ 41 | public static List> toTreeData(List roles){ 42 | List> resultData = new LinkedList>(); 43 | for (URole u : roles) { 44 | //角色列表 45 | Map map = new LinkedHashMap(); 46 | map.put("text", u.getName());//名称 47 | map.put("href", "javascript:void(0)");//链接 48 | List ps = u.getPermissions(); 49 | map.put("tags", new Integer[]{ps.size()});//显示子数据条数 50 | if(null != ps && ps.size() > 0){ 51 | List> list = new LinkedList>(); 52 | //权限列表 53 | for (UPermission up : ps) { 54 | Map mapx = new LinkedHashMap(); 55 | mapx.put("text", up.getName());//权限名称 56 | mapx.put("href", up.getUrl());//权限url 57 | //mapx.put("tags", "0");//没有下一级 58 | list.add(mapx); 59 | } 60 | map.put("nodes", list); 61 | } 62 | resultData.add(map); 63 | } 64 | return resultData; 65 | 66 | } 67 | 68 | public static void main(String[] args) { 69 | System.out.println(md5Pswd("admin","admin")); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/sojson/user/service/UUserService.java: -------------------------------------------------------------------------------- 1 | package com.sojson.user.service; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.ui.ModelMap; 7 | 8 | import com.sojson.common.model.UUser; 9 | import com.sojson.core.mybatis.page.Pagination; 10 | import com.sojson.permission.bo.URoleBo; 11 | import com.sojson.permission.bo.UserRoleAllocationBo; 12 | 13 | public interface UUserService { 14 | 15 | int deleteByPrimaryKey(Long id); 16 | 17 | UUser insert(UUser record); 18 | 19 | UUser insertSelective(UUser record); 20 | 21 | UUser selectByPrimaryKey(Long id); 22 | 23 | int updateByPrimaryKeySelective(UUser record); 24 | 25 | int updateByPrimaryKey(UUser record); 26 | 27 | UUser login(String email ,String pswd); 28 | 29 | UUser findUserByEmail(String email); 30 | 31 | Pagination findByPage(Map resultMap, Integer pageNo, 32 | Integer pageSize); 33 | 34 | Map deleteUserById(String ids); 35 | 36 | Map updateForbidUserById(Long id, Long status); 37 | 38 | Pagination findUserAndRole(ModelMap modelMap, 39 | Integer pageNo, Integer pageSize); 40 | 41 | List selectRoleByUserId(Long id); 42 | 43 | Map addRole2User(Long userId, String ids); 44 | 45 | Map deleteRoleByUserIds(String userIds); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/resources/config.properties: -------------------------------------------------------------------------------- 1 | domain.www=http://www.sojson.com 2 | #???? 3 | domain.cdn=http\://cdn.sojson.com 4 | -------------------------------------------------------------------------------- /src/main/resources/jdbc.properties: -------------------------------------------------------------------------------- 1 | #Detailed introduction for http://www.sojson.com/blog/47 2 | jdbc.driverClassName=com.mysql.jdbc.Driver 3 | jdbc.url=jdbc:mysql://localhost/shiro?useUnicode=true&characterEncoding=gbk 4 | jdbc.username=root 5 | jdbc.password=123456 6 | jdbc.initialSize=3 7 | jdbc.minIdle=2 8 | jdbc.maxActive=60 9 | jdbc.maxWait=60000 10 | jdbc.timeBetweenEvictionRunsMillis=60000 11 | jdbc.minEvictableIdleTimeMillis=30000 12 | jdbc.validationQuery=SELECT 'x' 13 | jdbc.testWhileIdle=true 14 | jdbc.testOnBorrow=false 15 | jdbc.testOnReturn=false 16 | jdbc.poolPreparedStatements=true 17 | jdbc.maxPoolPreparedStatementPerConnectionSize=20 18 | jdbc.removeAbandoned=true 19 | jdbc.removeAbandonedTimeout=120 20 | jdbc.logAbandoned=false 21 | jdbc.filters=stat -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=debug,Console 2 | 3 | log4j.appender.Console=org.apache.log4j.ConsoleAppender 4 | log4j.appender.Console.Target=System.out 5 | log4j.appender.Console.layout=org.apache.log4j.PatternLayout 6 | log4j.appender.Console.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n 7 | -------------------------------------------------------------------------------- /src/main/resources/mapper/URolePermissionMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | rid, pid 11 | 12 | 13 | 18 | 19 | 24 | 25 | 31 | 32 | 33 | delete from u_role_permission where pid = #{id,jdbcType=BIGINT} 34 | 35 | 36 | 37 | delete from u_role_permission where rid = #{id,jdbcType=BIGINT} 38 | 39 | 40 | 41 | delete from u_role_permission where rid = #{rid,jdbcType=BIGINT} 42 | and pid = #{pid,jdbcType=BIGINT} 43 | 44 | 45 | 46 | delete from u_role_permission where rid in(${roleIds}) 47 | 48 | 49 | 50 | 51 | insert into u_role_permission (rid, pid) 52 | values (#{rid,jdbcType=BIGINT}, #{pid,jdbcType=BIGINT}) 53 | 54 | 55 | insert into u_role_permission 56 | 57 | 58 | rid, 59 | 60 | 61 | pid, 62 | 63 | 64 | 65 | 66 | #{rid,jdbcType=BIGINT}, 67 | 68 | 69 | #{pid,jdbcType=BIGINT}, 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UUserRoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | insert into u_user_role (uid, rid) 10 | values (#{uid,jdbcType=BIGINT}, #{rid,jdbcType=BIGINT}) 11 | 12 | 13 | 14 | delete from u_user_role where uid = #{id,jdbcType=BIGINT} 15 | 16 | 17 | delete from u_user_role where uid in(${userIds}) 18 | 19 | 20 | 23 | 24 | 25 | insert into u_user_role 26 | 27 | 28 | uid, 29 | 30 | 31 | rid, 32 | 33 | 34 | 35 | 36 | #{uid,jdbcType=BIGINT}, 37 | 38 | 39 | #{rid,jdbcType=BIGINT}, 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/main/resources/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 23 | -------------------------------------------------------------------------------- /src/main/resources/shiro-config.properties: -------------------------------------------------------------------------------- 1 | session.timeout=12000000 2 | session.validate.timespan=18000000 -------------------------------------------------------------------------------- /src/main/resources/shiro_base_auth.ini: -------------------------------------------------------------------------------- 1 | [base_auth] 2 | /u/**=anon 3 | /user/**=kickout,simple,login 4 | /js/**=anon 5 | /css/**=anon 6 | /open/**=anon 7 | 8 | #不用校验地址是否有权限 9 | /permission/selectPermissionById.shtml=kickout,simple,login 10 | /member/onlineDetails/**=kickout,simple,login 11 | /role/mypermission.shtml=kickout,simple,login 12 | /role/getPermissionTree.shtml=kickout,simple,login 13 | /role/selectRoleByUserId.shtml=kickout,simple,login 14 | 15 | 16 | #需要根据地址校验有无权限 17 | /permission/**=kickout,simple,login,permission 18 | /role/**=kickout,simple,login,permission 19 | /member/**=kickout,simple,login,permission 20 | #ps:kickout 是校验是否踢出的,如果嫌配置多,可以在装载的时候拼入 21 | 22 | 23 | /**=simple,login 24 | -------------------------------------------------------------------------------- /src/main/resources/spring-cache.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 31 | 32 | 37 | -------------------------------------------------------------------------------- /src/main/resources/spring-timer.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 15 | 16 | 18 | 19 | 20 | 21 | 22 | classpath:jdbc.properties 23 | classpath:config.properties 24 | classpath:shiro-config.properties 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 36 | 37 | -------------------------------------------------------------------------------- /src/main/webapp/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/common/404.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/WEB-INF/ftl/common/404.ftl -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/common/500.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/WEB-INF/ftl/common/500.ftl -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/common/config/left.ftl: -------------------------------------------------------------------------------- 1 | <#macro user index> 2 |

3 | 19 |
20 | 21 | <#macro member index> 22 | <@shiro.hasAnyRoles name='888888,100002'> 23 |
24 | 36 |
37 | 38 | 39 | <#macro role index> 40 | <@shiro.hasAnyRoles name='888888,100003'> 41 |
42 | 73 |
74 | 75 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/common/kicked_out.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 您已经被踢出登录 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 19 | <@_top.top 0/> 20 |
21 |
22 |
23 |

系统提示

24 |
25 |

您已经被系统踢出。请重新登录或者联系管理员!

26 |
27 |
<#--/row--> 28 |
29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/common/unauthorized.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 被拒绝的请求,你没有权限 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 19 | <@_top.top 0/> 20 |
21 |
22 |
23 |

系统提示

24 |
25 |

被拒绝的请求,你没有权限。请重新登录或者联系管理员!

26 |
27 |
<#--/row--> 28 |
29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/demo/index.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 安全提交Demo —个人中心 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | <@_top.top 1/> 15 |
16 | <#--row--> 17 |
18 | <@_left.user 2/> 19 |
20 |

安全提交测试

21 |
22 |
23 |
24 | 25 |
26 |
27 | 28 | 29 | 30 | 31 |
32 | 33 |
34 |
35 |
36 |
37 |
38 | 39 | 40 | 41 | 42 |
43 |
44 |
45 |
46 | 47 | 48 | 49 | 50 |
51 |
52 |
53 | 54 |
55 |

56 |
57 | 58 |
59 |
60 |
61 | <#--/row--> 62 |
63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/member/online.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 当前在线Session — SSM + Shiro Demo 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 47 | 48 | 49 | 50 | <@_top.top 2/> 51 |
52 |
53 | <@_left.member 2/> 54 |
55 |

当前在线用户

56 |
57 |
58 |
59 |
60 | 62 |
63 | <#--pull-right --> 64 | 65 | 66 |
67 |
68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | <#if list?exists && list?size gt 0 > 79 | <#list list as it> 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 93 | 94 | 95 | <#else> 96 | 97 | 98 | 99 | 100 | 101 |
SessionID昵称Email/帐号创建回话回话最后活动状态操作
${it.sessionId?default('未设置')}${it.nickname?default('未设置')}${it.email?default('未设置')}${it.startTime?string('HH:mm:ss yy-MM-dd')}${it.lastAccess?string('HH:mm:ss yy-MM-dd')}${(it.sessionStatus)?string('有效','已踢出')} 88 | 详情 89 | <@shiro.hasPermission name="/member/changeSessionStatus.shtml"> 90 | ${(it.sessionStatus)?string('踢出','激活')} 91 | 92 |
没有用户
102 |
103 |
<#--/row--> 104 |
105 | 106 | 107 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/member/onlineDetails.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Session详情 — SSM + Shiro Demo 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | <@_top.top 2/> 19 |
20 |
21 | <@_left.member 2/> 22 |
23 |

Session详情

24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 |
Session Id${bo.sessionId?default('—')}
Session创建时间${bo.startTime?string('yyyy年MM月dd日 HH:mm:ss')}
Session最后交互时间${bo.lastAccess?string('yyyy年MM月dd日 HH:mm:ss')}
Session 状态${(bo.sessionStatus)?string('有效','已踢出')}
Session Host${bo.host?default('—')}
Session timeout${bo.timeout} (毫秒) = ${bo.timeout/1000}(秒) = ${bo.timeout/1000/60}(分钟)
昵称${bo.nickname?default('—')}
Email/帐号${bo.email?default('—')}
创建时间${bo.createTime?string('yyyy-MM-dd HH:mm')}
最后登录时间${bo.lastLoginTime?string('yyyy-MM-dd HH:mm')}
67 |
68 |
<#--/row--> 69 |
70 | 71 | 72 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/permission/mypermission.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 我的权限 —个人中心 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | <@_top.top 1/> 15 |
16 | <#--row--> 17 |
18 | <@_left.user 2/> 19 |
20 |

我的权限

21 |
22 |
loding... ...
23 |
24 |
25 | <#--/row--> 26 |
27 | 28 | 29 | 30 | 31 | 32 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/user/index.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ${token.nickname} —个人中心 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | <@_top.top 1/> 17 |
18 |
19 | <@_left.user 1/> 20 |
21 |

个人资料

22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
昵称${token.nickname?default('未设置')}
Email/帐号${token.email?default('未设置')}
创建时间${token.createTime?string('yyyy-MM-dd HH:mm')}
最后登录时间${token.lastLoginTime?string('yyyy-MM-dd HH:mm')}
41 |
42 |
43 | <#--/row--> 44 |
45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/user/updatePswd.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 密码修改—个人中心 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 19 | <@_top.top 1/> 20 |
21 |
22 | <@_left.user 1/> 23 |
24 |

密码修改

25 |
26 | 27 |
28 | 29 | 30 |
31 |
32 | 33 | 34 |
35 |
36 | 37 | 38 |
39 |
40 | 41 |
42 | 43 | 44 |
45 |
<#--/row--> 46 |
47 | 48 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/ftl/user/updateSelf.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 资料修改 —个人中心 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 19 | <@_top.top 1/> 20 |
21 |
22 | <@_left.user 1/> 23 |
24 |

资料修改

25 |
26 |
27 | 28 |
29 | 30 | 31 |
32 |
33 | 34 | 35 |
36 |
37 | 38 |
39 |
40 | 41 |
42 | <#--地图 43 | <@_html.tool_map/> 44 | --> 45 |
<#--/row--> 46 |
47 | <#-- 页脚 48 | <@_footer.footer 0/> 49 | --> 50 | 51 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | spring.profiles.active 10 | dev 11 | 12 | 13 | spring.profiles.default 14 | dev 15 | 16 | 17 | spring.liveBeansView.mbeanDomain 18 | dev 19 | 20 | 21 | 22 | contextConfigLocation 23 | classpath*:spring.xml 24 | 25 | 26 | 27 | 字符集过滤器 28 | encodingFilter 29 | org.springframework.web.filter.CharacterEncodingFilter 30 | 31 | 字符集编码 32 | encoding 33 | UTF-8 34 | 35 | 36 | 37 | encodingFilter 38 | /* 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | shiroFilter 47 | org.springframework.web.filter.DelegatingFilterProxy 48 | 49 | 50 | shiroFilter 51 | *.shtml 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | spring监听器 60 | org.springframework.web.context.ContextLoaderListener 61 | 62 | 63 | 64 | org.springframework.web.util.IntrospectorCleanupListener 65 | 66 | 67 | 68 | spring mvc servlet 69 | springMvc 70 | org.springframework.web.servlet.DispatcherServlet 71 | 72 | spring mvc 配置文件 73 | contextConfigLocation 74 | classpath:spring-mvc.xml 75 | 76 | 1 77 | 78 | 79 | springMvc 80 | *.shtml 81 | 82 | 83 | /user/index.shtml 84 | 85 | 86 | 404 87 | /open/404.shtml 88 | 89 | 90 | 500 91 | /open/404.shtml 92 | 93 | 94 | 95 | 900 96 | 97 | 98 | -------------------------------------------------------------------------------- /src/main/webapp/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/favicon.ico -------------------------------------------------------------------------------- /src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/bootstrap/3.3.5/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/extend/layer.ext.js: -------------------------------------------------------------------------------- 1 | /*! layer弹层组件拓展类 */ 2 | ;!function(){layer.use("skin/layer.ext.css",function(){layer.layui_layer_extendlayerextjs=!0});var a=layer.cache,b=function(b){return a.skin?" "+a.skin+" "+a.skin+"-"+b:""};layer.prompt=function(a,c){a=a||{},"function"==typeof a&&(c=a);var d,e=2==a.formType?'":function(){return''}();return layer.open($.extend({btn:["确定","取消"],content:e,skin:"layui-layer-prompt"+b("prompt"),success:function(a){d=a.find(".layui-layer-input"),d.focus()},yes:function(b){var e=d.val();""===e?d.focus():e.length>(a.maxlength||500)?layer.tips("最多输入"+(a.maxlength||500)+"个字数",d,{tips:1}):c&&c(e,b,d)}},a))},layer.tab=function(a){a=a||{};var c=a.tab||{};return layer.open($.extend({type:1,skin:"layui-layer-tab"+b("tab"),title:function(){var a=c.length,b=1,d="";if(a>0)for(d=''+c[0].title+"";a>b;b++)d+=""+c[b].title+"";return d}(),content:'
    '+function(){var a=c.length,b=1,d="";if(a>0)for(d='
  • '+(c[0].content||"no content")+"
  • ";a>b;b++)d+='
  • '+(c[b].content||"no content")+"
  • ";return d}()+"
",success:function(a){var b=a.find(".layui-layer-title").children(),c=a.find(".layui-layer-tabmain").children();b.on("mousedown",function(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0;var b=$(this),d=b.index();b.addClass("layui-layer-tabnow").siblings().removeClass("layui-layer-tabnow"),c.eq(d).show().siblings().hide()})}},a))},layer.photos=function(a,c,d){function e(a,b,c){var d=new Image;d.onload=function(){d.onload=null,b(d)},d.onerror=function(a){d.onload=null,c(a)},d.src=a}var f={};if(a=a||{},a.photos){var g=a.photos.constructor===Object,h=g?a.photos:{},i=h.data||[],j=h.start||0;if(f.imgIndex=j+1,g){if(0===i.length)return void layer.msg("没有图片")}else{var k=$(a.photos),l=k.find(a.img||"img");if(0===l.length)return;if(c||k.find(h.img||"img").each(function(b){var c=$(this);i.push({alt:c.attr("alt"),pid:c.attr("layer-pid"),src:c.attr("layer-src")||c.attr("src"),thumb:c.attr("src")}),c.on("click",function(){layer.photos($.extend(a,{photos:{start:b,data:i,tab:a.tab},full:a.full}),!0)})}),!c)return}f.imgprev=function(a){f.imgIndex--,f.imgIndex<1&&(f.imgIndex=i.length),f.tabimg(a)},f.imgnext=function(a){f.imgIndex++,f.imgIndex>i.length&&(f.imgIndex=1),f.tabimg(a)},f.keyup=function(a){if(!f.end){var b=a.keyCode;a.preventDefault(),37===b?f.imgprev(!0):39===b?f.imgnext(!0):27===b&&layer.close(f.index)}},f.tabimg=function(b){h.start=f.imgIndex-1,layer.close(f.index),layer.photos(a,!0,b)},f.event=function(){f.bigimg.hover(function(){f.imgsee.show()},function(){f.imgsee.hide()}),f.bigimg.find(".layui-layer-imgprev").on("click",function(a){a.preventDefault(),f.imgprev()}),f.bigimg.find(".layui-layer-imgnext").on("click",function(a){a.preventDefault(),f.imgnext()}),$(document).on("keyup",f.keyup)},f.loadi=layer.load(1,{shade:"shade"in a?!1:.9,scrollbar:!1}),e(i[j].src,function(c){layer.close(f.loadi),f.index=layer.open($.extend({type:1,area:function(){var b=[c.width,c.height],d=[$(window).width()-100,$(window).height()-100];return!a.full&&b[0]>d[0]&&(b[0]=d[0],b[1]=b[0]*d[1]/b[0]),[b[0]+"px",b[1]+"px"]}(),title:!1,shade:.9,shadeClose:!0,closeBtn:!1,move:".layui-layer-phimg img",moveType:1,scrollbar:!1,moveOut:!0,shift:5*Math.random()|0,skin:"layui-layer-photos"+b("photos"),content:'
'+(i[j].alt||
'+(i[j].alt||"")+""+f.imgIndex+"/"+i.length+"
",success:function(b,c){f.bigimg=b.find(".layui-layer-phimg"),f.imgsee=b.find(".layui-layer-imguide,.layui-layer-imgbar"),f.event(b),a.tab&&a.tab(i[j],b)},end:function(){f.end=!0,$(document).off("keyup",f.keyup)}},a))},function(){layer.close(f.loadi),layer.msg("当前图片地址异常",{time:2e3},function(){i.length>1&&f.imgnext(!0)})})}}}(); -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/default/icon-ext.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/layer/skin/default/icon-ext.png -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/default/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/layer/skin/default/icon.png -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/default/loading-0.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/layer/skin/default/loading-0.gif -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/default/loading-1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/layer/skin/default/loading-1.gif -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/default/loading-2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qzw1210/SpringMVC_Mybatis_Shiro/c0053f6db4000b34833f0c3954807cd3349ea5a6/src/main/webapp/js/common/layer/skin/default/loading-2.gif -------------------------------------------------------------------------------- /src/main/webapp/js/common/layer/skin/layer.ext.css: -------------------------------------------------------------------------------- 1 | /*! 2 | 3 | @Name: layer拓展样式 4 | @Date: 2012.12.13 5 | @Author: 贤心 6 | @blog: sentsin.com 7 | 8 | */.layui-layer-imgbar,.layui-layer-imgtit a,.layui-layer-tab .layui-layer-title span{text-overflow:ellipsis;white-space:nowrap}.layui-layer-iconext{background:url(default/icon-ext.png) no-repeat}html #layui_layer_skinlayerextcss{display:none;position:absolute;width:1989px}.layui-layer-prompt .layui-layer-input{display:block;width:220px;height:30px;margin:0 auto;line-height:30px;padding:0 5px;border:1px solid #ccc;box-shadow:1px 1px 5px rgba(0,0,0,.1) inset;color:#333}.layui-layer-prompt textarea.layui-layer-input{width:300px;height:100px;line-height:20px}.layui-layer-tab{box-shadow:1px 1px 50px rgba(0,0,0,.4)}.layui-layer-tab .layui-layer-title{padding-left:0;border-bottom:1px solid #ccc;background-color:#eee;overflow:visible}.layui-layer-tab .layui-layer-title span{position:relative;float:left;min-width:80px;max-width:260px;padding:0 20px;text-align:center;cursor:default;overflow:hidden}.layui-layer-tab .layui-layer-title span.layui-layer-tabnow{height:36px;border-left:1px solid #ccc;border-right:1px solid #ccc;background-color:#fff;z-index:10}.layui-layer-tab .layui-layer-title span:first-child{border-left:none}.layui-layer-tabmain{line-height:24px;clear:both}.layui-layer-tabmain .layui-layer-tabli{display:none}.layui-layer-tabmain .layui-layer-tabli.xubox_tab_layer{display:block}.xubox_tabclose{position:absolute;right:10px;top:5px;cursor:pointer}.layui-layer-photos{-webkit-animation-duration:1s;animation-duration:1s;background:url(default/xubox_loading1.gif) center center no-repeat #000}.layui-layer-photos .layui-layer-content{overflow:hidden;text-align:center}.layui-layer-photos .layui-layer-phimg img{position:relative;width:100%;display:inline-block;*display:inline;*zoom:1;vertical-align:top}.layui-layer-imgbar,.layui-layer-imguide{display:none}.layui-layer-imgnext,.layui-layer-imgprev{position:absolute;top:50%;width:27px;_width:44px;height:44px;margin-top:-22px;outline:0;blr:expression(this.onFocus=this.blur())}.layui-layer-imgprev{left:10px;background-position:-5px -5px;_background-position:-70px -5px}.layui-layer-imgprev:hover{background-position:-33px -5px;_background-position:-120px -5px}.layui-layer-imgnext{right:10px;_right:8px;background-position:-5px -50px;_background-position:-70px -50px}.layui-layer-imgnext:hover{background-position:-33px -50px;_background-position:-120px -50px}.layui-layer-imgbar{position:absolute;left:0;bottom:0;width:100%;height:32px;line-height:32px;background-color:rgba(0,0,0,.8);background-color:#000\9;filter:Alpha(opacity=80);color:#fff;overflow:hidden;font-size:0}.layui-layer-imgtit *{display:inline-block;*display:inline;*zoom:1;vertical-align:top;font-size:12px}.layui-layer-imgtit a{max-width:65%;overflow:hidden;color:#fff}.layui-layer-imgtit a:hover{color:#fff;text-decoration:underline}.layui-layer-imgtit em{padding-left:10px;font-style:normal} -------------------------------------------------------------------------------- /src/main/webapp/js/shiro.demo.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @author sojson.com 4 | * @ps 你可以当作是一个闭包 | 封装的Demo 5 | */ 6 | (function(o,w){ 7 | if(!w.so)w.so = {}; 8 | return (function(so){ 9 | so.$1 = !0,//true 10 | so.$0 = !1;//false 11 | /** 12 | * 全选 13 | */ 14 | so.checkBoxInit = function(prentCheckbox,childCheckbox){ 15 | childCheckbox = o(childCheckbox),prentCheckbox = o(prentCheckbox); 16 | //先取消全选。 17 | //childCheckbox.add(prentCheckbox).attr('checked',!1); 18 | //全选 19 | prentCheckbox.on('click',function(){ 20 | childCheckbox.attr('checked',this.checked); 21 | }); 22 | //子选择 23 | childCheckbox.on('click',function(){ 24 | prentCheckbox.attr('checked',childCheckbox.length === childCheckbox.end().find(':checked').not(prentCheckbox).length); 25 | }); 26 | }, 27 | //初始化 28 | so.init = function(fn){ 29 | o(function(){fn()}); 30 | } 31 | so.id = function(id){ 32 | return o('#' + id); 33 | } 34 | so.default = function(){} 35 | 36 | })(so); 37 | })($,window); 38 | -------------------------------------------------------------------------------- /src/main/webapp/js/user.login.js: -------------------------------------------------------------------------------- 1 | 2 | //换种方式获取,之前的方式在不同的环境下,有问题 3 | var baseUrl = $("script[baseUrl]").attr('baseUrl'); 4 | /**退出*/ 5 | function logout(){ 6 | var load = layer.load(); 7 | $.getJSON(baseUrl + '/u/logout.shtml',{},function(result){ 8 | layer.close(load); 9 | if(result && result.status == 200){ 10 | $(".qqlogin").html('').next('ul').remove(); 11 | layer.msg('退出成功'); 12 | window.location.reload(true); 13 | return !1; 14 | }else{ 15 | layer.msg('退出失败,重试!'); 16 | } 17 | }); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/webapp/user/index.shtml: -------------------------------------------------------------------------------- 1 | --------------------------------------------------------------------------------