From 00214b1bf03c85b58a449bad1c54c7d0c603368c Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Thu, 20 Jun 2019 10:19:44 +0800 Subject: [PATCH 1/6] ignore ignore --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..31d7fc6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target/ +.settings/org.eclipse.m2e.core.prefs +.settings/org.eclipse.jdt.core.prefs +.settings/org.eclipse.core.resources.prefs +.project +.classpath From b2773d6bafecda2b4773090fcfaf6ee8ed16e21e Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Thu, 20 Jun 2019 10:21:30 +0800 Subject: [PATCH 2/6] fixbug fixbug --- .../com/haiyu/manager/dto/AdminRoleDTO.java | 66 +++++++++++++++ .../com/haiyu/manager/dto/AdminUserDTO.java | 2 +- .../com/haiyu/manager/dto/PermissionDTO.java | 82 +++++++++++++++++++ 3 files changed, 149 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/haiyu/manager/dto/AdminRoleDTO.java b/src/main/java/com/haiyu/manager/dto/AdminRoleDTO.java index 5357d90..a70acb9 100644 --- a/src/main/java/com/haiyu/manager/dto/AdminRoleDTO.java +++ b/src/main/java/com/haiyu/manager/dto/AdminRoleDTO.java @@ -45,4 +45,70 @@ public class AdminRoleDTO { 0:无效 */ private Integer roleStatus; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public String getRoleDesc() { + return roleDesc; + } + + public void setRoleDesc(String roleDesc) { + this.roleDesc = roleDesc; + } + + public String getPermissionIds() { + return permissionIds; + } + + public void setPermissionIds(String permissionIds) { + this.permissionIds = permissionIds; + } + + public String getPermissions() { + return permissions; + } + + public void setPermissions(String permissions) { + this.permissions = permissions; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public Integer getRoleStatus() { + return roleStatus; + } + + public void setRoleStatus(Integer roleStatus) { + this.roleStatus = roleStatus; + } + + } diff --git a/src/main/java/com/haiyu/manager/dto/AdminUserDTO.java b/src/main/java/com/haiyu/manager/dto/AdminUserDTO.java index aee052a..0be9e0b 100644 --- a/src/main/java/com/haiyu/manager/dto/AdminUserDTO.java +++ b/src/main/java/com/haiyu/manager/dto/AdminUserDTO.java @@ -1,6 +1,6 @@ package com.haiyu.manager.dto; -;import lombok.Data; +import lombok.Data; /** * @Title: AdminUserDTO diff --git a/src/main/java/com/haiyu/manager/dto/PermissionDTO.java b/src/main/java/com/haiyu/manager/dto/PermissionDTO.java index 980ed91..2ae83a8 100644 --- a/src/main/java/com/haiyu/manager/dto/PermissionDTO.java +++ b/src/main/java/com/haiyu/manager/dto/PermissionDTO.java @@ -33,4 +33,86 @@ public class PermissionDTO { private Integer delFlag; List childrens; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPid() { + return pid; + } + + public void setPid(Integer pid) { + this.pid = pid; + } + + public String getPname() { + return pname; + } + + public void setPname(String pname) { + this.pname = pname; + } + + public String getDescpt() { + return descpt; + } + + public void setDescpt(String descpt) { + this.descpt = descpt; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public Integer getDelFlag() { + return delFlag; + } + + public void setDelFlag(Integer delFlag) { + this.delFlag = delFlag; + } + + public List getChildrens() { + return childrens; + } + + public void setChildrens(List childrens) { + this.childrens = childrens; + } + + } From 5d3e0783c94056bf35ea3a63858734981ae79bae Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Thu, 20 Jun 2019 10:59:03 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E8=87=AA=E5=B7=B1=E6=94=B9=E4=BA=86?= =?UTF-8?q?=E4=BA=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 自己改了些 --- .../com/haiyu/manager/config/ShiroConfig.java | 289 ------------------ .../system/PermissionController.java | 3 +- .../com/haiyu/manager/filter/FormFilter.java | 45 --- .../manager/filter/KickoutSessionFilter.java | 205 ------------- .../com/haiyu/manager/pojo/BaseAdminRole.java | 9 + .../service/impl/AdminRoleServiceImpl.java | 8 +- .../java/com/haiyu/manager/shiro/MyRealm.java | 114 ------- src/main/resources/application.yml | 6 +- 8 files changed, 20 insertions(+), 659 deletions(-) delete mode 100644 src/main/java/com/haiyu/manager/config/ShiroConfig.java delete mode 100644 src/main/java/com/haiyu/manager/filter/FormFilter.java delete mode 100644 src/main/java/com/haiyu/manager/filter/KickoutSessionFilter.java delete mode 100644 src/main/java/com/haiyu/manager/shiro/MyRealm.java diff --git a/src/main/java/com/haiyu/manager/config/ShiroConfig.java b/src/main/java/com/haiyu/manager/config/ShiroConfig.java deleted file mode 100644 index 351c3fa..0000000 --- a/src/main/java/com/haiyu/manager/config/ShiroConfig.java +++ /dev/null @@ -1,289 +0,0 @@ -package com.haiyu.manager.config; - - -import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; -import com.haiyu.manager.filter.KickoutSessionFilter; -import com.haiyu.manager.shiro.MyRealm; -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; -import org.apache.shiro.authc.credential.HashedCredentialsMatcher; -import org.apache.shiro.cache.ehcache.EhCacheManager; -import org.apache.shiro.io.ResourceUtils; -import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; -import org.apache.shiro.spring.web.ShiroFilterFactoryBean; -import org.apache.shiro.web.mgt.CookieRememberMeManager; -import org.apache.shiro.web.mgt.DefaultWebSecurityManager; -import org.apache.shiro.web.servlet.SimpleCookie; -import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import javax.servlet.Filter; -import java.io.IOException; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * @Title: ShiroConfig - * @Description: shiro配置 - * @author: youqing - * @version: 1.0 - * @date: 2018/9/11 10:33 - */ -@Configuration -public class ShiroConfig { - - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * ShiroFilterFactoryBean 处理拦截资源文件过滤器 - *
1,配置shiro安全管理器接口securityManage; - *
2,shiro 连接约束配置filterChainDefinitions; - */ - @Bean - public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) { - ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); - - logger.info("Shiro拦截器工厂类注入开始"); - - // 配置shiro安全管理器 SecurityManager - bean.setSecurityManager(securityManager); - //添加kickout认证 - HashMap hashMap=new HashMap(); - hashMap.put("kickout",kickoutSessionFilter()); - bean.setFilters(hashMap); - - // 指定要求登录时的链接 - bean.setLoginUrl("/login"); - // 登录成功后要跳转的链接 - bean.setSuccessUrl("/home"); - // 未授权时跳转的界面; - bean.setUnauthorizedUrl("/error"); - - // filterChainDefinitions拦截器map必须用:LinkedHashMap,因为它必须保证有序 - Map filterMap = new LinkedHashMap<>(); - // 放行登录页面 - filterMap.put("/login", "anon"); - // 配置退出过滤器,具体的退出代码Shiro已经实现 - filterMap.put("/logout", "logout"); - //配置记住我或认证通过可以访问的地址 - filterMap.put("/user/userList", "user"); - filterMap.put("/", "user"); - - // 配置不会被拦截的链接 从上向下顺序判断 - filterMap.put("/css/*", "anon"); - filterMap.put("/js/*", "anon"); - filterMap.put("/js/*/*", "anon"); - filterMap.put("/js/*/*/*", "anon"); - filterMap.put("/images/*/**", "anon"); - filterMap.put("/layui/*", "anon"); - filterMap.put("/layui/*/**", "anon"); - filterMap.put("/treegrid/*", "anon"); - filterMap.put("/treegrid/*/*", "anon"); - filterMap.put("/fragments/*", "anon"); - filterMap.put("/layout", "anon"); - filterMap.put("/home", "anon"); - filterMap.put("/user/login", "anon"); - - // - filterMap.put("/**", "kickout,authc"); - filterMap.put("/*/*", "authc"); - filterMap.put("/*/*/*", "authc"); - filterMap.put("/*/*/*/**", "authc"); - - // 添加 shiro 过滤器 - bean.setFilterChainDefinitionMap(filterMap); - logger.info("Shiro拦截器工厂类注入成功"); - - return bean; - } - - /** - * shiro安全管理器设置realm认证和ehcache缓存管理 - */ - @Bean - public DefaultWebSecurityManager securityManager() { - DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); - - // 关联realm - manager.setRealm(shiroRealm()); - //注入ehcache缓存管理器; - manager.setCacheManager(ehCacheManager()); - //注入session管理器; - manager.setSessionManager(sessionManager()); - //注入Cookie记住我管理器 - manager.setRememberMeManager(rememberMeManager()); - - return manager; - } - - /** - * 3.创建身份认证 Realm - */ - @Bean - public MyRealm shiroRealm() { - MyRealm realm = new MyRealm(); - realm.setCredentialsMatcher(hashedCredentialsMatcher()); - return realm; - } - - - /** - * 凭证匹配器 (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 - * 所以我们需要修改下doGetAuthenticationInfo中的代码,更改密码生成规则和校验的逻辑一致即可; ) - * - * @return - */ - @Bean - public HashedCredentialsMatcher hashedCredentialsMatcher() { - HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); - hashedCredentialsMatcher.setHashAlgorithmName("MD5");// 散列算法:这里使用MD5算法; - hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于 // md5(md5("")); - hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true); - return hashedCredentialsMatcher; - } - - - /** - * RememberMe 的功能 - */ - // 创建 Cookie - @Bean - public SimpleCookie remeberMeCookie() { - logger.info("记住我,设置cookie过期时间!"); - SimpleCookie cookie = new SimpleCookie("rememberMe"); - // //记住我cookie生效时间30天 ,单位秒 [10天] - cookie.setMaxAge(864000); - // 设置只读模型 - //cookie.setHttpOnly(true); - return cookie; - } - - /** - * 配置cookie记住我管理器 - * @return - */ - @Bean - public CookieRememberMeManager rememberMeManager(){ - logger.debug("配置cookie记住我管理器!"); - CookieRememberMeManager cookieRememberMeManager=new CookieRememberMeManager(); - cookieRememberMeManager.setCookie(remeberMeCookie()); - return cookieRememberMeManager; - } - - - /** - * - * 功能描述: 同一个用户多设备登录限制 - * - * @param: - * @return: - * @auther: youqing - * @date: 2018/11/23 10:22 - */ - public KickoutSessionFilter kickoutSessionFilter(){ - KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter(); - //使用cacheManager获取相应的cache来缓存用户登录的会话;用于保存用户—会话之间的关系的; - //这里我们还是用之前shiro使用的ehcache实现的cacheManager()缓存管理 - //也可以重新另写一个,重新配置缓存时间之类的自定义缓存属性 - kickoutSessionFilter.setCacheManager(ehCacheManager()); - //用于根据会话ID,获取会话进行踢出操作的; - kickoutSessionFilter.setSessionManager(sessionManager()); - //是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序。 - kickoutSessionFilter.setKickoutAfter(false); - //同一个用户最大的会话数,默认1;比如2的意思是同一个用户允许最多同时两个人登录; - kickoutSessionFilter.setMaxSession(1); - //被踢出后重定向到的地址; - kickoutSessionFilter.setKickoutUrl("/login?kickout=1"); - return kickoutSessionFilter; - } - - - /** - * ehcache缓存管理器;shiro整合ehcache: - * 通过安全管理器:securityManager - * 单例的cache防止热部署重启失败 - * @return EhCacheManager - */ - @Bean - public EhCacheManager ehCacheManager(){ - logger.debug("shiro整合ehcache缓存:ShiroConfiguration.getEhCacheManager()"); - EhCacheManager ehcache = new EhCacheManager(); - CacheManager cacheManager = CacheManager.getCacheManager("shiro"); - if(cacheManager == null){ - try { - cacheManager = CacheManager.create(ResourceUtils.getInputStreamForPath("classpath:config/ehcache.xml")); - } catch (CacheException | IOException e) { - e.printStackTrace(); - } - } - ehcache.setCacheManager(cacheManager); - return ehcache; - } - - /** - * - * 功能描述: sessionManager添加session缓存操作DAO - * - * @param: - * @return: - * @auther: youqing - * @date: 2018/11/23 10:31 - */ - @Bean - public DefaultWebSessionManager sessionManager() { - DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); - - sessionManager.setSessionDAO(enterCacheSessionDAO()); - sessionManager.setSessionIdCookie(sessionIdCookie()); - return sessionManager; - } - - /** - * EnterpriseCacheSessionDAO shiro sessionDao层的实现; - * 提供了缓存功能的会话维护,默认情况下使用MapCache实现,内部使用ConcurrentHashMap保存缓存的会话。 - */ - @Bean - public EnterpriseCacheSessionDAO enterCacheSessionDAO() { - EnterpriseCacheSessionDAO enterCacheSessionDAO = new EnterpriseCacheSessionDAO(); - enterCacheSessionDAO.setActiveSessionsCacheName("shiro-activeSessionCache"); - return enterCacheSessionDAO; - } - - - /** - * - * 功能描述: 自定义cookie中session名称等配置 - * - * @param: - * @return: - * @auther: youqing - * @date: 2018/11/23 10:34 - */ - @Bean - public SimpleCookie sessionIdCookie() { - //DefaultSecurityManager - SimpleCookie simpleCookie = new SimpleCookie(); - //sessionManager.setCacheManager(ehCacheManager()); - //如果在Cookie中设置了"HttpOnly"属性,那么通过程序(JS脚本、Applet等)将无法读取到Cookie信息,这样能有效的防止XSS攻击。 - simpleCookie.setHttpOnly(true); - simpleCookie.setName("SHRIOSESSIONID"); - //单位秒 - simpleCookie.setMaxAge(86400); - return simpleCookie; - } - - - - /** - * 整合 Shiro 标签 - */ - @Bean - public ShiroDialect shiroDialect() { - return new ShiroDialect(); - } -} diff --git a/src/main/java/com/haiyu/manager/controller/system/PermissionController.java b/src/main/java/com/haiyu/manager/controller/system/PermissionController.java index 317aeca..003325f 100644 --- a/src/main/java/com/haiyu/manager/controller/system/PermissionController.java +++ b/src/main/java/com/haiyu/manager/controller/system/PermissionController.java @@ -161,7 +161,8 @@ public Map del(@RequestParam("id") Long id) { public Map getUserPerms(){ logger.info("获取登陆用户的权限"); Map data = new HashMap<>(); - BaseAdminUser user = (BaseAdminUser) SecurityUtils.getSubject().getPrincipal(); + BaseAdminUser user = new BaseAdminUser(); + user.setRoleId(1); data = permissionService.getUserPerms(user); return data; } diff --git a/src/main/java/com/haiyu/manager/filter/FormFilter.java b/src/main/java/com/haiyu/manager/filter/FormFilter.java deleted file mode 100644 index e15c4c8..0000000 --- a/src/main/java/com/haiyu/manager/filter/FormFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.haiyu.manager.filter; - -import com.haiyu.manager.pojo.BaseAdminUser; -import org.apache.shiro.session.Session; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -/** - * @Title: FormFilter - * @Description: - * @author: youqing - * @version: 1.0 - * @date: 2018/9/11 10:55 - */ -public class FormFilter extends FormAuthenticationFilter { - - @Override - protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { - Subject subject = getSubject(request, response); - - // 如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true - // 证明是没登陆直接通过记住我功能进来的 - if (!subject.isAuthenticated() && subject.isRemembered()) { - - // 获取session看看是不是空的 - Session session = subject.getSession(true); - - // 查看session属性当前是否是空的 - if (session.getAttribute("userName") == null) { - // 如果是空的才初始化 - BaseAdminUser user = (BaseAdminUser)subject.getPrincipal(); - //存入用户数据 - session.setAttribute("userName", user.getSysUserName()); - } - } - - // 这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() - // 让它同时也兼容remember这种情况 - return subject.isAuthenticated() || subject.isRemembered(); - } - -} diff --git a/src/main/java/com/haiyu/manager/filter/KickoutSessionFilter.java b/src/main/java/com/haiyu/manager/filter/KickoutSessionFilter.java deleted file mode 100644 index bd8cf22..0000000 --- a/src/main/java/com/haiyu/manager/filter/KickoutSessionFilter.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.haiyu.manager.filter; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.haiyu.manager.pojo.BaseAdminUser; -import com.haiyu.manager.response.ResponseResult; -import com.haiyu.manager.common.IStatusMessage; -import com.haiyu.manager.common.utils.ShiroFilterUtils; -import org.apache.shiro.cache.Cache; -import org.apache.shiro.cache.CacheManager; -import org.apache.shiro.session.Session; -import org.apache.shiro.session.mgt.DefaultSessionKey; -import org.apache.shiro.session.mgt.SessionManager; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.web.filter.AccessControlFilter; -import org.apache.shiro.web.util.WebUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Serializable; -import java.util.ArrayDeque; -import java.util.Deque; - - -/** - * @Title: KickouSessionFilter - * @Description: 进行用户访问控制 - * @author: youqing - * @version: 1.0 - * @date: 2018/11/23 9:37 - */ -public class KickoutSessionFilter extends AccessControlFilter { - - private static final Logger logger = LoggerFactory.getLogger(KickoutSessionFilter.class); - - private final static ObjectMapper objectMapper = new ObjectMapper(); - - private String kickoutUrl; // 踢出后到的地址 - private boolean kickoutAfter = false; // 踢出之前登录的/之后登录的用户 默认false踢出之前登录的用户 - private int maxSession = 1; // 同一个帐号最大会话数 默认1 - private SessionManager sessionManager; - private Cache> cache; - - public void setKickoutUrl(String kickoutUrl) { - this.kickoutUrl = kickoutUrl; - } - - public void setKickoutAfter(boolean kickoutAfter) { - this.kickoutAfter = kickoutAfter; - } - - public void setMaxSession(int maxSession) { - this.maxSession = maxSession; - } - - public void setSessionManager(SessionManager sessionManager) { - this.sessionManager = sessionManager; - } - - // 设置Cache的key的前缀 - public void setCacheManager(CacheManager cacheManager) { - //必须和ehcache缓存配置中的缓存name一致 - this.cache = cacheManager.getCache("shiro-activeSessionCache"); - } - - - - @Override - protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { - return false; - } - - @Override - protected boolean onAccessDenied(ServletRequest request, ServletResponse response)throws Exception { - Subject subject = getSubject(request,response); - // 没有登录授权 且没有记住我 - if(!subject.isAuthenticated() && !subject.isRemembered()){ - // 如果没有登录,直接进行之后的流程 - return true; - } - // 获得用户请求的URI - HttpServletRequest req=(HttpServletRequest) request; - String path = req.getRequestURI(); - logger.info("===当前请求的uri:" + path); - - if(path.equals("/login")){ - return true; - } - Session session = subject.getSession(); - logger.info("session时间设置:" + String.valueOf(session.getTimeout())); - - - try{ - // 当前用户 - BaseAdminUser user = (BaseAdminUser) subject.getPrincipal(); - String username = user.getSysUserName(); - logger.info("===当前用户username:" + username); - Serializable sessionId = session.getId(); - logger.info("===当前用户sessionId:" + sessionId); - // 读取缓存用户 没有就存入 - Deque deque = cache.get(username); - logger.debug("===当前deque:" + deque); - if (deque == null) { - // 初始化队列 - deque = new ArrayDeque(); - } - // 如果队列里没有此sessionId,且用户没有被踢出;放入队列 - if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) { - // 将sessionId存入队列 - deque.push(sessionId); - // 将用户的sessionId队列缓存 - cache.put(username, deque); - } - // 如果队列里的sessionId数超出最大会话数,开始踢人 - while (deque.size() > maxSession) { - logger.debug("===deque队列长度:" + deque.size()); - Serializable kickoutSessionId = null; - // 是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户; - if (kickoutAfter) { // 如果踢出后者 - kickoutSessionId = deque.removeFirst(); - } else { // 否则踢出前者 - kickoutSessionId = deque.removeLast(); - } - // 踢出后再更新下缓存队列 - cache.put(username, deque); - try{ - // 获取被踢出的sessionId的session对象 - Session kickoutSession = sessionManager - .getSession(new DefaultSessionKey(kickoutSessionId)); - if (kickoutSession != null) { - // 设置会话的kickout属性表示踢出了 - kickoutSession.setAttribute("kickout", true); - } - }catch (Exception e){ - - } - } - - // 如果被踢出了,(前者或后者)直接退出,重定向到踢出后的地址 - if ((Boolean) session.getAttribute("kickout") != null - && (Boolean) session.getAttribute("kickout") == true){ - // 会话被踢出了 - try { - // 退出登录 - subject.logout(); - } catch (Exception e) { // ignore - } - saveRequest(request); - logger.debug("===踢出后用户重定向的路径kickoutUrl:" + kickoutUrl); - return isAjaxResponse(request,response); - } - return true; - }catch (Exception e){ - logger.error("控制用户在线数量【KickoutSessionFilter.onAccessDenied】异常!", e); - return isAjaxResponse(request,response); - } - } - - - public static void out(ServletResponse response, ResponseResult result){ - PrintWriter out = null; - try { - response.setCharacterEncoding("UTF-8");//设置编码 - response.setContentType("application/json");//设置返回类型 - out = response.getWriter(); - out.println(objectMapper.writeValueAsString(result));//输出 - logger.info("用户在线数量限制【KickoutSessionFilter.out】响应json信息成功"); - } catch (Exception e) { - logger.error("用户在线数量限制【KickoutSessionFilter.out】响应json信息出错", e); - }finally{ - if(null != out){ - out.flush(); - out.close(); - } - } - } - - private boolean isAjaxResponse(ServletRequest request, - ServletResponse response) throws IOException { - // ajax请求 - /** - * 判断是否已经踢出 - * 1.如果是Ajax 访问,那么给予json返回值提示。 - * 2.如果是普通请求,直接跳转到登录页 - */ - //判断是不是Ajax请求 - ResponseResult responseResult = new ResponseResult(); - if (ShiroFilterUtils.isAjax(request) ) { - logger.info(getClass().getName()+ "当前用户已经在其他地方登录,并且是Ajax请求!"); - responseResult.setCode(IStatusMessage.SystemStatus.MANY_LOGINS.getCode()); - responseResult.setMessage("您已在别处登录,请您修改密码或重新登录"); - out(response, responseResult); - }else{ - // 重定向 - WebUtils.issueRedirect(request, response, kickoutUrl); - } - return false; - } - - -} diff --git a/src/main/java/com/haiyu/manager/pojo/BaseAdminRole.java b/src/main/java/com/haiyu/manager/pojo/BaseAdminRole.java index 5c4f5b2..329cafd 100644 --- a/src/main/java/com/haiyu/manager/pojo/BaseAdminRole.java +++ b/src/main/java/com/haiyu/manager/pojo/BaseAdminRole.java @@ -176,4 +176,13 @@ public Integer getRoleStatus() { public void setRoleStatus(Integer roleStatus) { this.roleStatus = roleStatus; } + + @Override + public String toString() { + return "BaseAdminRole [id=" + id + ", roleName=" + roleName + ", roleDesc=" + roleDesc + ", permissions=" + + permissions + ", createTime=" + createTime + ", updateTime=" + updateTime + ", roleStatus=" + + roleStatus + "]"; + } + + } \ No newline at end of file diff --git a/src/main/java/com/haiyu/manager/service/impl/AdminRoleServiceImpl.java b/src/main/java/com/haiyu/manager/service/impl/AdminRoleServiceImpl.java index 287cd22..5011a9a 100644 --- a/src/main/java/com/haiyu/manager/service/impl/AdminRoleServiceImpl.java +++ b/src/main/java/com/haiyu/manager/service/impl/AdminRoleServiceImpl.java @@ -47,6 +47,8 @@ public PageDataResult getRoleList(Integer pageNum,Integer pageSize) { List roleList = new ArrayList <>(); for(BaseAdminRole r:roles){ + + logger.info(r.toString()); AdminRoleDTO roleDTO = new AdminRoleDTO(); String permissions = r.getPermissions(); @@ -58,8 +60,10 @@ public PageDataResult getRoleList(Integer pageNum,Integer pageSize) { List p = new ArrayList <>(); for(String id: ids){ BaseAdminPermission baseAdminPermission = this.baseAdminPermission.selectByPrimaryKey(id); - String name = baseAdminPermission.getName(); - p.add(name); + if(baseAdminPermission != null){ + String name = baseAdminPermission.getName(); + p.add(name); + } } roleDTO.setPermissions(p.toString()); } diff --git a/src/main/java/com/haiyu/manager/shiro/MyRealm.java b/src/main/java/com/haiyu/manager/shiro/MyRealm.java deleted file mode 100644 index a26ffc8..0000000 --- a/src/main/java/com/haiyu/manager/shiro/MyRealm.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.haiyu.manager.shiro; - -import com.haiyu.manager.pojo.BaseAdminUser; -import com.haiyu.manager.service.AdminPermissionService; -import com.haiyu.manager.service.AdminRoleService; -import com.haiyu.manager.service.AdminUserService; -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.apache.shiro.authc.*; -import org.apache.shiro.authz.AuthorizationInfo; -import org.apache.shiro.authz.SimpleAuthorizationInfo; -import org.apache.shiro.realm.AuthorizingRealm; -import org.apache.shiro.subject.PrincipalCollection; -import org.apache.shiro.util.ByteSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * @Title: MyRealm - * @Description: - * @author: youqing - * @version: 1.0 - * @date: 2018/11/22 15:53 - */ -public class MyRealm extends AuthorizingRealm { - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - - @Autowired - private AdminUserService userService; - - @Autowired - private AdminRoleService roleService; - - @Autowired - private AdminPermissionService permissionService; - - - /** - * - * 功能描述: 授权 - * - * @param: - * @return: - * @auther: youqing - * @date: 2018/9/11 10:30 - */ - @Override - protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { - //授权 - logger.info("授予角色和权限"); - // 添加权限 和 角色信息 - SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); - // 获取当前登陆用户 - /*Subject subject = SecurityUtils.getSubject(); - BaseAdminUser user = (BaseAdminUser) subject.getPrincipal(); - System.out.println(user); - if (user.getSysUserName().equals("admin")) { - // 超级管理员,添加所有角色、添加所有权限 - authorizationInfo.addRole("*"); - authorizationInfo.addStringPermission("*"); - } else { - // 普通用户,查询用户的角色,根据角色查询权限 - Integer roleId = user.getRoleId(); - BaseAdminRole role = roleService.findRoleById(roleId); - if (null != role ) { - String permissions = role.getPermissions(); - String[] ids = permissions.split(","); - for (String id : ids) { - authorizationInfo.addRole(role.getRoleName()); - // 角色对应的权限数据 - BaseAdminPermission perm = permissionService.getById(id); - if (null != perm ) { - // 授权角色下所有权限 - authorizationInfo.addStringPermission(perm.getUrl()); - } - } - } - }*/ - return authorizationInfo; - } - - - /** - * - * 功能描述: 认证 - * - * @param: - * @return: - * @auther: youqing - * @date: 2018/9/11 10:32 - */ - @Override - protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { - //UsernamePasswordToken用于存放提交的登录信息 - UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; - logger.info("用户登录认证:验证当前Subject时获取到token为:" + ReflectionToStringBuilder - .toString(token, ToStringStyle.MULTI_LINE_STYLE)); - String username = token.getUsername(); - // 调用数据层 - BaseAdminUser sysUser = userService.findByUserName(username); - logger.debug("用户登录认证!用户信息user:" + sysUser); - if (sysUser == null) { - // 用户不存在 - return null; - } - // 返回密码 - return new SimpleAuthenticationInfo(sysUser, sysUser.getSysUserPwd(), ByteSource.Util.bytes(username), getName()); - - } - -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 6c2a2a5..3f33886 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -7,9 +7,9 @@ spring: name: haiyu datasource: druid: - url: jdbc:mysql://localhost:3306/haiyu?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 - username: root - password: root + url: jdbc:mysql://10.11.0.156:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 + username: bpms + password: bpms@123 initial-size: 1 min-idle: 1 max-active: 20 From 6a6c19e32bcdb2a0ea5ab9a0420345fd353f347f Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Mon, 24 Jun 2019 10:40:18 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 + .../com/haiyu/manager/ManagerApplication.java | 3 + .../common/utils/AuthorizationUtils.java | 104 ++++ .../manager/controller/IndexController.java | 26 +- .../controller/system/ScheduledTask.java | 52 ++ .../controller/system/keyController.java | 131 +++++ .../com/haiyu/manager/dao/BaseUserMapper.java | 26 + .../java/com/haiyu/manager/dto/BaseUser.java | 100 ++++ .../manager/service/BaseUserService.java | 25 + .../service/impl/BaseUserServiceImpl.java | 95 ++++ src/main/resources/application.yml | 4 +- src/main/resources/mapper/BaseUserMapper.xml | 73 +++ .../resources/static/js/jquery/jquery.tmpl.js | 486 ++++++++++++++++++ src/main/resources/templates/activation.html | 91 ++++ src/main/resources/templates/docum.html | 202 ++++++++ src/main/resources/templates/layout.html | 1 + src/main/resources/templates/register.html | 82 +++ 17 files changed, 1491 insertions(+), 15 deletions(-) create mode 100644 src/main/java/com/haiyu/manager/common/utils/AuthorizationUtils.java create mode 100644 src/main/java/com/haiyu/manager/controller/system/ScheduledTask.java create mode 100644 src/main/java/com/haiyu/manager/controller/system/keyController.java create mode 100644 src/main/java/com/haiyu/manager/dao/BaseUserMapper.java create mode 100644 src/main/java/com/haiyu/manager/dto/BaseUser.java create mode 100644 src/main/java/com/haiyu/manager/service/BaseUserService.java create mode 100644 src/main/java/com/haiyu/manager/service/impl/BaseUserServiceImpl.java create mode 100644 src/main/resources/mapper/BaseUserMapper.xml create mode 100644 src/main/resources/static/js/jquery/jquery.tmpl.js create mode 100644 src/main/resources/templates/activation.html create mode 100644 src/main/resources/templates/docum.html create mode 100644 src/main/resources/templates/register.html diff --git a/pom.xml b/pom.xml index a1dd7cf..4c97c8e 100644 --- a/pom.xml +++ b/pom.xml @@ -106,6 +106,11 @@ 1.18.4 + + org.springframework.security + spring-security-core + 3.2.8.RELEASE + diff --git a/src/main/java/com/haiyu/manager/ManagerApplication.java b/src/main/java/com/haiyu/manager/ManagerApplication.java index bc6af4b..ac8ef57 100644 --- a/src/main/java/com/haiyu/manager/ManagerApplication.java +++ b/src/main/java/com/haiyu/manager/ManagerApplication.java @@ -2,10 +2,13 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan(basePackages = "com.haiyu.manager.dao") +@EnableScheduling public class ManagerApplication { public static void main(String[] args) { diff --git a/src/main/java/com/haiyu/manager/common/utils/AuthorizationUtils.java b/src/main/java/com/haiyu/manager/common/utils/AuthorizationUtils.java new file mode 100644 index 0000000..e2bf113 --- /dev/null +++ b/src/main/java/com/haiyu/manager/common/utils/AuthorizationUtils.java @@ -0,0 +1,104 @@ +package com.haiyu.manager.common.utils; + +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +import org.springframework.security.authentication.encoding.Md5PasswordEncoder; + +public class AuthorizationUtils { + + private static final int SPLITLENGTH = 4; + + public static void main(String args[]) throws Exception { + String code = getMachineCode(); + String authCode = getAuthCode(code,"2213"); + System.out.println("机器码:" + code); + System.out.println("注册码:" + authCode); + } + + public static String getMachineCode() { + Set result = new HashSet<>(); + result.add(getCpuMachineCode()); + String code = new Md5PasswordEncoder().encodePassword(result.toString(), "1234"); + return getSplitString(code, "-", 4); + + } + + /** + * 根据机器码和私盐得到授权码 + * @param machineCode + * @return + */ + public static String getAuthCode(String machineCode,String salt) { + String newCode = "(yunshouhuxxx@gmail.com)[" + machineCode.toUpperCase() + "](xxx应用级产品开发平台)"; + String code1 = new Md5PasswordEncoder().encodePassword(newCode, salt).toUpperCase() ; + return getSplitString(code1); + } + + private static String getSplitString(String str) { + return getSplitString(str, "-", SPLITLENGTH); + } + + private static String getSplitString(String str, String split, int length) { + int len = str.length(); + StringBuilder temp = new StringBuilder(); + for (int i = 0; i < len; i++) { + if (i % length == 0 && i > 0) { + temp.append(split); + } + temp.append(str.charAt(i)); + } + String[] attrs = temp.toString().split(split); + StringBuilder finalMachineCode = new StringBuilder(); + for (String attr : attrs) { + if (attr.length() == length) { + finalMachineCode.append(attr).append(split); + } + } + return finalMachineCode.toString().substring(0, finalMachineCode.toString().length() - 1); + } + + + /** + * 获取CPU机器码 + * @return + */ + @SuppressWarnings("resource") + private static String getCpuMachineCode() { + String serial = ""; + try { + Process process = Runtime.getRuntime().exec( + new String[]{"wmic", "cpu", "get", "ProcessorId"}); + process.getOutputStream().close(); + Scanner sc = new Scanner(process.getInputStream()); + sc.next(); + serial = sc.next(); + } catch (Exception e) { + e.printStackTrace(); + } + return serial; + } + + /** + * 随机得到6位数用来作为用户私盐 + * @return + */ + public static String getSalt(){ + Double d = new Double((Math.random()*9+1)*100000); + int i = d.intValue(); + return i+""; + } + + /** + * 根据手机号和私盐得到注册码 + * @param phone + * @param salt + * @return + */ + public static String getRegisterCode(String phone, String salt) { + String code = new Md5PasswordEncoder().encodePassword(phone, salt).toUpperCase() ; + return getSplitString(code, "-", 4); + } + +} diff --git a/src/main/java/com/haiyu/manager/controller/IndexController.java b/src/main/java/com/haiyu/manager/controller/IndexController.java index 2b2d45e..1f51470 100644 --- a/src/main/java/com/haiyu/manager/controller/IndexController.java +++ b/src/main/java/com/haiyu/manager/controller/IndexController.java @@ -19,24 +19,24 @@ public class IndexController { private Logger logger = LoggerFactory.getLogger(this.getClass()); - @RequestMapping("login") - public String tologin(){ - logger.info("定向登陆页"); - return "login"; - } - @RequestMapping("home") public String home(){ logger.info("定向主页"); return "home"; } - - @RequestMapping("logout") - public String logout(){ - logger.info("退出系统"); - Subject subject = SecurityUtils.getSubject(); - subject.logout(); // shiro底层删除session的会话信息 - return "redirect:login"; + + @RequestMapping("docum") + public String docum(){ + return "docum"; } + @RequestMapping("register") + public String register(){ + return "register"; + } + + @RequestMapping("activation") + public String activation(){ + return "activation"; + } } diff --git a/src/main/java/com/haiyu/manager/controller/system/ScheduledTask.java b/src/main/java/com/haiyu/manager/controller/system/ScheduledTask.java new file mode 100644 index 0000000..e814643 --- /dev/null +++ b/src/main/java/com/haiyu/manager/controller/system/ScheduledTask.java @@ -0,0 +1,52 @@ +package com.haiyu.manager.controller.system; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import com.haiyu.manager.common.utils.AuthorizationUtils; +import com.haiyu.manager.common.utils.DateUtils; +import com.haiyu.manager.dto.BaseUser; +import com.haiyu.manager.service.BaseUserService; + +@Component +public class ScheduledTask { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + @Autowired + BaseUserService baseUserService; + + @Scheduled(cron="0/30 * * * * ?") + public void reportCurrentTime() { + + String date = DateUtils.getCurrentDate(); + logger.info("执行了定时器:" + date); + String machineCode = AuthorizationUtils.getMachineCode(); + + BaseUser qbaseUser = new BaseUser(); + qbaseUser.setMachineCode(machineCode); + List baseUsers = baseUserService.getBaseUsers(qbaseUser); + + BaseUser baseUser = baseUsers.get(0); + String authCode = AuthorizationUtils.getAuthCode(machineCode, baseUser.getSalt()); + if (authCode.equals(baseUser.getAuthCode())) { + baseUser.setYunSuccess(baseUser.getYunSuccess() + 1); + baseUser.setYunSuccessDate(new Timestamp(new Date().getTime())); + logger.info(baseUser.getPhone() + " success " + date); + } else { + baseUser.setYunFail(baseUser.getYunFail() + 1); + baseUser.setYunFailDate(new Timestamp(new Date().getTime())); + logger.info(baseUser.getPhone()); + logger.info(baseUser.getPhone() + " fail " + date); + } + + baseUserService.updateBaseUser(baseUser); + + } +} diff --git a/src/main/java/com/haiyu/manager/controller/system/keyController.java b/src/main/java/com/haiyu/manager/controller/system/keyController.java new file mode 100644 index 0000000..ab3f293 --- /dev/null +++ b/src/main/java/com/haiyu/manager/controller/system/keyController.java @@ -0,0 +1,131 @@ +package com.haiyu.manager.controller.system; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.shiro.util.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import com.haiyu.manager.common.utils.AuthorizationUtils; +import com.haiyu.manager.dto.BaseUser; +import com.haiyu.manager.service.BaseUserService; + +@Controller +@RequestMapping("key") +public class keyController { + + @Autowired + BaseUserService baseUserService; + + /** + * 获取注册码 + * + * @return + */ + @RequestMapping("/nextKey") + @ResponseBody + public Map toPage(@RequestParam("phone") String phone) { + Map retMap = new HashMap<>(); + + String salt = AuthorizationUtils.getSalt(); + String regCode = AuthorizationUtils.getRegisterCode(phone, salt); + + BaseUser baseUser = new BaseUser(); + baseUser.setSalt(salt); + baseUser.setPhone(phone); + baseUser.setActivateFlag("0"); + baseUser.setRegisterCode(regCode); + baseUser.setRegisterDate(new Timestamp(new Date().getTime())); + retMap = baseUserService.addBaseUser(baseUser); + retMap.put("regCode", regCode); + return retMap; + } + + /** + * 激活注册码 + * + * @return + */ + @RequestMapping("/useKey") + @ResponseBody + public Map useKey(HttpServletRequest request) { + + Map retMap = new HashMap<>(); + String phone = request.getParameter("phone"); + String regCode = request.getParameter("regCode"); + BaseUser baseUser = new BaseUser(); + baseUser.setPhone(phone); + baseUser.setRegisterCode(regCode); + List baseUsers = baseUserService.getBaseUsers(baseUser); + if (CollectionUtils.isEmpty(baseUsers) || baseUsers.size() > 1) { + retMap.put("code", 2); + retMap.put("msg", "验证失败"); + return retMap; + } + + String machineCode = AuthorizationUtils.getMachineCode(); + baseUser = baseUsers.get(0); + baseUser.setActivateFlag("1"); + baseUser.setActivateDate(new Timestamp(new Date().getTime())); + baseUser.setMachineCode(machineCode); + baseUser.setAuthCode(AuthorizationUtils.getAuthCode(machineCode, baseUser.getSalt())); + + return baseUserService.updateBaseUser(baseUser); + + } + + /** + * 云检测注册码 + * + * @return + */ + @RequestMapping("/yunCheck") + @ResponseBody + public Map yunCheck(HttpServletRequest request) { + + Map retMap = new HashMap<>(); + BaseUser qbaseUser = new BaseUser(); + + String machineCode = request.getParameter("machineCode"); + qbaseUser.setMachineCode(machineCode); + List baseUsers = baseUserService.getBaseUsers(qbaseUser); + if (CollectionUtils.isEmpty(baseUsers)) { + retMap.put("code", 2); + retMap.put("msg", "验证失败"); + return retMap; + } + + BaseUser baseUser = baseUsers.get(0); + String authCode = AuthorizationUtils.getAuthCode(machineCode, baseUser.getSalt()); + if (authCode.equals(baseUser.getAuthCode())) { + baseUser.setYunSuccess(baseUser.getYunSuccess() + 1); + baseUser.setYunSuccessDate(new Timestamp(new Date().getTime())); + } else { + baseUser.setYunFail(baseUser.getYunFail() + 1); + baseUser.setYunFailDate(new Timestamp(new Date().getTime())); + } + + return baseUserService.updateBaseUser(baseUser); + } + + + /** + * 展示列表数据 + * + * @return + */ + @RequestMapping("/list") + @ResponseBody + public List list(HttpServletRequest request) { + BaseUser baseUser = new BaseUser(); + return baseUserService.getBaseUsers(baseUser); + } +} diff --git a/src/main/java/com/haiyu/manager/dao/BaseUserMapper.java b/src/main/java/com/haiyu/manager/dao/BaseUserMapper.java new file mode 100644 index 0000000..6e4f926 --- /dev/null +++ b/src/main/java/com/haiyu/manager/dao/BaseUserMapper.java @@ -0,0 +1,26 @@ +package com.haiyu.manager.dao; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; + +import com.haiyu.manager.dto.BaseUser; +import com.haiyu.manager.response.PageDataResult; + +public interface BaseUserMapper { + + PageDataResult getBaseUserList(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize); + + List getBaseUsers(BaseUser baseUser); + + BaseUser findBaseUserById(@Param("id") Integer id); + + int updateBaseUser(BaseUser role); + + int delBaseUser(@Param("id") Integer id, @Param("status") Integer status); + + int recoverBaseUser(@Param("id") Integer id, @Param("status") Integer status); + + int addBaseUser(BaseUser role); + +} diff --git a/src/main/java/com/haiyu/manager/dto/BaseUser.java b/src/main/java/com/haiyu/manager/dto/BaseUser.java new file mode 100644 index 0000000..a5d5c08 --- /dev/null +++ b/src/main/java/com/haiyu/manager/dto/BaseUser.java @@ -0,0 +1,100 @@ +package com.haiyu.manager.dto; + +import java.sql.Timestamp; + +public class BaseUser { + + private int id; + private String phone; + private String salt; + private String registerCode; + private String machineCode; + private String authCode; + private Timestamp registerDate; + private String activateFlag; + private Timestamp activateDate; + private int yunSuccess; + private int yunFail; + private Timestamp yunSuccessDate; + private Timestamp yunFailDate; + + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + public String getSalt() { + return salt; + } + public void setSalt(String salt) { + this.salt = salt; + } + public String getRegisterCode() { + return registerCode; + } + public void setRegisterCode(String registerCode) { + this.registerCode = registerCode; + } + public String getMachineCode() { + return machineCode; + } + public void setMachineCode(String machineCode) { + this.machineCode = machineCode; + } + public String getAuthCode() { + return authCode; + } + public void setAuthCode(String authCode) { + this.authCode = authCode; + } + public Timestamp getRegisterDate() { + return registerDate; + } + public void setRegisterDate(Timestamp registerDate) { + this.registerDate = registerDate; + } + public Timestamp getActivateDate() { + return activateDate; + } + public void setActivateDate(Timestamp activateDate) { + this.activateDate = activateDate; + } + public Timestamp getYunSuccessDate() { + return yunSuccessDate; + } + public void setYunSuccessDate(Timestamp yunSuccessDate) { + this.yunSuccessDate = yunSuccessDate; + } + public Timestamp getYunFailDate() { + return yunFailDate; + } + public void setYunFailDate(Timestamp yunFailDate) { + this.yunFailDate = yunFailDate; + } + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getActivateFlag() { + return activateFlag; + } + public void setActivateFlag(String activateFlag) { + this.activateFlag = activateFlag; + } + public int getYunSuccess() { + return yunSuccess; + } + public void setYunSuccess(int yunSuccess) { + this.yunSuccess = yunSuccess; + } + public int getYunFail() { + return yunFail; + } + public void setYunFail(int yunFail) { + this.yunFail = yunFail; + } + +} diff --git a/src/main/java/com/haiyu/manager/service/BaseUserService.java b/src/main/java/com/haiyu/manager/service/BaseUserService.java new file mode 100644 index 0000000..d0a60cd --- /dev/null +++ b/src/main/java/com/haiyu/manager/service/BaseUserService.java @@ -0,0 +1,25 @@ +package com.haiyu.manager.service; + +import java.util.List; +import java.util.Map; + +import com.haiyu.manager.dto.BaseUser; +import com.haiyu.manager.response.PageDataResult; + +public interface BaseUserService { + + PageDataResult getBaseUserList(Integer pageNum, Integer pageSize); + + List getBaseUsers(BaseUser baseUser); + + BaseUser findBaseUserById(Integer id); + + Map updateBaseUser(BaseUser baseUser); + + Map delBaseUser(Integer id, Integer status); + + Map recoverBaseUser(Integer id, Integer status); + + Map addBaseUser(BaseUser baseUser); + +} diff --git a/src/main/java/com/haiyu/manager/service/impl/BaseUserServiceImpl.java b/src/main/java/com/haiyu/manager/service/impl/BaseUserServiceImpl.java new file mode 100644 index 0000000..127a7bc --- /dev/null +++ b/src/main/java/com/haiyu/manager/service/impl/BaseUserServiceImpl.java @@ -0,0 +1,95 @@ +package com.haiyu.manager.service.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.haiyu.manager.dao.BaseUserMapper; +import com.haiyu.manager.dto.BaseUser; +import com.haiyu.manager.response.PageDataResult; +import com.haiyu.manager.service.BaseUserService; + +@Service +public class BaseUserServiceImpl implements BaseUserService { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private BaseUserMapper baseUserMapper; + + @Override + public PageDataResult getBaseUserList(Integer pageNum, Integer pageSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getBaseUsers(BaseUser baseUser) { + return baseUserMapper.getBaseUsers(baseUser); + } + + @Override + public BaseUser findBaseUserById(Integer id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map updateBaseUser(BaseUser baseUser) { + Map retMap = new HashMap(); + try { + int result = baseUserMapper.updateBaseUser(baseUser); + if (result == 0) { + retMap.put("code", 0); + retMap.put("msg", "操作失败"); + logger.error("updateBaseUser失败"); + return retMap; + } + retMap.put("code", 1); + retMap.put("msg", "操作成功"); + } catch (Exception e) { + e.printStackTrace(); + logger.error("updateBaseUser异常!", e); + } + return retMap; + } + + @Override + public Map delBaseUser(Integer id, Integer status) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map recoverBaseUser(Integer id, Integer status) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map addBaseUser(BaseUser baseUser) { + + Map retMap = new HashMap(); + try { + int result = baseUserMapper.addBaseUser(baseUser); + if (result == 0) { + retMap.put("code", 0); + retMap.put("msg", "新增用户失败"); + logger.error("新增用户失败"); + return retMap; + } + retMap.put("code", 1); + retMap.put("msg", "新增用户成功"); + } catch (Exception e) { + e.printStackTrace(); + logger.error("添加用户!异常!", e); + } + return retMap; + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3f33886..ed4452a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,10 +1,10 @@ server: - port: 8102 + port: 9102 spring: application: - name: haiyu + name: yunsen datasource: druid: url: jdbc:mysql://10.11.0.156:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 diff --git a/src/main/resources/mapper/BaseUserMapper.xml b/src/main/resources/mapper/BaseUserMapper.xml new file mode 100644 index 0000000..b0eb27c --- /dev/null +++ b/src/main/resources/mapper/BaseUserMapper.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + id,phone,salt,register_code,machine_code,auth_code,register_date,activate_flag,activate_date,yun_success,yun_fail,yun_success_date,yun_fail_date + + + + + + UPDATE base_user + + + phone = #{phone}, + salt = #{salt}, + register_code = #{registerCode}, + machine_code = #{machineCode}, + auth_code = #{authCode}, + register_date = #{registerDate}, + activate_flag = #{activateFlag}, + activate_date = #{activateDate}, + yun_success = #{yunSuccess}, + yun_fail = #{yunFail}, + yun_success_date = #{yunSuccessDate}, + yun_fail_date = #{yunFailDate} + + id = #{id} + + + + INSERT INTO `base_user` (`id`, `phone`, `salt`, `register_code`, `machine_code`, `auth_code`, `register_date`, `activate_flag`, `activate_date`, `yun_success`, `yun_fail`, `yun_success_date`, `yun_fail_date`) VALUES + (#{id}, #{phone}, #{salt}, #{registerCode}, #{machineCode}, #{authCode}, #{registerDate}, #{activateFlag}, #{activateDate}, #{yunSuccess}, #{yunFail}, #{yunSuccessDate}, #{yunFailDate}); + + + \ No newline at end of file diff --git a/src/main/resources/static/js/jquery/jquery.tmpl.js b/src/main/resources/static/js/jquery/jquery.tmpl.js new file mode 100644 index 0000000..0fa579f --- /dev/null +++ b/src/main/resources/static/js/jquery/jquery.tmpl.js @@ -0,0 +1,486 @@ +/* + * jQuery Templating Plugin + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + */ +(function( jQuery, undefined ){ + var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, + newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; + + function newTmplItem( options, parentItem, fn, data ) { + // Returns a template item data structure for a new rendered instance of a template (a 'template item'). + // The content field is a hierarchical array of strings and nested items (to be + // removed and replaced by nodes field of dom elements, once inserted in DOM). + var newItem = { + data: data || (parentItem ? parentItem.data : {}), + _wrap: parentItem ? parentItem._wrap : null, + tmpl: null, + parent: parentItem || null, + nodes: [], + calls: tiCalls, + nest: tiNest, + wrap: tiWrap, + html: tiHtml, + update: tiUpdate + }; + if ( options ) { + jQuery.extend( newItem, options, { nodes: [], parent: parentItem } ); + } + if ( fn ) { + // Build the hierarchical content to be used during insertion into DOM + newItem.tmpl = fn; + newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); + newItem.key = ++itemKey; + // Keep track of new template item, until it is stored as jQuery Data on DOM element + (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; + } + return newItem; + } + + // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). + jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" + }, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, + parent = this.length === 1 && this[0].parentNode; + + appendToTmplItems = newTmplItems || {}; + if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { + insert[ original ]( this[0] ); + ret = this; + } else { + for ( i = 0, l = insert.length; i < l; i++ ) { + cloneIndex = i; + elems = (i > 0 ? this.clone(true) : this).get(); + jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); + ret = ret.concat( elems ); + } + cloneIndex = 0; + ret = this.pushStack( ret, name, insert.selector ); + } + tmplItems = appendToTmplItems; + appendToTmplItems = null; + jQuery.tmpl.complete( tmplItems ); + return ret; + }; + }); + + jQuery.fn.extend({ + // Use first wrapped element as template markup. + // Return wrapped set of template items, obtained by rendering template against data. + tmpl: function( data, options, parentItem ) { + return jQuery.tmpl( this[0], data, options, parentItem ); + }, + + // Find which rendered template item the first wrapped DOM element belongs to + tmplItem: function() { + return jQuery.tmplItem( this[0] ); + }, + + // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. + template: function( name ) { + return jQuery.template( name, this[0] ); + }, + + domManip: function( args, table, callback, options ) { + // This appears to be a bug in the appendTo, etc. implementation + // it should be doing .call() instead of .apply(). See #6227 + if ( args[0] && args[0].nodeType ) { + var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem; + while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {} + if ( argsLength > 1 ) { + dmArgs[0] = [jQuery.makeArray( args )]; + } + if ( tmplItem && cloneIndex ) { + dmArgs[2] = function( fragClone ) { + // Handler called by oldManip when rendered template has been inserted into DOM. + jQuery.tmpl.afterManip( this, fragClone, callback ); + }; + } + oldManip.apply( this, dmArgs ); + } else { + oldManip.apply( this, arguments ); + } + cloneIndex = 0; + if ( !appendToTmplItems ) { + jQuery.tmpl.complete( newTmplItems ); + } + return this; + } + }); + + jQuery.extend({ + // Return wrapped set of template items, obtained by rendering template against data. + tmpl: function( tmpl, data, options, parentItem ) { + var ret, topLevel = !parentItem; + if ( topLevel ) { + // This is a top-level tmpl call (not from a nested template using {{tmpl}}) + parentItem = topTmplItem; + tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); + wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level + } else if ( !tmpl ) { + // The template item is already associated with DOM - this is a refresh. + // Re-evaluate rendered template for the parentItem + tmpl = parentItem.tmpl; + newTmplItems[parentItem.key] = parentItem; + parentItem.nodes = []; + if ( parentItem.wrapped ) { + updateWrapped( parentItem, parentItem.wrapped ); + } + // Rebuild, without creating a new template item + return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); + } + if ( !tmpl ) { + return []; // Could throw... + } + if ( typeof data === "function" ) { + data = data.call( parentItem || {} ); + } + if ( options && options.wrapped ) { + updateWrapped( options, options.wrapped ); + } + ret = jQuery.isArray( data ) ? + jQuery.map( data, function( dataItem ) { + return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; + }) : + [ newTmplItem( options, parentItem, tmpl, data ) ]; + return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; + }, + + // Return rendered template item for an element. + tmplItem: function( elem ) { + var tmplItem; + if ( elem instanceof jQuery ) { + elem = elem[0]; + } + while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} + return tmplItem || topTmplItem; + }, + + // Set: + // Use $.template( name, tmpl ) to cache a named template, + // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. + // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. + + // Get: + // Use $.template( name ) to access a cached template. + // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) + // will return the compiled template, without adding a name reference. + // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent + // to $.template( null, templateString ) + template: function( name, tmpl ) { + if (tmpl) { + // Compile template and associate with name + if ( typeof tmpl === "string" ) { + // This is an HTML string being passed directly in. + tmpl = buildTmplFn( tmpl ) + } else if ( tmpl instanceof jQuery ) { + tmpl = tmpl[0] || {}; + } + if ( tmpl.nodeType ) { + // If this is a template block, use cached copy, or generate tmpl function and cache. + tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); + } + return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; + } + // Return named compiled template + return name ? (typeof name !== "string" ? jQuery.template( null, name ): + (jQuery.template[name] || + // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) + jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; + }, + + encode: function( text ) { + // Do HTML encoding replacing < > & and ' and " by corresponding entities. + return ("" + text).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'"); + } + }); + + jQuery.extend( jQuery.tmpl, { + tag: { + "tmpl": { + _default: { $2: "null" }, + open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" + // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) + // This means that {{tmpl foo}} treats foo as a template (which IS a function). + // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. + }, + "wrap": { + _default: { $2: "null" }, + open: "$item.calls(_,$1,$2);_=[];", + close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" + }, + "each": { + _default: { $2: "$index, $value" }, + open: "if($notnull_1){$.each($1a,function($2){with(this){", + close: "}});}" + }, + "if": { + open: "if(($notnull_1) && $1a){", + close: "}" + }, + "else": { + _default: { $1: "true" }, + open: "}else if(($notnull_1) && $1a){" + }, + "html": { + // Unecoded expression evaluation. + open: "if($notnull_1){_.push($1a);}" + }, + "=": { + // Encoded expression evaluation. Abbreviated form is ${}. + _default: { $1: "$data" }, + open: "if($notnull_1){_.push($.encode($1a));}" + }, + "!": { + // Comment tag. Skipped by parser + open: "" + } + }, + + // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events + complete: function( items ) { + newTmplItems = {}; + }, + + // Call this from code which overrides domManip, or equivalent + // Manage cloning/storing template items etc. + afterManip: function afterManip( elem, fragClone, callback ) { + // Provides cloned fragment ready for fixup prior to and after insertion into DOM + var content = fragClone.nodeType === 11 ? + jQuery.makeArray(fragClone.childNodes) : + fragClone.nodeType === 1 ? [fragClone] : []; + + // Return fragment to original caller (e.g. append) for DOM insertion + callback.call( elem, fragClone ); + + // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. + storeTmplItems( content ); + cloneIndex++; + } + }); + + //========================== Private helper functions, used by code above ========================== + + function build( tmplItem, nested, content ) { + // Convert hierarchical content into flat string array + // and finally return array of fragments ready for DOM insertion + var frag, ret = content ? jQuery.map( content, function( item ) { + return (typeof item === "string") ? + // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. + (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : + // This is a child template item. Build nested template. + build( item, tmplItem, item._ctnt ); + }) : + // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. + tmplItem; + if ( nested ) { + return ret; + } + + // top-level template + ret = ret.join(""); + + // Support templates which have initial or final text nodes, or consist only of text + // Also support HTML entities within the HTML markup. + ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { + frag = jQuery( middle ).get(); + + storeTmplItems( frag ); + if ( before ) { + frag = unencode( before ).concat(frag); + } + if ( after ) { + frag = frag.concat(unencode( after )); + } + }); + return frag ? frag : unencode( ret ); + } + + function unencode( text ) { + // Use createElement, since createTextNode will not render HTML entities correctly + var el = document.createElement( "div" ); + el.innerHTML = text; + return jQuery.makeArray(el.childNodes); + } + + // Generate a reusable function that will serve to render a template against data + function buildTmplFn( markup ) { + return new Function("jQuery","$item", + "var $=jQuery,call,_=[],$data=$item.data;" + + + // Introduce the data as local variables using with(){} + "with($data){_.push('" + + + // Convert the template into pure JavaScript + jQuery.trim(markup) + .replace( /([\\'])/g, "\\$1" ) + .replace( /[\r\t\n]/g, " " ) + .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) + .replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g, + function( all, slash, type, fnargs, target, parens, args ) { + var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; + if ( !tag ) { + throw "Template command not found: " + type; + } + def = tag._default || []; + if ( parens && !/\w$/.test(target)) { + target += parens; + parens = ""; + } + if ( target ) { + target = unescape( target ); + args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); + // Support for target being things like a.toLowerCase(); + // In that case don't call with template item as 'this' pointer. Just evaluate... + expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target; + exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; + } else { + exprAutoFnDetect = expr = def.$1 || "null"; + } + fnargs = unescape( fnargs ); + return "');" + + tag[ slash ? "close" : "open" ] + .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) + .split( "$1a" ).join( exprAutoFnDetect ) + .split( "$1" ).join( expr ) + .split( "$2" ).join( fnargs ? + fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) { + params = params ? ("," + params + ")") : (parens ? ")" : ""); + return params ? ("(" + name + ").call($item" + params) : all; + }) + : (def.$2||"") + ) + + "_.push('"; + }) + + "');}return _;" + ); + } + function updateWrapped( options, wrapped ) { + // Build the wrapped content. + options._wrap = build( options, true, + // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. + jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] + ).join(""); + } + + function unescape( args ) { + return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; + } + function outerHtml( elem ) { + var div = document.createElement("div"); + div.appendChild( elem.cloneNode(true) ); + return div.innerHTML; + } + + // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. + function storeTmplItems( content ) { + var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; + for ( i = 0, l = content.length; i < l; i++ ) { + if ( (elem = content[i]).nodeType !== 1 ) { + continue; + } + elems = elem.getElementsByTagName("*"); + for ( m = elems.length - 1; m >= 0; m-- ) { + processItemKey( elems[m] ); + } + processItemKey( elem ); + } + function processItemKey( el ) { + var pntKey, pntNode = el, pntItem, tmplItem, key; + // Ensure that each rendered template inserted into the DOM has its own template item, + if ( (key = el.getAttribute( tmplItmAtt ))) { + while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } + if ( pntKey !== key ) { + // The next ancestor with a _tmplitem expando is on a different key than this one. + // So this is a top-level element within this template item + // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment. + pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0; + if ( !(tmplItem = newTmplItems[key]) ) { + // The item is for wrapped content, and was copied from the temporary parent wrappedItem. + tmplItem = wrappedItems[key]; + tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true ); + tmplItem.key = ++itemKey; + newTmplItems[itemKey] = tmplItem; + } + if ( cloneIndex ) { + cloneTmplItem( key ); + } + } + el.removeAttribute( tmplItmAtt ); + } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { + // This was a rendered element, cloned during append or appendTo etc. + // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. + cloneTmplItem( tmplItem.key ); + newTmplItems[tmplItem.key] = tmplItem; + pntNode = jQuery.data( el.parentNode, "tmplItem" ); + pntNode = pntNode ? pntNode.key : 0; + } + if ( tmplItem ) { + pntItem = tmplItem; + // Find the template item of the parent element. + // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) + while ( pntItem && pntItem.key != pntNode ) { + // Add this element as a top-level node for this rendered template item, as well as for any + // ancestor items between this item and the item of its parent element + pntItem.nodes.push( el ); + pntItem = pntItem.parent; + } + // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... + delete tmplItem._ctnt; + delete tmplItem._wrap; + // Store template item as jQuery data on the element + jQuery.data( el, "tmplItem", tmplItem ); + } + function cloneTmplItem( key ) { + key = key + keySuffix; + tmplItem = newClonedItems[key] = + (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true )); + } + } + } + + //---- Helper functions for template item ---- + + function tiCalls( content, tmpl, data, options ) { + if ( !content ) { + return stack.pop(); + } + stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); + } + + function tiNest( tmpl, data, options ) { + // nested template, using {{tmpl}} tag + return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); + } + + function tiWrap( call, wrapped ) { + // nested template, using {{wrap}} tag + var options = call.options || {}; + options.wrapped = wrapped; + // Apply the template, which may incorporate wrapped content, + return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); + } + + function tiHtml( filter, textOnly ) { + var wrapped = this._wrap; + return jQuery.map( + jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), + function(e) { + return textOnly ? + e.innerText || e.textContent : + e.outerHTML || outerHtml(e); + }); + } + + function tiUpdate() { + var coll = this.nodes; + jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); + jQuery( coll ).remove(); + } +})( jQuery ); \ No newline at end of file diff --git a/src/main/resources/templates/activation.html b/src/main/resources/templates/activation.html new file mode 100644 index 0000000..636a377 --- /dev/null +++ b/src/main/resources/templates/activation.html @@ -0,0 +1,91 @@ + + + + + 密钥激活 + + + + + + + + +
+ +
+
+
+
+ 密钥激活 +
+ +
+ +
+
+ +
+ +
+
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+
+
+
+ + + + + \ No newline at end of file diff --git a/src/main/resources/templates/docum.html b/src/main/resources/templates/docum.html new file mode 100644 index 0000000..31b6935 --- /dev/null +++ b/src/main/resources/templates/docum.html @@ -0,0 +1,202 @@ + + + + +法诉关联分析 + + + + + + + + +
+法诉关联查询示例 +
+
+
+
+
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + +
客户姓名:
出生日期:
性别:
+
+ +
+ + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/layout.html b/src/main/resources/templates/layout.html index 056d911..2852e50 100644 --- a/src/main/resources/templates/layout.html +++ b/src/main/resources/templates/layout.html @@ -11,6 +11,7 @@ 后台管理系统 + diff --git a/src/main/resources/templates/register.html b/src/main/resources/templates/register.html new file mode 100644 index 0000000..a635bbb --- /dev/null +++ b/src/main/resources/templates/register.html @@ -0,0 +1,82 @@ + + + + + 密钥申请 + + + + + + + + +
+ +
+
+
+
+ 密钥申请 +
+ +
+ +
+
+ +
+ +
+
+
+ +
+
+ +
+
+
+
+ +
+ +
+
+
+
+ + + + + \ No newline at end of file From c2e0e3de1c602beb5a87dc47fd5ca9be0ec9e85a Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Mon, 24 Jun 2019 15:02:29 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 提交代码 --- .../controller/system/keyController.java | 9 ++- src/main/resources/static/js/head.js | 4 +- .../resources/static/js/sysUser/userList.js | 65 +++++++++++++++++-- src/main/resources/templates/docum.html | 54 ++++++++++----- .../resources/templates/fragments/head.html | 12 ++-- src/main/resources/templates/home.html | 3 +- .../resources/templates/user/userManage.html | 28 -------- 7 files changed, 110 insertions(+), 65 deletions(-) diff --git a/src/main/java/com/haiyu/manager/controller/system/keyController.java b/src/main/java/com/haiyu/manager/controller/system/keyController.java index ab3f293..bae10f5 100644 --- a/src/main/java/com/haiyu/manager/controller/system/keyController.java +++ b/src/main/java/com/haiyu/manager/controller/system/keyController.java @@ -124,8 +124,13 @@ public Map yunCheck(HttpServletRequest request) { */ @RequestMapping("/list") @ResponseBody - public List list(HttpServletRequest request) { + public Map list(HttpServletRequest request) { + Map ret = new HashMap<>(); BaseUser baseUser = new BaseUser(); - return baseUserService.getBaseUsers(baseUser); + List userList = baseUserService.getBaseUsers(baseUser); + ret.put("code", 200); + ret.put("list", userList); + ret.put("totals", userList.size()); + return ret; } } diff --git a/src/main/resources/static/js/head.js b/src/main/resources/static/js/head.js index e251765..949f743 100644 --- a/src/main/resources/static/js/head.js +++ b/src/main/resources/static/js/head.js @@ -1,6 +1,6 @@ /** * 菜单 - * */ + * *//* //获取路径uri var pathUri=window.location.href; $(function(){ @@ -75,4 +75,4 @@ function updateUsePwd(){ area: ['450px'], content:$('#pwdDiv') }); -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/src/main/resources/static/js/sysUser/userList.js b/src/main/resources/static/js/sysUser/userList.js index 2b8d9e3..39e5b5f 100644 --- a/src/main/resources/static/js/sysUser/userList.js +++ b/src/main/resources/static/js/sysUser/userList.js @@ -10,7 +10,7 @@ $(function() { tableIns=table.render({ elem: '#uesrList', - url:'/user/getUserList', + url:'/key/list', method: 'post', //默认:get请求 cellMinWidth: 80, page: true, @@ -26,12 +26,36 @@ $(function() { }, cols: [[ {type:'numbers'} - ,{field:'sysUserName', title:'用户名',align:'center'} - ,{field:'roleName', title:'角色类型',align:'center'} - ,{field:'userPhone', title:'手机号',align:'center'} - ,{field:'regTime', title: '注册时间',align:'center'} - ,{field:'userStatus', title: '是否有效',align:'center'} - ,{title:'操作',align:'center', toolbar:'#optBar'} + ,{field:'phone', title:'手机号',align:'center'} + ,{field:'registerCode', title:'注册码',align:'center'} + ,{field:'machineCode', title:'机器码',align:'center'} + ,{field:'authCode', title: '云校验编码',align:'center'} + ,{field:'registerDate', title: '注册时间',align:'center',templet: function (d) { + if(!d.registerDate){ + return "-"; + } + return Format(d.registerDate,"yyyy-MM-dd hh:mm:ss"); + }} + ,{field:'activateDate', title: '激活时间',align:'center',templet: function (d) { + if(!d.activateDate){ + return "-"; + } + return Format(d.activateDate,"yyyy-MM-dd hh:mm:ss"); + }} + ,{field:'yunSuccess', title: '云检测成功次数',align:'center'} + ,{field:'yunSuccessDate', title: '云检测成功时间',align:'center',templet: function (d) { + if(!d.yunSuccessDate){ + return "-"; + } + return Format(d.yunSuccessDate,"yyyy-MM-dd hh:mm:ss"); + }} + ,{field:'yunFail', title: '云检测失败次数',align:'center'} + ,{field:'yunFailDate', title: '云检测失败时间',align:'center',templet: function (d) { + if(!d.yunFailDate){ + return "-"; + } + return Format(d.yunFailDate,"yyyy-MM-dd hh:mm:ss"); + }} ]], done: function(res, curr, count){ //如果是异步请求数据方式,res即为你接口返回的信息。 @@ -96,6 +120,33 @@ $(function() { }); }); +function Format(datetime,fmt) { + console.log(parseInt(datetime)); + if (parseInt(datetime)==datetime) { + if (datetime.length==10) { + datetime=parseInt(datetime)*1000; + } else if(datetime.length==13) { + datetime=parseInt(datetime); + } + } + datetime=new Date(datetime); + var o = { + "M+" : datetime.getMonth()+1, //月份 + "d+" : datetime.getDate(), //日 + "h+" : datetime.getHours(), //小时 + "m+" : datetime.getMinutes(), //分 + "s+" : datetime.getSeconds(), //秒 + "q+" : Math.floor((datetime.getMonth()+3)/3), //季度 + "S" : datetime.getMilliseconds() //毫秒 + }; + if(/(y+)/.test(fmt)) + fmt=fmt.replace(RegExp.$1, (datetime.getFullYear()+"").substr(4 - RegExp.$1.length)); + for(var k in o) + if(new RegExp("("+ k +")").test(fmt)) + fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); + return fmt; + } + //提交表单 function formSubmit(obj){ $.ajax({ diff --git a/src/main/resources/templates/docum.html b/src/main/resources/templates/docum.html index 31b6935..9a06dc3 100644 --- a/src/main/resources/templates/docum.html +++ b/src/main/resources/templates/docum.html @@ -40,22 +40,19 @@
- +
- +
- +
@@ -72,20 +69,16 @@ 客户姓名: - + 出生日期: - + 性别: - + -
@@ -185,15 +178,40 @@ var form = layui.form, layer = layui.layer; //监听提交 form.on('submit(demo1)', function(data) { - layer.alert(JSON.stringify(data.field), { - title : '最终的提交信息' - }) - return false; + var paramArr = []; + paramArr[0]=data.field.applyNo|'ZZS0420190425011'; + paramArr[1]=data.field.userName|'刘金荣'; + paramArr[2]=data.field.idCardNum|'410104196205305524'; + console.log(paramArr.join(",")); + + $.ajax({ + url:"http://10.96.2.139:5000/test", + type:'post', + data:paramArr.join(","), + beforeSend:function () { + this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] }); + }, + success:function(data){ + + if(data){ + + }else{ + layer.alert("查询数据为空"); + } + }, + complete: function () { + layer.close(this.layerIndex); + }, + }); + + return false; + }); }); $(function () { - var users = [{ ID: 'think8848', Name: 'Joseph Chan', Ctrl: {x:"x"} }, { ID: 'aCloud', Name: 'Mary Cheung', Ctrl: {x:''}}]; + // var users = [{ ID: '', Name: 'Joseph Chan', Ctrl: {x:"x"} }, { ID: 'aCloud', Name: 'Mary Cheung', Ctrl: {x:''}}]; + var users = [{ Ctrl: {x:""}}]; $('#coredata').tmpl(users).appendTo('.layui-container'); }); diff --git a/src/main/resources/templates/fragments/head.html b/src/main/resources/templates/fragments/head.html index e901c7b..4638dc2 100644 --- a/src/main/resources/templates/fragments/head.html +++ b/src/main/resources/templates/fragments/head.html @@ -27,15 +27,15 @@
    - -
  • + +
  • -->
diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html index 15b4aaa..1ebe81f 100644 --- a/src/main/resources/templates/home.html +++ b/src/main/resources/templates/home.html @@ -15,8 +15,7 @@
  -

,欢迎登录 - 海韵后台管理系统

+

欢迎登录后台管理系统

diff --git a/src/main/resources/templates/user/userManage.html b/src/main/resources/templates/user/userManage.html index b2595be..0fd5cd9 100644 --- a/src/main/resources/templates/user/userManage.html +++ b/src/main/resources/templates/user/userManage.html @@ -9,38 +9,10 @@
-
-
- -
- -
- -
- -
-
-
-
- -
- -
-
-
-
- -
- - -
-
-

- From b996d95d0fc5612683141d8a977a2b343efe256d Mon Sep 17 00:00:00 2001 From: qinyunsen Date: Fri, 28 Jun 2019 15:52:50 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 12 + .../haiyu/manager/common/IStatusMessage.java | 2 +- .../manager/common/utils/HttpClientUtil.java | 317 ++++++++++++++++++ .../manager/controller/IndexController.java | 32 +- src/main/resources/templates/docum.html | 155 +++++---- src/test/java/com/haiyu/EightQueen.java | 89 +++++ src/test/java/com/haiyu/HttpCliectTest.java | 18 + 7 files changed, 563 insertions(+), 62 deletions(-) create mode 100644 src/main/java/com/haiyu/manager/common/utils/HttpClientUtil.java create mode 100644 src/test/java/com/haiyu/EightQueen.java create mode 100644 src/test/java/com/haiyu/HttpCliectTest.java diff --git a/pom.xml b/pom.xml index 4c97c8e..5181677 100644 --- a/pom.xml +++ b/pom.xml @@ -111,6 +111,18 @@ spring-security-core 3.2.8.RELEASE + + + org.apache.httpcomponents + httpclient + 4.4.1 + + + + com.alibaba + fastjson + 1.2.56 + diff --git a/src/main/java/com/haiyu/manager/common/IStatusMessage.java b/src/main/java/com/haiyu/manager/common/IStatusMessage.java index de9bc8f..2cc4b4f 100644 --- a/src/main/java/com/haiyu/manager/common/IStatusMessage.java +++ b/src/main/java/com/haiyu/manager/common/IStatusMessage.java @@ -17,7 +17,7 @@ public enum SystemStatus implements IStatusMessage{ SUCCESS("200","SUCCESS"), //请求成功 ERROR("404","ERROR"), //请求失败 - PARAM_ERROR("1002","PARAM_ERROR"), //请求参数有误 + PARAM_ERROR("1002","参数错误"), //请求参数有误 SUCCESS_MATCH("1003","SUCCESS_MATCH"), //表示成功匹配 NO_LOGIN("1100","NO_LOGIN"), //未登录 MANY_LOGINS("1101","MANY_LOGINS"), //多用户在线(踢出用户) diff --git a/src/main/java/com/haiyu/manager/common/utils/HttpClientUtil.java b/src/main/java/com/haiyu/manager/common/utils/HttpClientUtil.java new file mode 100644 index 0000000..d71a4aa --- /dev/null +++ b/src/main/java/com/haiyu/manager/common/utils/HttpClientUtil.java @@ -0,0 +1,317 @@ +package com.haiyu.manager.common.utils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.CoreConnectionPNames; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * HttpClientUtil 工具类 + * @author Frez + * + */ +public class HttpClientUtil { + + // 设置默认超时时间为60s + public static final int DEFAULT_TIME_OUT = 60 * 1000; + // 默认字符集UTF-8 + public static final String DEFAULT_CHARSET = "UTF-8"; + + private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class); + + /** + * http请求 + * @param url + * @param paramMap + * @param charset + * @param isPost + * @return + */ + public static String sendHttpRequest(String url, Map paramMap, String charset, boolean isPost) { + return sendHttpRequest(url, paramMap, charset, isPost, DEFAULT_TIME_OUT); + } + + /** + * http请求 + * @param url + * @param paramMap + * @param charset + * @param isPost + * @param timeout + * @return + */ + public static String sendHttpRequest(String url, Map paramMap, String charset, boolean isPost, int timeout) { + if (isPost) { + return httpPost(url, paramMap, charset, timeout); + } + return httpGet(url, paramMap, charset, timeout); + } + + public static String httpPost(String url, Map params){ + return httpPost(url, params, DEFAULT_CHARSET, DEFAULT_TIME_OUT); + } + /** + * post请求 + * @param url + * @param params + * @param charset + * @param timeout + * @return + */ + public static String httpPost(String url, Map params, String charset, int timeout) { + log.debug("http request url: {} charset: {} timeout: {} request str: ", url, charset, timeout, params); + // 参数组装 + List pairs = new ArrayList(); + for (Entry entry : params.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + pairs.add(new BasicNameValuePair(key, formatStr(value))); + } + HttpEntity httpEntity; + try { + httpEntity = new UrlEncodedFormEntity(pairs); + return httpPost(url, charset, timeout, httpEntity); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return null; + } + + /** + * post请求 + * @param url + * @param jsonStr + * @return + */ + public static String httpPost(String url, String jsonStr){ + return httpPost(url, jsonStr, "UTF-8", DEFAULT_TIME_OUT); + } + + /** + * 上面那个默认content-type=ContentType.TEXT_PLAIN, 满足不了要求 + * 这个content-type=application/json + * @param url + * @param jsonStr + * @return + * @throws Exception + */ + public static String httpJsonPost(String url, String jsonStr) throws Exception{ + StringEntity httpEntity = new StringEntity(jsonStr,"UTF-8"); + httpEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); + return httpPost(url, "UTF-8", DEFAULT_TIME_OUT, httpEntity); + } + + /** + * post请求 + * @param url + * @param jsonStr + * @param charset + * @param timeout + * @return + */ + public static String httpPost(String url, String jsonStr, String charset, int timeout){ + log.debug("http request url: {} charset:{} timeout: {} request jsonStr: {}", url, charset, timeout, jsonStr); + + HttpEntity httpEntity = null; + try { + httpEntity = new StringEntity(jsonStr, charset); + return httpPost(url, charset, timeout, httpEntity); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String httpPost(String url, HttpEntity httpEntity) { + return httpPost(url, "UTF-8", DEFAULT_TIME_OUT, httpEntity); + } + + /** + * post请求 + * @param url + * @param charset + * @param timeout + * @param httpEntity + * @return + */ + public static String httpPost(String url, String charset, int timeout, HttpEntity httpEntity) { + log.debug("http url: {}", url); + if (url == null || url.equals("")) { + return null; + } + String result = null; + HttpClient httpClient = null; + HttpPost httpPost = null; + String responseBody = null; + HttpResponse httpResponse = null; + try { + HttpParams httpParams = new BasicHttpParams(); + httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); + httpClient = new DefaultHttpClient(httpParams); + httpPost = new HttpPost(url); + httpPost.setEntity(httpEntity); + httpResponse = httpClient.execute(httpPost); + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpPost.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = httpResponse.getEntity(); + responseBody = EntityUtils.toString(entity, charset); + result = responseBody; + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + // 关闭连接,释放资源 + if (httpClient != null) { + httpClient.getConnectionManager().shutdown(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + log.debug("http return:{}", result); + return result; + } + + /** + * get请求 + * @param url + * @param params + * @return + */ + public static String httpGet(String url, Map params){ + return httpGet(url, params, "UTF-8", DEFAULT_TIME_OUT); + } + + /** + * get请求 + * @param url + * @param params + * @param charset + * @param timeout + * @return + */ + public static String httpGet(String url, Map params, String charset, int timeout) { + HttpClient httpClient = null; + try { + HttpParams httpParams = new BasicHttpParams(); + httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIME_OUT); + httpClient = new DefaultHttpClient(httpParams); + HttpEntity httpEntity = httpGetEntity(httpClient, url, params, DEFAULT_CHARSET); + return EntityUtils.toString(httpEntity, charset); + } catch (ParseException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally{ + try { + if (httpClient != null) { + httpClient.getConnectionManager().shutdown(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * get请求 + * @param url + * @param params + * @param charset + * @param timeout + * @return + */ + public static byte[] httpGetBytes(String url, Map params) { + HttpClient httpClient = null; + try { + HttpParams httpParams = new BasicHttpParams(); + httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIME_OUT); + httpClient = new DefaultHttpClient(httpParams); + HttpEntity httpEntity = httpGetEntity(httpClient, url, params, DEFAULT_CHARSET); + return EntityUtils.toByteArray(httpEntity); + } catch (ParseException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally{ + try { + if (httpClient != null) { + httpClient.getConnectionManager().shutdown(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * get请求 + * @param url + * @param params + * @param charset + * @param timeout + * @return + */ + public static HttpEntity httpGetEntity(HttpClient httpClient, String url, Map params, String charset) { + log.debug("http request url: {} charset:{} request str: {}", url, charset, params); + if (url == null || url.equals("")) { + return null; + } + HttpGet httpGet; + HttpResponse httpResponse; + HttpEntity entity = null; + try { + if (params != null && !params.isEmpty()) { + List pairs = new ArrayList<>(); + for (Entry entry : params.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + pairs.add(new BasicNameValuePair(key, formatStr(value))); + } + url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + httpGet = new HttpGet(url); + httpResponse = httpClient.execute(httpGet); + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + entity = httpResponse.getEntity(); + } catch (Exception e) { + e.printStackTrace(); + } + return entity; + } + + private static String formatStr(String text) { + return (null == text ? "" : text.trim()); + } +} diff --git a/src/main/java/com/haiyu/manager/controller/IndexController.java b/src/main/java/com/haiyu/manager/controller/IndexController.java index 1f51470..42c6a51 100644 --- a/src/main/java/com/haiyu/manager/controller/IndexController.java +++ b/src/main/java/com/haiyu/manager/controller/IndexController.java @@ -1,11 +1,21 @@ package com.haiyu.manager.controller; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.subject.Subject; +import javax.servlet.http.HttpServletRequest; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.util.StringUtil; +import com.haiyu.manager.common.IStatusMessage; +import com.haiyu.manager.common.IStatusMessage.SystemStatus; +import com.haiyu.manager.common.utils.HttpClientUtil; +import com.haiyu.manager.response.ResponseResult; + /** * @Title: LoginController @@ -39,4 +49,22 @@ public String register(){ public String activation(){ return "activation"; } + + @RequestMapping("getData") + @ResponseBody + public ResponseResult getData(HttpServletRequest request) throws Exception{ + String input_data = request.getParameter("input_data"); + if(StringUtil.isEmpty(input_data) || ",,".equals(input_data)){ + return new ResponseResult(IStatusMessage.SystemStatus.PARAM_ERROR); + } + + ResponseResult ret = new ResponseResult(); + String s =HttpClientUtil.httpGet("http://10.11.0.116:5500/law?inputdata="+input_data, null); + JSONObject json = JSON.parseObject(s); + String code = json.getString("code"); + ret.setObj(s); + ret.setCode(SystemStatus.SUCCESS.getCode()); + ret.setMessage(SystemStatus.SUCCESS.getMessage()); + return ret; + } } diff --git a/src/main/resources/templates/docum.html b/src/main/resources/templates/docum.html index 9a06dc3..e83edb3 100644 --- a/src/main/resources/templates/docum.html +++ b/src/main/resources/templates/docum.html @@ -25,6 +25,11 @@ height:0; } } + .font-highlight{ + color: red; + font-size: 24px; + font-weight: 1000; + }
@@ -64,112 +69,113 @@
-
- +
+
+
+
+ + diff --git a/src/test/java/com/haiyu/EightQueen.java b/src/test/java/com/haiyu/EightQueen.java new file mode 100644 index 0000000..13e8d56 --- /dev/null +++ b/src/test/java/com/haiyu/EightQueen.java @@ -0,0 +1,89 @@ +package com.haiyu; + +import java.util.Date; + +/** + * 在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击, + * 即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 + * 下面使用递归方法解决 + * + * @author newflydd@189.cn + */ +public class EightQueen { + /**使用常量来定义,方便之后解N皇后问题*/ + private static final short N = 8; + /**结果计数器*/ + private static int count = 0; + + public static void main(String[] args) { + Date begin = new Date(); + //初始化棋盘,全部置0 + short [][]chess = new short[N][N]; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + chess[i][j] = 0; + } + } + putQueenAtRow(chess, 0); + Date end = new Date(); + System.out.println("解决 " + N + " 皇后问题,用时:" + String.valueOf(end.getTime() - begin.getTime()) + "毫秒,计算结果:" + count); + } + + private static void putQueenAtRow(short[][] chess, int row) { + /** + * 递归终止判断:如果row==N,则说明已经成功摆放了8个皇后 + * 输出结果,终止递归 + */ + if (row == N) { + count++; + System.out.println("第 " + count + " 种解:"); + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + System.out.print(chess[i][j] + " "); + } + System.out.println(); + } + return; + } + + short[][] chessTemp = chess.clone(); + + /** + * 向这一行的每一个位置尝试排放皇后 + * 然后检测状态,如果安全则继续执行递归函数摆放下一行皇后 + */ + for (int col = 0; col < N; col++) { + //摆放这一行的皇后,之前要清掉所有这一行摆放的记录,防止污染棋盘 + for (int j = 0; j < N; j++) { + chessTemp[row][j] = 0; + } + chessTemp[row][col] = 1; + + if (isSafety(chessTemp, row, col)) { + putQueenAtRow(chessTemp, row + 1); + } + } + } + + private static boolean isSafety(short[][] chess, int row, int col) { + //判断中上、左上、右上是否安全 + int step = 1; + while (row - step >= 0) { + //中上 + if (chess[row - step][col] == 1) { + return false; + } + //左上 + if (col - step >= 0 && chess[row - step][col - step] == 1) { + return false; + } + //右上 + if (col + step < N && chess[row - step][col + step] == 1) { + return false; + } + + step++; + } + return true; + } +} \ No newline at end of file diff --git a/src/test/java/com/haiyu/HttpCliectTest.java b/src/test/java/com/haiyu/HttpCliectTest.java new file mode 100644 index 0000000..d2dc508 --- /dev/null +++ b/src/test/java/com/haiyu/HttpCliectTest.java @@ -0,0 +1,18 @@ +package com.haiyu; + +import org.json.JSONObject; +import org.junit.Test; + +import com.haiyu.manager.common.utils.HttpClientUtil; + +public class HttpCliectTest { + + @Test + public void aa() throws Exception { + JSONObject paramjson = new JSONObject(); + paramjson.put("input_data", "'ZZS0420190425011','刘金荣','410104196205305524'"); + //String s =HttpClientUtil.httpPost("http://10.96.2.139:5000/test", paramjson.toString()); + String s =HttpClientUtil.httpGet("http://10.96.2.139:5000/test", null); + System.out.println(s); + } +}