├── UI
├── dump.rdb
├── .DS_Store
├── images
│ ├── index_1.jpg
│ ├── index_2.jpg
│ ├── index_3.jpg
│ └── login.jpeg
├── src
│ ├── config
│ │ └── config.js
│ ├── vendors.js
│ ├── router
│ │ ├── _import_development.js
│ │ └── index.js
│ ├── app.vue
│ ├── store
│ │ ├── getters.js
│ │ ├── index.js
│ │ └── modules
│ │ │ ├── Permission.js
│ │ │ └── user.js
│ ├── utils
│ │ ├── auth.js
│ │ └── fetch.js
│ ├── views
│ │ ├── dashboard
│ │ │ ├── navMenu.vue
│ │ │ ├── index.vue
│ │ │ └── wordCountPanel.vue
│ │ ├── login
│ │ │ ├── signed.vue
│ │ │ ├── index.vue
│ │ │ └── signIn.vue
│ │ ├── admin
│ │ │ ├── index.vue
│ │ │ ├── roleInfoPanel.vue
│ │ │ ├── permissionInfoPanel.vue
│ │ │ └── userInfoPanel.vue
│ │ └── index
│ │ │ └── index.vue
│ ├── libs
│ │ └── util.js
│ ├── template
│ │ └── index.ejs
│ ├── api
│ │ └── login.js
│ ├── main.js
│ └── permission.js
├── index.html
├── package.json
└── webpack.config.js
├── Server
├── dump.rdb
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── zhuxs
│ │ │ │ └── result
│ │ │ │ ├── service
│ │ │ │ ├── WordCountService.java
│ │ │ │ ├── PermissionService.java
│ │ │ │ ├── RoleService.java
│ │ │ │ ├── UserService.java
│ │ │ │ └── impl
│ │ │ │ │ ├── PermissionServiceImpl.java
│ │ │ │ │ ├── UserServiceImpl.java
│ │ │ │ │ ├── RoleServiceImpl.java
│ │ │ │ │ └── WordCountServiceImpl.java
│ │ │ │ ├── domain
│ │ │ │ ├── RoleDao.java
│ │ │ │ ├── enums
│ │ │ │ │ ├── JobTypeEnum.java
│ │ │ │ │ ├── ResourceType.java
│ │ │ │ │ ├── UserStatus.java
│ │ │ │ │ ├── ActionType.java
│ │ │ │ │ ├── ErrorCode.java
│ │ │ │ │ └── JobStatus.java
│ │ │ │ ├── PermissionDao.java
│ │ │ │ ├── UserDao.java
│ │ │ │ ├── JobDao.java
│ │ │ │ └── entity
│ │ │ │ │ ├── Job.java
│ │ │ │ │ ├── Permission.java
│ │ │ │ │ ├── Role.java
│ │ │ │ │ └── User.java
│ │ │ │ ├── bo
│ │ │ │ ├── Word.java
│ │ │ │ ├── comparator
│ │ │ │ │ └── CountComparator.java
│ │ │ │ └── Count.java
│ │ │ │ ├── config
│ │ │ │ ├── ModelMapperConfig.java
│ │ │ │ ├── CorsConfig.java
│ │ │ │ ├── RedisCacheConfig.java
│ │ │ │ ├── ApplicationConfig.java
│ │ │ │ └── ShiroConfig.java
│ │ │ │ ├── ResultApplication.java
│ │ │ │ ├── shiro
│ │ │ │ ├── ShiroSessionFactory.java
│ │ │ │ ├── ShiroSessionListener.java
│ │ │ │ ├── ShiroSession.java
│ │ │ │ ├── ShiroRealm.java
│ │ │ │ └── ShiroSessionDao.java
│ │ │ │ ├── dto
│ │ │ │ ├── TextDto.java
│ │ │ │ ├── ErrorDto.java
│ │ │ │ ├── RoleDto.java
│ │ │ │ ├── PermissionDto.java
│ │ │ │ └── UserDto.java
│ │ │ │ ├── utils
│ │ │ │ ├── RegsUtil.java
│ │ │ │ ├── ApplicationUtil.java
│ │ │ │ └── SerializeUtils.java
│ │ │ │ ├── Exception
│ │ │ │ └── ResultException.java
│ │ │ │ ├── Handler
│ │ │ │ └── GlobalExceptionHandler.java
│ │ │ │ └── controller
│ │ │ │ ├── JobController.java
│ │ │ │ ├── AuthController.java
│ │ │ │ └── AdminController.java
│ │ └── resources
│ │ │ └── application.properties
│ └── test
│ │ └── java
│ │ └── com
│ │ └── zhuxs
│ │ └── result
│ │ └── ResultApplicationTests.java
├── pom.xml
├── mvnw.cmd
└── mvnw
├── .gitignore
├── README.md
└── LICENSE
/UI/dump.rdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/dump.rdb
--------------------------------------------------------------------------------
/UI/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/.DS_Store
--------------------------------------------------------------------------------
/Server/dump.rdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/Server/dump.rdb
--------------------------------------------------------------------------------
/UI/images/index_1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/images/index_1.jpg
--------------------------------------------------------------------------------
/UI/images/index_2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/images/index_2.jpg
--------------------------------------------------------------------------------
/UI/images/index_3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/images/index_3.jpg
--------------------------------------------------------------------------------
/UI/images/login.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ZhuXS/Spring-Shiro-Spark/HEAD/UI/images/login.jpeg
--------------------------------------------------------------------------------
/UI/src/config/config.js:
--------------------------------------------------------------------------------
1 | import Env from './env';
2 |
3 | let config = {
4 | env: Env
5 | };
6 | export default config;
--------------------------------------------------------------------------------
/UI/src/vendors.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue';
2 | import iView from 'iview';
3 | import VueRouter from 'vue-router';
4 | import axios from 'axios';
--------------------------------------------------------------------------------
/UI/src/router/_import_development.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | module.exports = file => require('../views/' + file + ".vue").default
5 |
--------------------------------------------------------------------------------
/UI/src/app.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
--------------------------------------------------------------------------------
/UI/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Hello RESult
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 |
3 | ### IntelliJ IDEA ###
4 | Server/.idea
5 | UI/.idea
6 | UI/node_modules
7 | UI/dist
8 | Server/.idea/workspace.xml
9 | Server/.idea/workspace.xml
10 | UI/.idea/workspace.xml
11 | Server/.idea/workspace.xml
12 | UI/.idea/workspace.xml
13 | .DS_Store
14 |
15 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/WordCountService.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service;
2 |
3 | import com.zhuxs.result.bo.Count;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * Created by shusesshou on 2017/9/11.
9 | */
10 | public interface WordCountService {
11 | List wordCount(String words);
12 | }
13 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/RoleDao.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain;
2 |
3 | import com.zhuxs.result.domain.entity.Role;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | /**
7 | * Created by shusesshou on 2017/9/20.
8 | */
9 | public interface RoleDao extends JpaRepository{
10 | }
11 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/JobTypeEnum.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/15.
5 | */
6 | public class JobTypeEnum {
7 | public static final int WORDCOUNT_SIM = 0;
8 | public static final int WORDCOUNT_FILE = 1;
9 | public static final int WORDCOUNT_URL = 2;
10 | }
11 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/PermissionDao.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain;
2 |
3 | import com.zhuxs.result.domain.entity.Permission;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | /**
7 | * Created by shusesshou on 2017/9/20.
8 | */
9 | public interface PermissionDao extends JpaRepository {
10 | }
11 |
--------------------------------------------------------------------------------
/UI/src/store/getters.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | const getters = {
5 | status: state => state.user.status,
6 | username: state => state.user.username,
7 | name: state => state.user.name,
8 | roles: state => state.user.roles,
9 | addRouters: state => state.permission.addRouters
10 | }
11 |
12 | export default getters
13 |
--------------------------------------------------------------------------------
/UI/src/utils/auth.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | import Cookies from 'js-cookie'
5 |
6 | const sessionId = 'JSESSIONID'
7 |
8 | export function getSessionId() {
9 | return Cookies.get(sessionId)
10 | }
11 |
12 | export function setSessionId(token) {
13 | return Cookies.set(sessionId,token)
14 | }
15 |
16 | export function removeSessionId() {
17 | return Cookies.remove(sessionId)
18 | }
19 |
--------------------------------------------------------------------------------
/UI/src/views/dashboard/navMenu.vue:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
--------------------------------------------------------------------------------
/UI/src/store/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | import user from './modules/user'
5 | import permission from './modules/permission'
6 | import getters from './getters'
7 |
8 | import Vue from 'vue'
9 | import Vuex from 'vuex'
10 |
11 | Vue.use(Vuex)
12 |
13 | const store = new Vuex.Store({
14 | modules: {
15 | user,
16 | permission
17 | },
18 | getters
19 | })
20 |
21 | export default store
22 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/UserDao.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain;
2 |
3 | import com.zhuxs.result.domain.entity.User;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | import javax.transaction.Transactional;
7 |
8 | /**
9 | * Created by shusesshou on 2017/9/20.
10 | */
11 | public interface UserDao extends JpaRepository{
12 |
13 | @Transactional
14 | User findUserByUsername(String username);
15 | }
16 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/bo/Word.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.bo;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/4.
5 | */
6 | public class Word {
7 |
8 | private String word;
9 |
10 | public Word(){}
11 |
12 | public Word(String word) {
13 | this.word = word;
14 | }
15 |
16 | public String getWord() {
17 | return word;
18 | }
19 |
20 | public void setWord(String word) {
21 | this.word = word;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/config/ModelMapperConfig.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.config;
2 |
3 | import org.modelmapper.ModelMapper;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | /**
8 | * Created by shusesshou on 2017/9/25.
9 | */
10 | @Configuration
11 | public class ModelMapperConfig {
12 | @Bean
13 | public ModelMapper modelMapper(){
14 | return new ModelMapper();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Server/src/test/java/com/zhuxs/result/ResultApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result;
2 |
3 | import org.junit.Ignore;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.test.context.junit4.SpringRunner;
8 |
9 | @Ignore
10 | @RunWith(SpringRunner.class)
11 | @SpringBootTest
12 | public class ResultApplicationTests {
13 |
14 | @Test
15 | public void contextLoads() {
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/PermissionService.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service;
2 |
3 | import com.zhuxs.result.domain.entity.Permission;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * Created by shusesshou on 2017/9/25.
9 | */
10 | public interface PermissionService {
11 | Permission addPermission(Permission permission);
12 | List listPermissions();
13 | List getPermissionsByUserId(long userId);
14 |
15 | void delPermissionById(long id);
16 | }
17 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/bo/comparator/CountComparator.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.bo.comparator;
2 |
3 | import com.zhuxs.result.bo.Count;
4 |
5 | import java.util.Comparator;
6 |
7 | import static java.lang.Math.toIntExact;
8 |
9 | /**
10 | * Created by shusesshou on 2017/9/14.
11 | */
12 | public class CountComparator implements Comparator{
13 |
14 | @Override
15 | public int compare(Count o1, Count o2) {
16 | return toIntExact(o2.getCount() - o1.getCount());
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/UI/src/views/login/signed.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | {{ name }}
7 |
8 |
9 |
10 |
11 |
12 |
13 |
15 |
16 |
--------------------------------------------------------------------------------
/UI/src/libs/util.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import env from '../config/env';
3 |
4 | let util = {
5 |
6 | };
7 | util.title = function(title) {
8 | title = title ? title + ' - Home' : 'iView project';
9 | window.document.title = title;
10 | };
11 |
12 | const ajaxUrl = env === 'development' ?
13 | 'http://127.0.0.1:8888' :
14 | env === 'production' ?
15 | 'https://www.url.com' :
16 | 'https://debug.url.com';
17 |
18 | util.ajax = axios.create({
19 | baseURL: ajaxUrl,
20 | timeout: 30000
21 | });
22 |
23 | export default util;
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/JobDao.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain;
2 |
3 | import com.zhuxs.result.domain.entity.Job;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Repository;
6 |
7 | import javax.transaction.Transactional;
8 | import java.util.Date;
9 | import java.util.List;
10 |
11 | /**
12 | * Created by shusesshou on 2017/9/16.
13 | */
14 | @Transactional
15 | @Repository
16 | public interface JobDao extends JpaRepository {
17 | public List findAllByEndDate(Date date);
18 | }
19 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/RoleService.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service;
2 |
3 | import com.zhuxs.result.domain.entity.Permission;
4 | import com.zhuxs.result.domain.entity.Role;
5 |
6 | import java.util.List;
7 |
8 | /**
9 | * Created by shusesshou on 2017/9/25.
10 | */
11 | public interface RoleService {
12 | Role addRole(Role role);
13 |
14 | List listRoles();
15 |
16 | List getRolesByUserId(long userId);
17 |
18 | Role updatePermissionsById(long id,List permissions);
19 |
20 | void delRoleById(long id);
21 | }
--------------------------------------------------------------------------------
/UI/src/views/dashboard/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/UI/src/template/index.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | iView project
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service;
2 |
3 | import com.zhuxs.result.domain.entity.Permission;
4 | import com.zhuxs.result.domain.entity.Role;
5 | import com.zhuxs.result.domain.entity.User;
6 | import com.zhuxs.result.dto.UserDto;
7 |
8 | import java.util.List;
9 |
10 | /**
11 | * Created by shusesshou on 2017/9/25.
12 | */
13 | public interface UserService {
14 | User addUser(User user);
15 | List listUsers();
16 | User updateRolesById(long id, List roles);
17 | User updatePermissionsById(long id, List permissions);
18 | void delUserById(long id);
19 | }
20 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/ResultApplication.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
6 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
7 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
8 |
9 | @SpringBootApplication
10 | public class ResultApplication {
11 | public static void main(String[] args) {
12 | System.setProperty("spark.executor.memory","512m");
13 | SpringApplication.run(ResultApplication.class, args);
14 | }
15 |
16 |
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/shiro/ShiroSessionFactory.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.shiro;
2 |
3 | import org.apache.shiro.session.Session;
4 | import org.apache.shiro.session.mgt.SessionContext;
5 | import org.apache.shiro.session.mgt.SessionFactory;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | /**
10 | * Created by shusesshou on 2017/9/22.
11 | */
12 | public class ShiroSessionFactory implements SessionFactory{
13 | private static final Logger logger = LoggerFactory.getLogger(ShiroSessionFactory.class);
14 |
15 | @Override
16 | public Session createSession(SessionContext sessionContext) {
17 | ShiroSession session = new ShiroSession();
18 | return session;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/bo/Count.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.bo;
2 |
3 | import java.util.Comparator;
4 |
5 | /**
6 | * Created by shusesshou on 2017/9/4.
7 | */
8 | public class Count{
9 | private String word;
10 | private long count;
11 |
12 | public Count(){}
13 |
14 | public Count(String word, long count) {
15 | this.word = word;
16 | this.count = count;
17 | }
18 |
19 | public String getWord() {
20 | return word;
21 | }
22 |
23 | public void setWord(String word) {
24 | this.word = word;
25 | }
26 |
27 | public long getCount() {
28 | return count;
29 | }
30 |
31 | public void setCount(long count) {
32 | this.count = count;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/UI/src/api/login.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | import fetch from '../utils/fetch'
5 |
6 | export function login(username, password) {
7 | const data = {
8 | username,
9 | password
10 | }
11 | return fetch({
12 | url: '/login',
13 | method: 'post',
14 | data
15 | })
16 | }
17 |
18 | //test the user login or not and get the userInfo
19 | export function getUserInfo() {
20 | return fetch({
21 | url:'/userInfo',
22 | method:'get'
23 | })
24 | }
25 |
26 | export function logout(sessionId) {
27 | const data = {
28 | sessionId
29 | }
30 | return fetch({
31 | url:'/logout',
32 | method: 'post',
33 | data
34 | })
35 | }
36 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/ResourceType.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/20.
5 | */
6 | public enum ResourceType {
7 |
8 | WORDCOUNT(0,"WordCount");
9 |
10 | private int type;
11 | private String desc;
12 |
13 | ResourceType() {
14 | }
15 |
16 | ResourceType(int type, String desc) {
17 | this.type = type;
18 | this.desc = desc;
19 | }
20 |
21 | public int getType() {
22 | return type;
23 | }
24 |
25 | public void setType(int type) {
26 | this.type = type;
27 | }
28 |
29 | public String getDesc() {
30 | return desc;
31 | }
32 |
33 | public void setDesc(String desc) {
34 | this.desc = desc;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spark-Shiro-Spark
2 | Spark-Shiro-Spark是Spring-Boot Hibernate Spark Spark-SQL Shiro iView VueJs... ...的集成尝试
3 | ## 主要做了两件事
4 | - **前后端分离下的用户认证和鉴权实践**
5 |
6 | - [前后端分离下的用户认证和鉴权实践(一) 概述](https://github.com/ZhuXS/RESult/issues/1)
7 | - [前后端分离下的用户认证和鉴权实践(二) 权限粒度的设计](https://github.com/ZhuXS/RESult/issues/2)
8 | - [前后端分离下的用户认证和鉴权实践(三) Shiro简介](https://github.com/ZhuXS/RESult/issues/4)
9 | - [前后端分离下的用户认证和鉴权实践(四) 基于shiro的后端认证和鉴权](https://github.com/ZhuXS/RESult/issues/5)
10 | - [前后端分离下的用户认证和鉴权实践(五) 用户登录状态的保持和单点登录](https://github.com/ZhuXS/RESult/issues/6)
11 | - [前后端分离下的用户认证和鉴权实践(六) 前端的路由控制和动态渲染](https://github.com/ZhuXS/RESult/issues/7)
12 |
13 | - **Spring Boot与Spark的集成实践**
14 |
15 | - [Spring Boot与Spark的集成实践](https://github.com/ZhuXS/RESult/issues/8)
16 |
17 |
18 | ## 欢迎批评指教
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/UserStatus.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/19.
5 | */
6 | public enum UserStatus {
7 |
8 | CREATE(1,"create without certification"),
9 | NORMAL(2,"normal"),
10 | LOCKED(3,"locked");
11 |
12 | private int status;
13 | private String desc;
14 |
15 | UserStatus() {
16 | }
17 |
18 | UserStatus(int status, String desc) {
19 | this.status = status;
20 | this.desc = desc;
21 | }
22 |
23 | public int getStatus() {
24 | return status;
25 | }
26 |
27 | public void setStatus(int status) {
28 | this.status = status;
29 | }
30 |
31 | public String getDesc() {
32 | return desc;
33 | }
34 |
35 | public void setDesc(String desc) {
36 | this.desc = desc;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/ActionType.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | /**
4 | * Created by shusesshou on 2017/10/9.
5 | */
6 | public enum ActionType {
7 | ALL(0,"all"),
8 | CREATE(1,"create"),
9 | READ(2,"read"),
10 | UPDATE(3,"update"),
11 | DELETE(4,"delete")
12 | ;
13 | private int type;
14 | private String desc;
15 |
16 | ActionType() {
17 | }
18 |
19 | ActionType(int type, String desc) {
20 | this.type = type;
21 | this.desc = desc;
22 | }
23 |
24 | public int getType() {
25 | return type;
26 | }
27 |
28 | public void setType(int type) {
29 | this.type = type;
30 | }
31 |
32 | public String getDesc() {
33 | return desc;
34 | }
35 |
36 | public void setDesc(String desc) {
37 | this.desc = desc;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/dto/TextDto.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.dto;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/11.
5 | */
6 | public class TextDto {
7 | private String words;
8 |
9 | public TextDto() {
10 | }
11 |
12 | public TextDto(String words) {
13 | this.words = words;
14 | }
15 |
16 | public String getWords() {
17 | return words;
18 | }
19 |
20 | public void setWords(String words) {
21 | this.words = words;
22 | }
23 |
24 | @Override
25 | public boolean equals(Object o) {
26 | if (this == o) return true;
27 | if (o == null || getClass() != o.getClass()) return false;
28 |
29 | TextDto TextDto = (TextDto) o;
30 |
31 | return words != null ? words.equals(TextDto.words) : TextDto.words == null;
32 | }
33 |
34 | @Override
35 | public int hashCode() {
36 | return words != null ? words.hashCode() : 0;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/UI/src/views/admin/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/UI/src/main.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/8.
3 | */
4 | import Vue from 'vue'
5 | import VueRouter from 'vue-router'
6 | import Vuex from 'vuex'
7 | import App from './app.vue'
8 | import router from './router/index'
9 | import store from './store'
10 |
11 | //agile for index
12 | import VueAgile from 'vue-agile'
13 | Vue.use(VueAgile)
14 |
15 | //iView UI
16 | import iView from 'iview';
17 | import 'iview/dist/styles/iview.css';
18 | import './permission'
19 |
20 | //加载路由中间件
21 | Vue.use(iView)
22 | Vue.use(Vuex)
23 |
24 | //Global Error Handler
25 | Vue.config.errorHandler = function (err,vm,info) {
26 | //Server Error
27 | alert(err)
28 | if(err.response){
29 | //not Auth
30 | if(err.response.data.errorCode === 40010){
31 | Vue.$router.push({
32 | path:'/login'
33 | })
34 | }
35 | }
36 | }
37 |
38 | new Vue({
39 | el: '#app',
40 | router,
41 | store,
42 | render: h => h(App)
43 | })
44 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/ErrorCode.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | import com.fasterxml.jackson.annotation.JsonFormat;
4 |
5 | /**
6 | * Created by shusesshou on 2017/9/18.
7 | */
8 | @JsonFormat(shape = JsonFormat.Shape.OBJECT)
9 | public enum ErrorCode {
10 | ERROR(40000,"error"),
11 | NOTAUTHC(40100,"not authc"),
12 | NOTAUTHZ(40101,"not authz"),
13 | USERNAMEORPASSWORD(40401,"Username or Password Not Correct");
14 |
15 | private final int code;
16 | private final String desc;
17 |
18 | ErrorCode(int code, String desc) {
19 | this.code = code;
20 | this.desc = desc;
21 | }
22 |
23 | public int getCode() {
24 | return code;
25 | }
26 |
27 | public String getDesc() {
28 | return desc;
29 | }
30 |
31 | @Override
32 | public String toString() {
33 | return "ErrorCode{" +
34 | "code=" + code +
35 | ", desc='" + desc + '\'' +
36 | '}';
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/domain/enums/JobStatus.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.domain.enums;
2 |
3 | /**
4 | * Created by shusesshou on 2017/9/18.
5 | */
6 | public enum JobStatus {
7 |
8 | WAITING(0,"waiting"),
9 | READY(1,"ready"),
10 | RUNNING(2,"running"),
11 | BLOCK(3,"block"),
12 | FAILED(4,"failed"),
13 | SUCCESS(5,"success");
14 |
15 | private int status;
16 | private String desc;
17 |
18 | JobStatus(int status, String desc) {
19 | this.status = status;
20 | this.desc = desc;
21 | }
22 |
23 | public int getStatus() {
24 | return status;
25 | }
26 |
27 | public void setStatus(int status) {
28 | this.status = status;
29 | }
30 |
31 | public String getDesc() {
32 | return desc;
33 | }
34 |
35 | public void setDesc(String desc) {
36 | this.desc = desc;
37 | }
38 |
39 |
40 | @Override
41 | public String toString() {
42 | return "JobStatus{" +
43 | "status=" + status +
44 | ", desc='" + desc + '\'' +
45 | '}';
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/utils/RegsUtil.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.utils;
2 |
3 | import java.util.regex.Matcher;
4 | import java.util.regex.Pattern;
5 | import java.util.regex.PatternSyntaxException;
6 |
7 | /**
8 | * Created by shusesshou on 2017/9/14.
9 | */
10 | public class RegsUtil {
11 |
12 | public static boolean checkSpecialChar(String str) throws PatternSyntaxException {
13 | // 清除掉所有特殊字符
14 | String regEx = ".*[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?\\\\]+.*";
15 | Pattern p = Pattern.compile(regEx);
16 | Matcher m = p.matcher(str);
17 | return m.matches();
18 | }
19 |
20 | /**
21 | * replace all special symbol by one space
22 | * @param str
23 | * @return
24 | * @throws PatternSyntaxException
25 | */
26 | public static String filterString(String str) throws PatternSyntaxException {
27 | String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?\\\\]";
28 | Pattern p = Pattern.compile(regEx);
29 | Matcher m = p.matcher(str);
30 | return m.replaceAll(" ").replaceAll("\\s+"," ").trim();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/utils/ApplicationUtil.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.utils;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.http.HttpHeaders;
6 | import org.springframework.http.MediaType;
7 | import org.springframework.web.context.request.WebRequest;
8 | import org.springframework.web.util.UriComponents;
9 | import org.springframework.web.util.UriComponentsBuilder;
10 |
11 | import java.net.URI;
12 |
13 |
14 | /**
15 | * Created by shusesshou on 2017/9/11.
16 | */
17 | public class ApplicationUtil {
18 | private static final Logger logger = LoggerFactory.getLogger(ApplicationUtil.class);
19 |
20 | public static HttpHeaders getHttpHeaders(UriComponentsBuilder uriComponentsBuilder,String uri,Object... uriVariableValues){
21 | UriComponents uriComponents = uriComponentsBuilder.path(uri).buildAndExpand(uriVariableValues);
22 | HttpHeaders headers = new HttpHeaders();
23 | try {
24 | headers.setLocation(new URI(uriComponents.getPath()));
25 | }catch (Exception e){
26 | logger.error(e.getStackTrace().toString());
27 | }
28 | headers.setContentType(MediaType.APPLICATION_JSON);
29 | return headers;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/UI/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ui",
3 | "version": "1.0.0",
4 | "description": "UI of RESult",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "test",
8 | "dev": "webpack-dev-server --hot --open --port 8086"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "axios": "^0.16.2",
14 | "babel-core": "^6.26.0",
15 | "babel-loader": "^7.1.2",
16 | "babel-preset-vue-app": "^1.3.0",
17 | "cross-env": "^5.0.5",
18 | "css-loader": "^0.28.7",
19 | "file-loader": "^0.11.2",
20 | "iview": "^2.3.2",
21 | "js-cookie": "^2.1.4",
22 | "nprogress": "^0.2.0",
23 | "style-loader": "^0.18.2",
24 | "vue": "^2.4.2",
25 | "vue-agile": "^0.2.6",
26 | "vue-html-loader": "^1.2.4",
27 | "vue-loader": "^13.0.4",
28 | "vue-resource": "^1.3.4",
29 | "vue-router": "^2.7.0",
30 | "vue-style-loader": "^3.0.1",
31 | "vue-template-compiler": "^2.4.2",
32 | "vuex": "^2.4.0",
33 | "webpack": "^3.5.5",
34 | "webpack-dev-server": "^2.7.1"
35 | },
36 | "devDependencies": {
37 | "babel-plugin-component": "^0.10.0",
38 | "html-webpack-plugin": "^2.30.1",
39 | "node-sass": "^4.5.3",
40 | "sass-loader": "^6.0.6",
41 | "vue": "^2.4.2"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/UI/src/utils/fetch.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | import axios from 'axios'
5 | import { getToken } from './auth'
6 | import store from '../store'
7 |
8 | //创建axios实例
9 | const service = axios.create({
10 | baseURL: "http://localhost:8081",
11 | timeout: 5000, //请求超时时间
12 | withCredentials : true
13 | })
14 |
15 | //是否保留跨域请求凭证
16 | service.defaults.withCredentials = true
17 |
18 | //request拦截器
19 | service.interceptors.request.use(config => {
20 | if(store.getters.status){
21 | //take token or sessionId
22 | }
23 | return config
24 | },error => {
25 | console.log(error)
26 | Promise.reject(error)
27 | })
28 |
29 | //response拦截器
30 | service.interceptors.response.use(response => {
31 | //alert(response.data)
32 | return response
33 | },error => {
34 | //alert(error.response.data.errorCode.code)
35 | if(error.response.data.errorCode.code === 40100){
36 | window.location .href = "login"
37 | return Promise.reject(error)
38 | } else if(error.response.data.errorCode.code === 40101){
39 | window.location.href = "dashboard"
40 | return Promise.reject(error)
41 | }else {
42 | return Promise.reject(error)
43 | }
44 | })
45 |
46 | export default service
--------------------------------------------------------------------------------
/UI/src/views/login/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |

7 |
8 |
9 |
10 |
11 |
33 |
34 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/config/CorsConfig.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.cors.CorsConfiguration;
6 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
7 | import org.springframework.web.filter.CorsFilter;
8 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
9 |
10 | /**
11 | * Created by shusesshou on 2017/9/11.
12 | */
13 | @Configuration
14 | public class CorsConfig {
15 | private CorsConfiguration buildConfig(){
16 | CorsConfiguration corsConfiguration = new CorsConfiguration();
17 | corsConfiguration.addAllowedOrigin("*"); //allow all cross origin
18 | corsConfiguration.addAllowedHeader("*"); //allow all header
19 | corsConfiguration.addAllowedMethod("*"); //allow all http method
20 | corsConfiguration.setAllowCredentials(true); //允许保留跨域请求凭证
21 | return corsConfiguration;
22 | }
23 |
24 | @Bean
25 | public CorsFilter corsFilter(){
26 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
27 | source.registerCorsConfiguration("/**",buildConfig());
28 | return new CorsFilter(source);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/dto/ErrorDto.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.dto;
2 |
3 | import com.zhuxs.result.domain.enums.ErrorCode;
4 |
5 | /**
6 | * Created by shusesshou on 2017/9/18.
7 | */
8 | public class ErrorDto {
9 | private String status;
10 | private ErrorCode errorCode;
11 | private String url;
12 | private String msg;
13 |
14 | public ErrorDto() {
15 | }
16 |
17 | public ErrorDto(String status, ErrorCode errorCode, String url, String msg) {
18 | this.status = status;
19 | this.errorCode = errorCode;
20 | this.url = url;
21 | this.msg = msg;
22 | }
23 |
24 | public String getStatus() {
25 | return status;
26 | }
27 |
28 | public void setStatus(String status) {
29 | this.status = status;
30 | }
31 |
32 | public ErrorCode getErrorCode() {
33 | return errorCode;
34 | }
35 |
36 | public void setErrorCode(ErrorCode errorCode) {
37 | this.errorCode = errorCode;
38 | }
39 |
40 | public String getUrl() {
41 | return url;
42 | }
43 |
44 | public void setUrl(String url) {
45 | this.url = url;
46 | }
47 |
48 | public String getMsg() {
49 | return msg;
50 | }
51 |
52 | public void setMsg(String msg) {
53 | this.msg = msg;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/Exception/ResultException.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.exception;
2 |
3 | import com.fasterxml.jackson.annotation.JsonIgnore;
4 | import com.zhuxs.result.domain.enums.ErrorCode;
5 |
6 | /**
7 | * Created by shusesshou on 2017/9/18.
8 | */
9 | public class ResultException extends RuntimeException{
10 | private ErrorCode errorCode;
11 |
12 | public ResultException() {
13 | }
14 |
15 | public ResultException(String message) {
16 | super(message);
17 | }
18 |
19 | public ResultException(String message, ErrorCode errorCode) {
20 | super(message);
21 | this.errorCode = errorCode;
22 | }
23 |
24 | public ResultException(Throwable cause, ErrorCode errorCode) {
25 | super(cause);
26 | this.errorCode = errorCode;
27 | }
28 |
29 | public ResultException(String message, Throwable cause, ErrorCode errorCode) {
30 | super(message, cause);
31 | this.errorCode = errorCode;
32 | }
33 |
34 | public ErrorCode getErrorCode() {
35 | return errorCode;
36 | }
37 |
38 | public void setErrorCode(ErrorCode errorCode) {
39 | this.errorCode = errorCode;
40 | }
41 |
42 | @JsonIgnore
43 | public ResultException getResultExceptionWithoutCause(){
44 | return new ResultException(this.getMessage(),this.getErrorCode());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/UI/src/router/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/21.
3 | */
4 | import Vue from 'vue'
5 | import Router from "vue-router"
6 |
7 | const _import = require('./_import_development')
8 |
9 | Vue.use(Router)
10 |
11 | //所有权限通用路由表
12 | export const constantRouterMap = [
13 | {
14 | path: '/',
15 | component: _import('index/index'),
16 | name: "hello"
17 | },
18 | {
19 | path: '/dashboard',
20 | component: _import('dashboard/index'),
21 | name: "RESult",
22 | },
23 | {
24 | path: "/login",
25 | component: _import('login/index'),
26 | name: "login"
27 | },
28 | {
29 | path: "/admin",
30 | component: _import('admin/index'),
31 | //redirect: '/dashboard',
32 | meta:{
33 | role: ['Admin']
34 | },
35 | name: "admin"
36 | },
37 | {
38 | path: "*",
39 | component: _import('index/index'),
40 | name: "Not Found"
41 | }
42 | ]
43 |
44 | export default new Router({
45 | mode: 'history',
46 | scrollBehavior: () => ({y:0}),
47 | routes: constantRouterMap
48 | })
49 |
50 | export const asyncRouterMap = [
51 | {
52 | path: "/admin",
53 | component: _import('admin/index'),
54 | //redirect: '/dashboard',
55 | meta:{
56 | role: ['Admin']
57 | },
58 | name: "admin"
59 | }
60 | ]
--------------------------------------------------------------------------------
/Server/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | ###################################
2 | ############# BASE
3 | ###################################
4 | app.name=RESult
5 |
6 | ###################################
7 | ############# SPARK
8 | ###################################
9 | spark.home=127.0.0.1
10 | master.uri=spark://127.0.0.1:7077
11 | server.port=8081
12 |
13 | ###################################
14 | ############# MYSQL
15 | ###################################
16 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/result?useSSL=false
17 | spring.datasource.username=root
18 | spring.datasource.password=root
19 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
20 |
21 | ###################################
22 | ############# HIBERNATE
23 | ###################################
24 | spring.jpa.database=mysql
25 | spring.jpa.hibernate.ddl-auto=update
26 | spring.jpa.show-sql=true
27 | spring.jpa.properties.hibernate.format_sql=true
28 |
29 | ###################################
30 | ############# REDIS
31 | ###################################
32 | # Redis数据库索引
33 | spring.redis.database=0
34 | # Redis服务器地址
35 | spring.redis.host=127.0.0.1
36 | # Redis服务器连接端口
37 | spring.redis.port=6379
38 | # Redis服务器连接密码
39 | spring.redis.password=redis
40 | # 连接池最大阻塞等待时间
41 | spring.redis.pool.max-wait=-1
42 | # 连接池中的最大空闲连接
43 | spring.redis.pool.max-idle=-1
44 | # 连接池中的最小空闲连接
45 | spring.redis.pool.min-idle=-1
46 | # 连接超时时间
47 | spring.redis.timeout=5000
48 |
49 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/shiro/ShiroSessionListener.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.shiro;
2 |
3 | import org.apache.shiro.session.Session;
4 | import org.apache.shiro.session.SessionListener;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import redis.clients.jedis.Jedis;
9 | import redis.clients.jedis.JedisPool;
10 |
11 | /**
12 | * Created by shusesshou on 2017/9/22.
13 | */
14 | public class ShiroSessionListener implements SessionListener {
15 |
16 | private static final Logger logger = LoggerFactory.getLogger(ShiroSessionListener.class);
17 |
18 | @Autowired
19 | private ShiroSessionDao shiroSessionDao;
20 |
21 | @Autowired
22 | private JedisPool jedisPool;
23 |
24 | @Override
25 | public void onStart(Session session) {
26 | logger.debug("session {} onStart",session.getId());
27 | }
28 |
29 | @Override
30 | public void onStop(Session session) {
31 | shiroSessionDao.delete(session);
32 | Jedis jedis = jedisPool.getResource();
33 | jedis.publish("shiro.session.uncache",(String) session.getId());
34 | logger.debug("session {} onStop", session.getId());
35 | }
36 |
37 | @Override
38 | public void onExpiration(Session session) {
39 | shiroSessionDao.delete(session);
40 | Jedis jedis = jedisPool.getResource();
41 | jedis.publish("shiro.session.uncache",(String) session.getId());
42 | logger.debug("session {} onExpiration", session.getId());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/utils/SerializeUtils.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.utils;
2 |
3 | import com.google.common.collect.Lists;
4 | import com.zhuxs.result.exception.ResultException;
5 | import org.apache.commons.lang3.SerializationUtils;
6 | import org.apache.shiro.codec.Base64;
7 |
8 | import java.io.Serializable;
9 | import java.util.Collection;
10 | import java.util.List;
11 |
12 | /**
13 | * Created by shusesshou on 2017/9/22.
14 | */
15 | public class SerializeUtils extends SerializationUtils{
16 | public static String serializaToString(Serializable obj){
17 | try{
18 | byte[] value = serialize(obj);
19 | return Base64.encodeToString(value);
20 | }catch (Exception e){
21 | throw new ResultException("serialize session error");
22 | }
23 | }
24 |
25 | public static T deserializeFromString(String base64){
26 | try{
27 | byte[] objectData = Base64.decode(base64);
28 | return deserialize(objectData);
29 | } catch (Exception e){
30 | throw new ResultException("deserialize session error");
31 | }
32 | }
33 |
34 | public static Collection deserializeFromStrings(Collection base64s){
35 | try{
36 | List list = Lists.newLinkedList();
37 | for(String base64 : base64s){
38 | byte[] objectData = Base64.decode(base64);
39 | T t = deserialize(objectData);
40 | list.add(t);
41 | }
42 | return list;
43 | }catch (Exception e){
44 | throw new ResultException("deserialize session error");
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/config/RedisCacheConfig.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.config;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.beans.factory.annotation.Value;
6 | import org.springframework.cache.annotation.CachingConfigurerSupport;
7 | import org.springframework.cache.annotation.EnableCaching;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 | import redis.clients.jedis.JedisPool;
11 | import redis.clients.jedis.JedisPoolConfig;
12 |
13 | /**
14 | * Created by shusesshou on 2017/9/23.
15 | */
16 | @Configuration
17 | @EnableCaching
18 | public class RedisCacheConfig extends CachingConfigurerSupport{
19 | private Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
20 |
21 | @Value("${spring.redis.host}")
22 | private String host;
23 |
24 | @Value("${spring.redis.port}")
25 | private int port;
26 |
27 | @Value("${spring.redis.timeout}")
28 | private int timeout;
29 |
30 | @Value("${spring.redis.pool.max-idle}")
31 | private int maxIdle;
32 |
33 | @Value("${spring.redis.pool.max-wait}")
34 | private long maxWaitMillis;
35 |
36 | @Value("${spring.redis.password}")
37 | private String password;
38 |
39 | @Bean
40 | public JedisPool redisPoolFactory() {
41 | logger.info("redis: " + host + ":" + port);
42 | JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
43 | jedisPoolConfig.setMaxIdle(maxIdle);
44 | jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
45 |
46 | JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
47 | return jedisPool;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/UI/src/permission.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/26.
3 | */
4 | import router from './router'
5 | import store from './store'
6 | import { getSessionId } from "./utils/auth"
7 | import NProgress from 'nprogress' //进度条
8 | import 'nprogress/nprogress.css'
9 |
10 | //permission judge
11 | function hasPermission(roles,permissions) {
12 | if (roles.indexOf('admin') > 0) return true //admin权限,直接通过
13 | if(!permissions) return true
14 |
15 | }
16 |
17 | //register global progress
18 | const whiteList = ['/login','/'] //不重定向白名单
19 | router.beforeEach((to,from,next) => {
20 | NProgress.start(); //开启Progress
21 | if(store.getters.status) {
22 | next
23 | } else {
24 | if(whiteList.indexOf(to.path) !== -1){ //在登录白名单,直接进入
25 | //alert("test")
26 | next();
27 | } else {
28 | store.dispatch('GetUserInfo').then(res => {
29 | //拉取user_info,并测试用户是否登录
30 | const roles = res.data.roles
31 | store.dispatch('GenerateRoutes',roles).then(() => {
32 | console.log(store.getters.addRouters)
33 | router.addRoutes(store.getters.addRouters) //动态添加可访问路由表
34 | console.log(router)
35 | next()
36 | //next({ ...to })
37 | })
38 | }).catch(e => {
39 | if(e.response.data.errorCode.code === 40010){
40 | next('/login') //否则全部定向到登录页
41 | }
42 | if(e.response.data.errorCode.code === 1)
43 | next('/login') //否则全部定向到登录页
44 | })
45 | }
46 | }
47 | })
48 |
49 | router.afterEach(() => {
50 | NProgress.done() //结束Progress
51 | })
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/impl/PermissionServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service.impl;
2 |
3 | import com.zhuxs.result.domain.PermissionDao;
4 | import com.zhuxs.result.domain.UserDao;
5 | import com.zhuxs.result.domain.entity.Permission;
6 | import com.zhuxs.result.domain.entity.User;
7 | import com.zhuxs.result.exception.ResultException;
8 | import com.zhuxs.result.service.PermissionService;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Service;
11 |
12 | import java.util.List;
13 |
14 | /**
15 | * Created by shusesshou on 2017/9/25.
16 | */
17 | @Service
18 | public class PermissionServiceImpl implements PermissionService {
19 | @Autowired
20 | private UserDao userDao;
21 | @Autowired
22 | private PermissionDao permissionDao;
23 | @Override
24 | public Permission addPermission(Permission permission) {
25 | permissionDao.save(permission);
26 | return null;
27 | }
28 |
29 | @Override
30 | public List listPermissions() {
31 | List permissions = permissionDao.findAll();
32 | return permissions;
33 | }
34 |
35 | @Override
36 | public List getPermissionsByUserId(long userId) {
37 | if(!userDao.exists(userId)){
38 | throw new ResultException();
39 | }
40 | try {
41 | User user = userDao.findOne(userId);
42 | List permissions = user.getPermissions();
43 | return permissions;
44 | }catch (Exception e){
45 | throw new ResultException();
46 | }
47 | }
48 |
49 | @Override
50 | public void delPermissionById(long id) {
51 | permissionDao.delete(id);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/UI/src/views/index/index.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
62 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/dto/RoleDto.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Created by shusesshou on 2017/9/25.
7 | */
8 | public class RoleDto implements Serializable{
9 | private long id;
10 | private String name;
11 | private String desc;
12 |
13 | public RoleDto() {
14 | }
15 |
16 | public RoleDto(String name, String desc) {
17 | this.name = name;
18 | this.desc = desc;
19 | }
20 |
21 | public RoleDto(long id, String name, String desc) {
22 | this.id = id;
23 | this.name = name;
24 | this.desc = desc;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public void setName(String name) {
32 | this.name = name;
33 | }
34 |
35 | public String getDesc() {
36 | return desc;
37 | }
38 |
39 | public void setDesc(String desc) {
40 | this.desc = desc;
41 | }
42 |
43 | public long getId() {
44 | return id;
45 | }
46 |
47 | public void setId(long id) {
48 | this.id = id;
49 | }
50 |
51 | @Override
52 | public boolean equals(Object o) {
53 | if (this == o) return true;
54 | if (o == null || getClass() != o.getClass()) return false;
55 |
56 | RoleDto roleDto = (RoleDto) o;
57 |
58 | if (id != roleDto.id) return false;
59 | if (name != null ? !name.equals(roleDto.name) : roleDto.name != null) return false;
60 | return desc != null ? desc.equals(roleDto.desc) : roleDto.desc == null;
61 | }
62 |
63 | @Override
64 | public int hashCode() {
65 | int result = (int) (id ^ (id >>> 32));
66 | result = 31 * result + (name != null ? name.hashCode() : 0);
67 | result = 31 * result + (desc != null ? desc.hashCode() : 0);
68 | return result;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/UI/src/store/modules/Permission.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by shusesshou on 2017/9/28.
3 | */
4 | import { asyncRouterMap,constantRouterMap } from "../../router"
5 |
6 | /**
7 | * 通过meta.role判断是否与当前用户权限匹配
8 | */
9 | function hasPermission(roles,route) {
10 | if(route.meta && route.meta.roles) {
11 | return roles.some(roles => route.meta.indexOf(roles) >= 0)
12 | } else {
13 | return true
14 | }
15 | }
16 | /**
17 | * 递归过滤异步路由表,返回符合角色权限的路由表
18 | */
19 | function filterAsyncRouter(asyncRouterMap,roles) {
20 | const accessedRouters = asyncRouterMap.filter(route => {
21 | if(hasPermission(roles,route)){
22 | if(route.children && route.children.length){
23 | route.children = filterAsyncRouter(route.children,roles)
24 | }
25 | return true
26 | }
27 | return false
28 | })
29 | return accessedRouters
30 | }
31 |
32 | const permission = {
33 | state: {
34 | routers: constantRouterMap,
35 | addRouters: []
36 | },
37 | mutations: {
38 | SET_ROUTERS: (state, routers) => {
39 | state.addRouters = routers
40 | state.routers = constantRouterMap.concat(routers)
41 | //alert(state.routers.length)
42 | }
43 | },
44 | actions: {
45 | GenerateRoutes({commit},data){
46 | return new Promise(resolve => {
47 | const roles = data.map(item => {
48 | return item.name
49 | })
50 | let accessedRouters
51 |
52 | if(roles.indexOf('Admin') >= 0){
53 | accessedRouters = asyncRouterMap
54 | } else {
55 | accessedRouters = filterAsyncRouter(asyncRouterMap,roles)
56 | }
57 | commit('SET_ROUTERS',accessedRouters)
58 | resolve()
59 | })
60 | }
61 | }
62 | }
63 |
64 | export default permission
65 |
66 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service.impl;
2 |
3 | import com.zhuxs.result.domain.entity.Permission;
4 | import com.zhuxs.result.exception.ResultException;
5 | import com.zhuxs.result.domain.UserDao;
6 | import com.zhuxs.result.domain.entity.Role;
7 | import com.zhuxs.result.domain.entity.User;
8 | import com.zhuxs.result.service.UserService;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.stereotype.Service;
11 |
12 | import java.util.List;
13 |
14 | /**
15 | * Created by shusesshou on 2017/9/25.
16 | */
17 | @Service
18 | public class UserServiceImpl implements UserService {
19 | @Autowired
20 | private UserDao userDao;
21 | @Override
22 | public User addUser(User user) {
23 | user = userDao.save(user);
24 | return user;
25 | }
26 |
27 | @Override
28 | public List listUsers() {
29 | List users = userDao.findAll();
30 | return users;
31 | }
32 |
33 | @Override
34 | public User updateRolesById(long id, List roles) {
35 | if(!userDao.exists(id)){
36 | throw new ResultException();
37 | }
38 | try {
39 | User user = userDao.findOne(id);
40 | user.setRoles(roles);
41 | user = userDao.save(user);
42 | return user;
43 | }catch (Exception e){
44 | //throw e;
45 | throw new ResultException();
46 | }
47 | }
48 |
49 | @Override
50 | public User updatePermissionsById(long id, List permissions) {
51 | if(!userDao.exists(id)){
52 | throw new ResultException();
53 | }
54 | try {
55 | User user = userDao.findOne(id);
56 | user.setPermissions(permissions);
57 | user = userDao.save(user);
58 | return user;
59 | }catch (Exception e){
60 | throw new ResultException();
61 | }
62 | }
63 |
64 | @Override
65 | public void delUserById(long id) {
66 | userDao.delete(id);
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/service/impl/RoleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.service.impl;
2 |
3 | import com.zhuxs.result.domain.UserDao;
4 | import com.zhuxs.result.domain.entity.User;
5 | import com.zhuxs.result.exception.ResultException;
6 | import com.zhuxs.result.domain.RoleDao;
7 | import com.zhuxs.result.domain.entity.Permission;
8 | import com.zhuxs.result.domain.entity.Role;
9 | import com.zhuxs.result.service.RoleService;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.stereotype.Service;
12 |
13 | import java.util.List;
14 |
15 | /**
16 | * Created by shusesshou on 2017/9/25.
17 | */
18 | @Service
19 | public class RoleServiceImpl implements RoleService{
20 | @Autowired
21 | private RoleDao roleDao;
22 | @Autowired
23 | private UserDao userDao;
24 | @Override
25 | public Role addRole(Role role) {
26 | role = roleDao.save(role);
27 | return role;
28 | }
29 |
30 | @Override
31 | public List listRoles() {
32 | List roles = roleDao.findAll();
33 | return roles;
34 | }
35 |
36 | @Override
37 | public List getRolesByUserId(long userId) {
38 | if (!userDao.exists(userId)){
39 | throw new ResultException();
40 | }
41 | try{
42 | User user = userDao.findOne(userId);
43 | List roles = user.getRoles();
44 | return roles;
45 | }catch (Exception e){
46 | throw new ResultException();
47 | }
48 | }
49 |
50 | @Override
51 | public Role updatePermissionsById(long id, List permissions){
52 | if(!roleDao.exists(id)){
53 | throw new ResultException();
54 | }
55 | try {
56 | Role role = roleDao.findOne(id);
57 | role.setPermissions(permissions);
58 | role = roleDao.save(role);
59 | return role;
60 | } catch (Exception e){
61 | throw new ResultException();
62 | }
63 | }
64 |
65 | @Override
66 | public void delRoleById(long id) {
67 | roleDao.delete(id);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/Server/src/main/java/com/zhuxs/result/Handler/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.zhuxs.result.Handler;
2 |
3 | import com.zhuxs.result.exception.ResultException;
4 | import com.zhuxs.result.dto.ErrorDto;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.http.HttpHeaders;
8 | import org.springframework.http.HttpStatus;
9 | import org.springframework.http.MediaType;
10 | import org.springframework.http.ResponseEntity;
11 | import org.springframework.web.bind.annotation.ControllerAdvice;
12 | import org.springframework.web.bind.annotation.ExceptionHandler;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import javax.servlet.http.HttpServletRequest;
16 | import java.net.URI;
17 | import java.net.URISyntaxException;
18 |
19 | /**
20 | * Created by shusesshou on 2017/9/18.
21 | */
22 | @ControllerAdvice
23 | @RestController
24 | public class GlobalExceptionHandler {
25 | private Logger logger = LoggerFactory.getLogger("com.zhuxs.result.GlobalExceptionHandler");
26 |
27 | @ExceptionHandler(value = {ResultException.class})
28 | public ResponseEntity