();
29 |
30 |
31 | @Bean
32 | public SimpleCookie rememberMeCookie() {
33 | SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
34 | simpleCookie.setMaxAge(7 * 24 * 60 * 60);//保存10天
35 | return simpleCookie;
36 | }
37 |
38 | /**
39 | * cookie管理对象;
40 | */
41 | @Bean
42 | public CookieRememberMeManager rememberMeManager() {
43 | logger.debug("ShiroConfiguration.rememberMeManager()");
44 | CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
45 | cookieRememberMeManager.setCookie(rememberMeCookie());
46 | cookieRememberMeManager.setCipherKey(Base64.decode("kPv59vyqzj00x11LXJZTjJ2UHW48jzHN"));
47 | return cookieRememberMeManager;
48 | }
49 |
50 |
51 | @Bean(name = "lifecycleBeanPostProcessor")
52 | public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
53 | return new LifecycleBeanPostProcessor();
54 | }
55 |
56 |
57 | @Bean
58 | public FilterRegistrationBean filterRegistrationBean() {
59 | FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
60 | DelegatingFilterProxy proxy = new DelegatingFilterProxy("shiroFilter");
61 | // 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
62 | proxy.setTargetFilterLifecycle(true);
63 | filterRegistration.setFilter(proxy);
64 |
65 | filterRegistration.setEnabled(true);
66 | //filterRegistration.addUrlPatterns("/*");// 可以自己灵活的定义很多,避免一些根本不需要被Shiro处理的请求被包含进来
67 | return filterRegistration;
68 | }
69 |
70 | @Bean
71 | public MyShiroRealm myShiroRealm() {
72 | MyShiroRealm myShiroRealm = new MyShiroRealm();
73 | return myShiroRealm;
74 | }
75 |
76 | @Bean(name="securityManager")
77 | public DefaultWebSecurityManager securityManager() {
78 | DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
79 | manager.setRealm(myShiroRealm());
80 | manager.setRememberMeManager(rememberMeManager());
81 | manager.setCacheManager(ehCacheManager());
82 | return manager;
83 | }
84 |
85 |
86 | /**
87 | * ShiroFilterFactoryBean 处理拦截资源文件问题。
88 | * 注意:单独一个ShiroFilterFactoryBean配置是或报错的,以为在
89 | * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager
90 | *
91 | * Filter Chain定义说明
92 | * 1、一个URL可以配置多个Filter,使用逗号分隔
93 | * 2、当设置多个过滤器时,全部验证通过,才视为通过
94 | * 3、部分过滤器可指定参数,如perms,roles
95 | */
96 | @Bean(name = "shiroFilter")
97 | public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
98 | logger.debug("ShiroConfigration.getShiroFilterFactoryBean()");
99 | ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
100 | // 必须设置 SecurityManager
101 | shiroFilterFactoryBean.setSecurityManager(securityManager());
102 |
103 | HashMap loginFilter = new HashMap<>();
104 | loginFilter.put("loginFilter", new LoginFilter());
105 | shiroFilterFactoryBean.setFilters(loginFilter);
106 |
107 |
108 | filterChainDefinitionMap.put("/login/submit", "anon");
109 | filterChainDefinitionMap.put("/logout", "anon");
110 | filterChainDefinitionMap.put("/img/**", "anon");
111 | filterChainDefinitionMap.put("/js/**", "anon");
112 | filterChainDefinitionMap.put("/css/**", "anon");
113 |
114 | // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
115 | shiroFilterFactoryBean.setLoginUrl("/login");
116 |
117 | //配置记住我或认证通过可以访问的地址
118 | filterChainDefinitionMap.put("/", "user");
119 | //未授权界面;
120 | shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");
121 | filterChainDefinitionMap.put("/**", "loginFilter");
122 | shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
123 | return shiroFilterFactoryBean;
124 | }
125 |
126 | /**
127 | * shiro缓存管理器;
128 | * 需要注入对应的其它的实体类中:
129 | * 1、安全管理器:securityManager
130 | * 可见securityManager是整个shiro的核心;
131 | *
132 | * @return
133 | */
134 | @Bean
135 | public EhCacheManager ehCacheManager() {
136 | EhCacheManager cacheManager = new EhCacheManager();
137 | cacheManager.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
138 | return cacheManager;
139 | }
140 |
141 |
142 | @Bean
143 | public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
144 | AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
145 | authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
146 | return authorizationAttributeSourceAdvisor;
147 | }
148 |
149 | }
150 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/config/Swagger2.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | import springfox.documentation.builders.ApiInfoBuilder;
7 | import springfox.documentation.builders.PathSelectors;
8 | import springfox.documentation.builders.RequestHandlerSelectors;
9 | import springfox.documentation.service.ApiInfo;
10 | import springfox.documentation.spi.DocumentationType;
11 | import springfox.documentation.spring.web.plugins.Docket;
12 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
13 |
14 | @Configuration
15 | @EnableSwagger2
16 | public class Swagger2 {
17 |
18 | @Bean
19 | public Docket createRestApi() {
20 | return new Docket(DocumentationType.SWAGGER_2)
21 | .apiInfo(apiInfo())
22 | .select()
23 | .apis(RequestHandlerSelectors
24 | .basePackage("com.onecoderspace.base.controller"))
25 | .paths(PathSelectors.any()).build();
26 | }
27 |
28 | private ApiInfo apiInfo() {
29 | return new ApiInfoBuilder()
30 | .title("基础项目接口API")
31 | .description("基础项目接口API")
32 | .version("1.0").build();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/config/WebConfig.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.config;
2 |
3 | import java.text.SimpleDateFormat;
4 | import java.util.Date;
5 | import java.util.Map;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.beans.factory.annotation.Value;
9 | import org.springframework.boot.actuate.autoconfigure.ExportMetricWriter;
10 | import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics;
11 | import org.springframework.boot.actuate.endpoint.PublicMetrics;
12 | import org.springframework.boot.actuate.metrics.aggregate.AggregateMetricReader;
13 | import org.springframework.boot.actuate.metrics.export.MetricExportProperties;
14 | import org.springframework.boot.actuate.metrics.reader.MetricReader;
15 | import org.springframework.boot.actuate.metrics.repository.redis.RedisMetricRepository;
16 | import org.springframework.boot.actuate.metrics.writer.MetricWriter;
17 | import org.springframework.boot.web.servlet.FilterRegistrationBean;
18 | import org.springframework.context.annotation.Bean;
19 | import org.springframework.context.annotation.Configuration;
20 | import org.springframework.core.convert.converter.Converter;
21 | import org.springframework.data.redis.connection.RedisConnectionFactory;
22 | import org.springframework.http.HttpHeaders;
23 | import org.springframework.web.servlet.config.annotation.CorsRegistry;
24 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
25 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
26 |
27 | import com.google.common.collect.Maps;
28 | import com.onecoderspace.base.filter.CsrfFilter;
29 | import com.onecoderspace.base.filter.ShiroSessionFilter;
30 | import com.onecoderspace.base.filter.XssFilter;
31 |
32 | @Configuration
33 | public class WebConfig {
34 |
35 | @Autowired
36 | private RedisConnectionFactory redisConnectionFactory;
37 |
38 | @Value("${server.session.timeout}")
39 | private String serverSessionTimeout;
40 |
41 | @Value("${csrf.filter.open}")
42 | private String isCsrfFilterOpen;
43 |
44 | @Bean
45 | @ExportMetricWriter
46 | MetricWriter metricWriter(MetricExportProperties export) {
47 | return new RedisMetricRepository(redisConnectionFactory, export
48 | .getRedis().getPrefix(), export.getRedis().getKey());
49 | }
50 |
51 | @Autowired
52 | private MetricExportProperties export;
53 |
54 | @Bean
55 | public PublicMetrics metricsAggregate() {
56 | return new MetricReaderPublicMetrics(aggregatesMetricReader());
57 | }
58 |
59 | private MetricReader globalMetricsForAggregation() {
60 | return new RedisMetricRepository(this.redisConnectionFactory,
61 | this.export.getRedis().getAggregatePrefix(), this.export
62 | .getRedis().getKey());
63 | }
64 |
65 | private MetricReader aggregatesMetricReader() {
66 | AggregateMetricReader repository = new AggregateMetricReader(
67 | globalMetricsForAggregation());
68 | return repository;
69 | }
70 |
71 | /**
72 | * 参数绑定时将String时间转换为Date
73 | * @author yangwk
74 | * @time 2017年7月26日 下午4:53:19
75 | * @return
76 | */
77 | @Bean
78 | public Converter stringDateConvert() {
79 | return new Converter() {
80 | @Override
81 | public Date convert(String source) {
82 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
83 | Date date = null;
84 | try {
85 | date = sdf.parse((String) source);
86 | } catch (Exception e) {
87 | e.printStackTrace();
88 | }
89 | return date;
90 | }
91 | };
92 | }
93 |
94 | /**
95 | * 解决跨域调用问题
96 | */
97 | @Bean
98 | public WebMvcConfigurer corsConfigurer() {
99 | return new WebMvcConfigurerAdapter() {
100 | @Override
101 | public void addCorsMappings(CorsRegistry registry) {
102 | registry.addMapping("/**").allowedOrigins("*")
103 | .allowedMethods("*").allowedHeaders("*")
104 | .allowCredentials(true)
105 | .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
106 | }
107 | };
108 | }
109 |
110 | /**
111 | * xss过滤拦截器
112 | */
113 | @Bean
114 | public FilterRegistrationBean xssFilterRegistrationBean() {
115 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
116 | filterRegistrationBean.setFilter(new XssFilter());
117 | filterRegistrationBean.setOrder(1);
118 | filterRegistrationBean.setEnabled(true);
119 | filterRegistrationBean.addUrlPatterns("/*");
120 | Map initParameters = Maps.newHashMap();
121 | initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
122 | initParameters.put("isIncludeRichText", "true");
123 | filterRegistrationBean.setInitParameters(initParameters);
124 | return filterRegistrationBean;
125 | }
126 |
127 | /**
128 | * csrf过滤拦截器 只处理post请求
129 | */
130 | @Bean
131 | public FilterRegistrationBean csrfFilterRegistrationBean() {
132 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
133 | filterRegistrationBean.setFilter(new CsrfFilter());
134 | filterRegistrationBean.setOrder(2);
135 | filterRegistrationBean.setEnabled(true);
136 | filterRegistrationBean.addUrlPatterns("/*");
137 | Map initParameters = Maps.newHashMap();
138 | initParameters.put("excludes", "/login/*");
139 | initParameters.put("isOpen", isCsrfFilterOpen);
140 | filterRegistrationBean.setInitParameters(initParameters);
141 | return filterRegistrationBean;
142 | }
143 |
144 | @Bean
145 | public FilterRegistrationBean shiroSessionFilterRegistrationBean() {
146 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
147 | filterRegistrationBean.setFilter(new ShiroSessionFilter());
148 | filterRegistrationBean.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
149 | filterRegistrationBean.setEnabled(true);
150 | filterRegistrationBean.addUrlPatterns("/*");
151 | Map initParameters = Maps.newHashMap();
152 | initParameters.put("serverSessionTimeout", serverSessionTimeout);
153 | initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
154 | filterRegistrationBean.setInitParameters(initParameters);
155 | return filterRegistrationBean;
156 | }
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiImplicitParams;
6 | import io.swagger.annotations.ApiOperation;
7 |
8 | import java.util.Map;
9 | import java.util.UUID;
10 |
11 | import javax.servlet.http.HttpServletRequest;
12 | import javax.servlet.http.HttpServletResponse;
13 |
14 | import org.apache.commons.lang3.math.NumberUtils;
15 | import org.apache.shiro.SecurityUtils;
16 | import org.apache.shiro.authc.AuthenticationException;
17 | import org.apache.shiro.authc.ExcessiveAttemptsException;
18 | import org.apache.shiro.authc.IncorrectCredentialsException;
19 | import org.apache.shiro.authc.LockedAccountException;
20 | import org.apache.shiro.authc.UnknownAccountException;
21 | import org.apache.shiro.authc.UsernamePasswordToken;
22 | import org.apache.shiro.subject.Subject;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 | import org.springframework.beans.factory.annotation.Autowired;
26 | import org.springframework.beans.factory.annotation.Value;
27 | import org.springframework.web.bind.annotation.RequestMapping;
28 | import org.springframework.web.bind.annotation.RequestMethod;
29 | import org.springframework.web.bind.annotation.RequestParam;
30 | import org.springframework.web.bind.annotation.RestController;
31 |
32 | import com.google.common.collect.Maps;
33 | import com.onecoderspace.base.domain.User;
34 | import com.onecoderspace.base.service.UserService;
35 | import com.onecoderspace.base.util.SaltMD5Util;
36 |
37 | @Api(value="用户登录",tags={"用户登录"})
38 | @RestController
39 | public class LoginController {
40 | private static Logger logger = LoggerFactory.getLogger(LoginController.class);
41 |
42 | @Value("${server.session.timeout}")
43 | private String serverSessionTimeout;
44 |
45 | /**
46 | * 用户登录接口 通过用户名和密码进行登录
47 | */
48 | @ApiOperation(value = "用户登录接口 通过用户名和密码进行登录", notes = "用户登录接口 通过用户名和密码进行登录")
49 | @ApiImplicitParams({
50 | @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"),
51 | @ApiImplicitParam(paramType = "query", name = "pwd", value = "密码", required = true, dataType = "String"),
52 | @ApiImplicitParam(paramType = "query", name = "autoLogin", value = "自动登录", required = true, dataType = "boolean")})
53 | @RequestMapping(value = "/login/submit",method={RequestMethod.GET,RequestMethod.POST})
54 | public Map subm(HttpServletRequest request,HttpServletResponse response,
55 | String username,String pwd,@RequestParam(value = "autoLogin", defaultValue = "false") boolean autoLogin) {
56 | Map map = Maps.newLinkedHashMap();
57 | Subject currentUser = SecurityUtils.getSubject();
58 | User user = userService.findByUsername(username);
59 | if (user == null) {
60 | map.put("code", "-1");
61 | map.put("description", "账号不存在");
62 | return map;
63 | }
64 | if (user.getEnable() == 0) { //账号被禁用
65 | map.put("code", "-1");
66 | map.put("description", "账号已被禁用");
67 | return map;
68 | }
69 |
70 | String salt = user.getSalt();
71 | UsernamePasswordToken token = null;
72 | Integer userId = user.getId();
73 | token = new UsernamePasswordToken(userId.toString(),SaltMD5Util.encode(pwd, salt));
74 | token.setRememberMe(autoLogin);
75 |
76 | loginValid(map, currentUser, token);
77 |
78 | // 验证是否登录成功
79 | if (currentUser.isAuthenticated()) {
80 | map.put("code","1");
81 | map.put("description", "ok");
82 | map.put("id", String.valueOf(userId));
83 | map.put("username", user.getUsername());
84 | map.put("name", user.getName());
85 | String uuidToken = UUID.randomUUID().toString();
86 | map.put("token", uuidToken);
87 |
88 | currentUser.getSession().setTimeout(NumberUtils.toLong(serverSessionTimeout, 1800)*1000);
89 | request.getSession().setAttribute("token",uuidToken );
90 | } else {
91 | map.put("code", "-1");
92 | token.clear();
93 | }
94 | return map;
95 | }
96 |
97 | @RequestMapping(value="test/set",method=RequestMethod.GET)
98 | public String testSet(HttpServletRequest request) {
99 | request.getSession().setAttribute("test", "test");
100 | return "success";
101 | }
102 |
103 | @RequestMapping(value="test/get",method=RequestMethod.GET)
104 | public String testGet(HttpServletRequest request) {
105 | String value = (String) request.getSession().getAttribute("test");
106 | return value == null ? "null" : value;
107 | }
108 |
109 | @RequestMapping(value="logout",method=RequestMethod.GET)
110 | public Map logout() {
111 | Map map = Maps.newLinkedHashMap();
112 | Subject currentUser = SecurityUtils.getSubject();
113 | currentUser.logout();
114 | map.put("code", "logout");
115 | return map;
116 | }
117 |
118 | @RequestMapping(value="unauth",method=RequestMethod.GET)
119 | public Map unauth() {
120 | Map map = Maps.newLinkedHashMap();
121 | map.put("code", "403");
122 | map.put("msg", "你没有访问权限");
123 | return map;
124 | }
125 |
126 | private boolean loginValid(Map map,Subject currentUser, UsernamePasswordToken token) {
127 | String username = null;
128 | if (token != null) {
129 | username = (String) token.getPrincipal();
130 | }
131 |
132 | try {
133 | // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
134 | // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
135 | // 所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
136 | currentUser.login(token);
137 | return true;
138 | } catch (UnknownAccountException | IncorrectCredentialsException ex) {
139 | map.put("description", "账号或密码错误");
140 | } catch (LockedAccountException lae) {
141 | map.put("description","账户已锁定");
142 | } catch (ExcessiveAttemptsException eae) {
143 | map.put("description", "错误次数过多");
144 | } catch (AuthenticationException ae) {
145 | // 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
146 | map.put("description", "登录失败");
147 | logger.warn(String.format("对用户[%s]进行登录验证..验证未通过", username),ae);
148 | }
149 | return false;
150 | }
151 |
152 | @Autowired
153 | private UserService userService;
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/UploadController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiOperation;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 | import java.util.HashSet;
10 | import java.util.List;
11 | import java.util.Set;
12 | import java.util.UUID;
13 |
14 | import org.jsoup.helper.StringUtil;
15 | import org.slf4j.Logger;
16 | import org.slf4j.LoggerFactory;
17 | import org.springframework.beans.factory.annotation.Value;
18 | import org.springframework.web.bind.annotation.RequestMapping;
19 | import org.springframework.web.bind.annotation.RequestMethod;
20 | import org.springframework.web.bind.annotation.RequestParam;
21 | import org.springframework.web.bind.annotation.RestController;
22 | import org.springframework.web.multipart.MultipartFile;
23 |
24 | import com.google.common.collect.Lists;
25 | import com.onecoderspace.base.util.DateUtils;
26 | import com.onecoderspace.base.util.RandomUtils;
27 |
28 | @Api(value = "上传图片", tags = { "上传图片" })
29 | @RestController
30 | @RequestMapping("/upload")
31 | public class UploadController {
32 |
33 | private static Logger logger = LoggerFactory.getLogger(UploadController.class);
34 |
35 | @Value("${upload.file.path}")
36 | private String uploadFilePath;//值类似于/var/www/html/upload
37 |
38 | @Value("${upload.file.path.project.name}")
39 | private String projectName; //值类似于dmp
40 |
41 | /**
42 | * 上传图片
43 | * @author yangwk
44 | * @time 2017年7月28日 下午3:42:41
45 | * @param files
46 | * @return
47 | */
48 | @ApiOperation(value = "上传图片", notes = "上传图片")
49 | @ApiImplicitParam(paramType = "query", name = "files", value = "图片上传", required = true, dataType = "MultipartFile")
50 | @RequestMapping(value = "/img", method = RequestMethod.POST)
51 | public List img(@RequestParam("file") MultipartFile[] files) {
52 | String savePath = String.format("/%s/img/%s/%s",projectName, RandomUtils.randomNum(2),RandomUtils.randomNum(2));
53 | List paths = Lists.newArrayList();
54 | for (MultipartFile file : files) {
55 | String name = file.getOriginalFilename();
56 | String suffix = "";
57 | if(suffix.lastIndexOf(".") != -1){
58 | suffix = name.substring(name.lastIndexOf("."));
59 | }
60 | if (StringUtil.isBlank(suffix)) {
61 | suffix = ".jpg";
62 | }
63 | name = String.format("%s-%s%s",DateUtils.getCurrentTime("yyyyMMdd"), getRandomUniqName(), suffix);
64 | boolean success = saveFile(savePath, name, file);
65 | if (success) {
66 | paths.add(String.format("%s/%s", savePath, name));
67 | } else {
68 | paths.add("");
69 | }
70 | }
71 | return paths;
72 | }
73 |
74 | /**
75 | * 上传图片
76 | * @author yangwk
77 | * @time 2017年7月28日 下午3:42:41
78 | * @param files
79 | * @return
80 | */
81 | @ApiOperation(value = "上传文件", notes = "上传图片")
82 | @ApiImplicitParam(paramType = "query", name = "files", value = "图片上传", required = true, dataType = "MultipartFile")
83 | @RequestMapping(value = "/file", method = RequestMethod.POST)
84 | public List file(@RequestParam("file") MultipartFile[] files) {
85 | String savePath = String.format("/%s/file/%s/%s",projectName, RandomUtils.randomNum(2),RandomUtils.randomNum(2));
86 | List paths = Lists.newArrayList();
87 | for (MultipartFile file : files) {
88 | String name = file.getOriginalFilename();
89 | String suffix = "";
90 | if(suffix.lastIndexOf(".") != -1){
91 | suffix = name.substring(name.lastIndexOf("."));
92 | }
93 | name = String.format("%s-%s%s",DateUtils.getCurrentTime("yyyyMMdd"),getRandomUniqName(), suffix);
94 | boolean success = saveFile(savePath, name, file);
95 | if (success) {
96 | paths.add(String.format("%s/%s", savePath, name));
97 | } else {
98 | paths.add("");
99 | }
100 | }
101 | return paths;
102 | }
103 |
104 | /**
105 | * 获取随机值:10w以内基本可保证唯一,但非绝对不唯一
106 | * @author yangwk
107 | * @time 2017年8月16日 下午3:18:18
108 | * @return
109 | */
110 | private static String getRandomUniqName(){
111 | String prefix = RandomUtils.randomNum(1);//最大支持1-9个集群机器部署
112 | int hashCodeV = UUID.randomUUID().toString().hashCode();
113 | if(hashCodeV < 0) {//有可能是负数
114 | hashCodeV = - hashCodeV;
115 | }
116 | // 0 代表前面补充0
117 | // 4 代表长度为4
118 | // d 代表参数为正数型
119 | return String.format("%s%015d",prefix, hashCodeV);
120 | }
121 |
122 | public static void main(String[] args) {
123 | Set set = new HashSet(100000);
124 | for(int i=0;i<100;i++){
125 | String value = getRandomUniqName();
126 | if(set.contains(value)){
127 | System.err.println(value);
128 | }
129 | set.add(value);
130 | }
131 | }
132 |
133 | private boolean saveFile(String savePath, String name, MultipartFile file) {
134 | String path = String.format("%s%s", uploadFilePath, savePath);
135 | File dir = new File(path);
136 | if (!dir.exists()) {
137 | dir.mkdirs();
138 | }
139 | // 保存文件
140 | try {
141 | file.transferTo(new File(String.format("%s/%s", path, name)));
142 | } catch (IOException e) {
143 | logger.error("save file due to error", e);
144 | return false;
145 | }
146 | return true;
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiImplicitParams;
6 | import io.swagger.annotations.ApiOperation;
7 |
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.apache.shiro.SecurityUtils;
10 | import org.apache.shiro.authz.annotation.RequiresPermissions;
11 | import org.apache.shiro.subject.Subject;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.web.bind.annotation.RequestMapping;
14 | import org.springframework.web.bind.annotation.RequestMethod;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.onecoderspace.base.domain.User;
18 | import com.onecoderspace.base.service.UserService;
19 | import com.onecoderspace.base.util.Return;
20 | import com.onecoderspace.base.util.SaltMD5Util;
21 |
22 | @Api(value="用户管理",tags={"用户管理"})
23 | @RestController
24 | @RequestMapping("/user")
25 | public class UserController {
26 |
27 | @ApiOperation(value="获取用户详细信息", notes="根据ID查找用户")
28 | @ApiImplicitParam(paramType="query",name = "id", value = "用户ID", required = true,dataType="int")
29 | @RequiresPermissions(value={"user:get"})
30 | @RequestMapping(value="/get",method=RequestMethod.GET)
31 | public User get(int id){
32 | User entity = userService.findById(id);
33 | entity.setPwd(null);
34 | entity.setSalt(null);
35 | return entity;
36 | }
37 |
38 | @ApiOperation(value="修改密码", notes="修改密码")
39 | @ApiImplicitParams({
40 | @ApiImplicitParam(paramType = "query", name = "oldPwd", value = "旧密码", required = true, dataType = "String"),
41 | @ApiImplicitParam(paramType = "query", name = "pwd", value = "新密码", required = true, dataType = "String"),
42 | @ApiImplicitParam(paramType = "query", name = "confirmPwd", value = "新密码(确认)", required = true, dataType = "String")})
43 | @RequiresPermissions(value={"user:reset-pwd"})
44 | @RequestMapping(value="/reset-pwd",method=RequestMethod.POST)
45 | public Return resetPwd(String oldPwd,String pwd,String confirmPwd){
46 | if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(pwd)
47 | || StringUtils.isBlank(confirmPwd) || !pwd.equals(confirmPwd)) {
48 | return Return.fail("非法参数");
49 | }
50 |
51 | Subject currentUser = SecurityUtils.getSubject();
52 | Integer userId=(Integer) currentUser.getPrincipal();
53 | User entity = userService.findById(userId);
54 | if(!entity.getPwd().equals(SaltMD5Util.encode(oldPwd, entity.getSalt()))){
55 | return Return.fail("原始密码错误");
56 | }
57 | return userService.changePwd(entity,pwd);
58 | }
59 |
60 | @ApiOperation(value="返回当前用户", notes="返回当前用户")
61 | @RequiresPermissions(value={"user:current"})
62 | @RequestMapping(value="/current",method=RequestMethod.GET)
63 | public User current(){
64 | //得到当前用户
65 | Subject currentUser = SecurityUtils.getSubject();
66 | Integer userId=(Integer) currentUser.getPrincipal();
67 | User entity = userService.findById(userId);
68 | entity.setPwd(null);
69 | entity.setSalt(null);
70 | return entity;
71 | }
72 |
73 | @Autowired
74 | private UserService userService;
75 |
76 | }
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/admin/AdminUserController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller.admin;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiImplicitParams;
6 | import io.swagger.annotations.ApiOperation;
7 |
8 | import java.sql.Timestamp;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | import org.apache.shiro.authz.annotation.RequiresPermissions;
13 | import org.springframework.beans.factory.annotation.Autowired;
14 | import org.springframework.data.domain.Page;
15 | import org.springframework.data.domain.PageRequest;
16 | import org.springframework.data.domain.Sort;
17 | import org.springframework.data.domain.Sort.Direction;
18 | import org.springframework.web.bind.annotation.RequestMapping;
19 | import org.springframework.web.bind.annotation.RequestMethod;
20 | import org.springframework.web.bind.annotation.RequestParam;
21 | import org.springframework.web.bind.annotation.RestController;
22 |
23 | import com.google.common.collect.Maps;
24 | import com.onecoderspace.base.domain.User;
25 | import com.onecoderspace.base.domain.UserRole;
26 | import com.onecoderspace.base.service.UserRoleService;
27 | import com.onecoderspace.base.service.UserService;
28 | import com.onecoderspace.base.util.Constants;
29 | import com.onecoderspace.base.util.LoginSessionHelper;
30 | import com.onecoderspace.base.util.Return;
31 | import com.onecoderspace.base.util.SaltMD5Util;
32 |
33 | @Api(value = "运营接口 用户", tags = { "运营接口 用户" })
34 | @RestController("adminUserController")
35 | @RequestMapping(value="/admin/user")
36 | public class AdminUserController {
37 |
38 | @ApiOperation(value = "分页获取用户数据", notes = "根据用户名获取用户姓名获取用户数据")
39 | @ApiImplicitParams({
40 | @ApiImplicitParam(paramType = "query", name = "type", value = "用户类别 0普通用户 1运营人员", required = true, dataType = "String"),
41 | @ApiImplicitParam(paramType = "query", name = "status", value = "账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过", required = true, dataType = "String"),
42 | @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"),
43 | @ApiImplicitParam(paramType = "query", name = "name", value = "用户姓名", required = true, dataType = "String"),
44 | @ApiImplicitParam(paramType = "query", name = "page", value = "分页,页码从0开始", required = true, dataType = "int"),
45 | @ApiImplicitParam(paramType = "query", name = "size", value = "每一页大小", required = true, dataType = "int") })
46 | @RequiresPermissions(value = { "admin:user:list" })
47 | @RequestMapping(value = "/list", method = RequestMethod.GET)
48 | public Page list(String type, String status, String username, String name,
49 | @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) {
50 | Map params = Maps.newHashMap();
51 | params.put("type", type);
52 | params.put("status", status);
53 | params.put("username", username);
54 | params.put("name", name);
55 | Page rs = this.userService.listByPage(params,new PageRequest(page, size, new Sort(Direction.DESC, "updateTime")));
56 |
57 | /*//或者使用service内的公共方法也可以
58 | Map params2 = Maps.newHashMap();
59 | params.put("type", type);
60 | params.put("status", status);
61 | params.put("username:like", username);
62 | params.put("name:like", name);
63 | Page rs2 = this.userService.list(params2, new PageRequest(page, size, new Sort(Direction.DESC, "updateTime")));
64 | */
65 | for (User user : rs.getContent()) {
66 | user.setPwd(null);
67 | user.setSalt(null);
68 | }
69 | return rs;
70 | }
71 |
72 | @ApiOperation(value = "用户审核时的全部信息", notes = "用户审核时的全部信息:用户信息、公司信息、公司资质信息,根据id查询用户")
73 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "int")
74 | @RequiresPermissions(value = { "admin:user:audit-info" })
75 | @RequestMapping(value = "/audit-info", method = RequestMethod.GET)
76 | public Map auditInfo(int id) {
77 | Map map = Maps.newHashMap();
78 | User entity = userService.findById(id);
79 | entity.setPwd(null);
80 | entity.setSalt(null);
81 | map.put("user", entity);
82 | return map;
83 | }
84 |
85 | @ApiOperation(value = "审核用户账号", notes = "审核用户账号")
86 | @ApiImplicitParams({
87 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "int"),
88 | @ApiImplicitParam(paramType = "query", name = "value", value = "value 0未通过 1通过", required = true, dataType = "int"),
89 | @ApiImplicitParam(paramType = "query", name = "msg", value = "不通过原因", required = true, dataType = "String") })
90 | @RequiresPermissions(value = { "admin:user:audit" })
91 | @RequestMapping(value = "/audit", method = RequestMethod.GET)
92 | public Return audit(int id, int value, String msg) {
93 | User entity = userService.findById(id);
94 | if (entity == null) {
95 | return Return.fail("用户已不存在");
96 | }
97 | if (entity.getStatus() != User.STATUS_WAIT_AUDIT) {
98 | return Return.fail("用户不是待审核状态");
99 | }
100 | return userService.doAudit(entity, value, msg);
101 | }
102 |
103 | @ApiOperation(value = "保存用户信息", notes = "保存用户信息")
104 | @ApiImplicitParam(paramType = "query", name = "user", value = "用户实体", required = true, dataType = "user")
105 | @RequiresPermissions(value = { "admin:user:save" })
106 | @RequestMapping(value = "/save", method = RequestMethod.GET)
107 | public Return save(User user) {
108 | int currentUid = LoginSessionHelper.getCurrentUserId();
109 | if (user.getId() != null && user.getId() != 0) {
110 | User old = userService.findById(user.getId());
111 | if (old == null) {
112 | return Return.fail("信息已不存在");
113 | }
114 | user.setUsername(old.getUsername());
115 | user.setPwd(old.getPwd());
116 | user.setSalt(old.getSalt());
117 | user.setStatus(old.getStatus());
118 | user.setType(old.getType());
119 | user.setDel(old.getDel());
120 | user.setRegisterTime(old.getRegisterTime());
121 | user.setEnable(old.getEnable());
122 |
123 | } else {
124 | user.setDel(Constants.DEL_NO);
125 | user.setStatus(User.STATUS_UNAUDIT);
126 | user.setEnable(1);
127 | String salt = SaltMD5Util.getSalt();
128 | String pwd = SaltMD5Util.encode(user.getPwd(), salt);
129 | user.setPwd(pwd);
130 | user.setSalt(salt);
131 | user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
132 |
133 | }
134 | user.setUpdator(currentUid);
135 | user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
136 |
137 | Return re = this.userService.saveUser(user);
138 | return re;
139 | }
140 |
141 | @ApiOperation(value = "标记删除", notes = "标记删除")
142 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id",dataType = "int")
143 | @RequiresPermissions(value = { "admin:user:delete" })
144 | @RequestMapping(value="/delete",method=RequestMethod.GET)
145 | public Return delete(int id) {
146 | User user = this.userService.findById(id);
147 | user.setDel(Constants.DEL_YES);
148 | userService.save(user);
149 | return Return.success();
150 | }
151 |
152 | @ApiOperation(value = "用户拥有的角色", notes = " 用户拥有的角色")
153 | @ApiImplicitParam(paramType = "query", name = "uid", value = "用户uid", required = true, dataType = "int")
154 | @RequiresPermissions(value = { "admin:user:role:list" })
155 | @RequestMapping(value="/role/list",method=RequestMethod.GET)
156 | public List roleList(int uid) {
157 | List userRoles = userRoleService.findByUserId(uid);
158 | return userRoles;
159 | }
160 |
161 | @ApiOperation(value = "设置用户角色", notes = "设置用户角色")
162 | @ApiImplicitParams({
163 | @ApiImplicitParam(paramType = "query", name = "uid", value = "用户uid", required = true, dataType = "int"),
164 | @ApiImplicitParam(paramType = "query", name = "roleids", value = "角色id", required = true, dataType = "String")
165 | })
166 | @RequiresPermissions(value = { "admin:user:role:set" })
167 | @RequestMapping(value="/role/set",method=RequestMethod.POST)
168 | public Return roleSet(int uid, String roleIds) {
169 | return userService.doSetRoles(uid, roleIds);
170 | }
171 |
172 | @Autowired
173 | private UserService userService;
174 |
175 | @Autowired
176 | private UserRoleService userRoleService;
177 | }
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/admin/PermissionController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller.admin;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiOperation;
6 |
7 | import org.apache.shiro.authz.annotation.RequiresPermissions;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.data.domain.Sort;
10 | import org.springframework.data.domain.Sort.Direction;
11 | import org.springframework.web.bind.annotation.RequestMapping;
12 | import org.springframework.web.bind.annotation.RequestMethod;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import com.onecoderspace.base.domain.Permission;
16 | import com.onecoderspace.base.service.PermissionService;
17 | import com.onecoderspace.base.util.Return;
18 |
19 |
20 | @Api(value = "运营接口 权限", tags = { "运营接口 权限" })
21 | @RestController
22 | @RequestMapping("/admin/permission")
23 | public class PermissionController {
24 |
25 | @ApiOperation(value = "获取所有权限", notes = "获取所有权限")
26 | @RequiresPermissions(value={"admin:permission:list"})
27 | @RequestMapping(value="/list",method=RequestMethod.GET)
28 | public Iterable list(){
29 | Iterable list = this.permissionService.findAll(new Sort(Direction.ASC, "weight","id"));
30 | return list;
31 | }
32 |
33 | @ApiOperation(value = "新增/修改 权限", notes = "保存 新增/修改的 权限")
34 | @ApiImplicitParam(paramType = "query", name = "permission", value = "菜单操作权限实体", required = true, dataType = "Permission")
35 | @RequiresPermissions(value={"admin:permission:save"})
36 | @RequestMapping(value="/save",method=RequestMethod.GET)
37 | public Return save(Permission permission){
38 | this.permissionService.save(permission);
39 | return Return.success();
40 | }
41 |
42 |
43 | @ApiOperation(value = "删除 权限", notes = "根据id删除权限")
44 | @ApiImplicitParam(paramType = "query", name = "id", value = "权限id", required = true, dataType = "int")
45 | @RequiresPermissions(value={"admin:permission:delete"})
46 | @RequestMapping(value="/delete",method=RequestMethod.GET)
47 | public Return delete(int id){
48 | this.permissionService.del(id);
49 | return Return.success();
50 | }
51 |
52 | @ApiOperation(value = "获取权限", notes = "根据id查询权限")
53 | @ApiImplicitParam(paramType = "query", name = "id", value = "权限id", required = true, dataType = "int")
54 | @RequiresPermissions(value={"admin:permission:get"})
55 | @RequestMapping(value="/get",method=RequestMethod.GET)
56 | public Permission get(int id){
57 | Permission entity = permissionService.findById(id);
58 | return entity;
59 | }
60 |
61 | @Autowired
62 | private PermissionService permissionService;
63 |
64 | }
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/controller/admin/RoleController.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.controller.admin;
2 |
3 | import io.swagger.annotations.Api;
4 | import io.swagger.annotations.ApiImplicitParam;
5 | import io.swagger.annotations.ApiImplicitParams;
6 | import io.swagger.annotations.ApiOperation;
7 |
8 | import java.util.List;
9 |
10 | import org.apache.shiro.authz.annotation.RequiresPermissions;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.data.domain.Page;
13 | import org.springframework.data.domain.PageRequest;
14 | import org.springframework.data.domain.Sort;
15 | import org.springframework.data.domain.Sort.Direction;
16 | import org.springframework.web.bind.annotation.RequestMapping;
17 | import org.springframework.web.bind.annotation.RequestMethod;
18 | import org.springframework.web.bind.annotation.RequestParam;
19 | import org.springframework.web.bind.annotation.RestController;
20 |
21 | import com.onecoderspace.base.domain.Role;
22 | import com.onecoderspace.base.domain.RolePermission;
23 | import com.onecoderspace.base.service.RolePermissionService;
24 | import com.onecoderspace.base.service.RoleService;
25 | import com.onecoderspace.base.util.Return;
26 |
27 | @Api(value="角色管理",tags={"运营接口 角色"})
28 | @RestController
29 | @RequestMapping("/admin/role")
30 | public class RoleController {
31 |
32 | @ApiOperation(value="分页查询",notes="分页查询")
33 | @ApiImplicitParams({
34 | @ApiImplicitParam(paramType="query",name="page",value="分页,页码从0开始",required=true,dataType="int"),
35 | @ApiImplicitParam(paramType="query",name="size",value="每一页大小",required=true,dataType="int")}
36 | )
37 | @RequiresPermissions(value={"admin:permission:list"})
38 | @RequestMapping(value="/list",method=RequestMethod.GET)
39 | public Page list(String name, @RequestParam(defaultValue = "0") int page,
40 | @RequestParam(defaultValue = "10") int size) {
41 | Page rs = this.roleService.listByPage(name, new PageRequest(page, size, new Sort(Direction.DESC, "id")));
42 | return rs;
43 | }
44 |
45 | @ApiOperation(value="新增&修改",notes="新增&修改")
46 | @ApiImplicitParam(paramType="query",name="role",value="角色",dataType="Role")
47 | @RequiresPermissions(value={"admin:permission:save"})
48 | @RequestMapping(value="/save",method=RequestMethod.GET)
49 | public Return save(Role role) {
50 | this.roleService.save(role);
51 | return Return.success();
52 | }
53 |
54 | @ApiOperation(value="查询",notes="根据id查询")
55 | @ApiImplicitParam(paramType="query",name="id",value="角色id",required=true,dataType="int")
56 | @RequiresPermissions(value={"admin:permission:get"})
57 | @RequestMapping(value="/get",method=RequestMethod.GET)
58 | public Role get(int id) {
59 | Role entity = roleService.findById(id);
60 | return entity;
61 | }
62 |
63 | @ApiOperation(value="删除",notes="根据id删除")
64 | @ApiImplicitParam(paramType="query",name="id",value="角色id",required=true,dataType="int")
65 | @RequiresPermissions(value={"admin:permission:delete"})
66 | @RequestMapping("/delete")
67 | public Return delete(int id){
68 | this.roleService.del(id);
69 | return Return.success();
70 | }
71 |
72 | @ApiOperation(value = "角色拥有权限", notes = "根据id查询用户拥有的权限")
73 | @ApiImplicitParam(paramType="query",name="roleId",value="角色id",required=true,dataType="int")
74 | @RequiresPermissions(value={"admin:permission:permission:list"})
75 | @RequestMapping(value="/permission/list",method=RequestMethod.GET)
76 | public List permissionList(int roleId) {
77 | List rolePermissions = rolePermissionService.findByRoleId(roleId);
78 | return rolePermissions;
79 | }
80 |
81 | @ApiOperation(value = "设置角色拥有的权限", notes = "根据角色id设置权限")
82 | @ApiImplicitParams({
83 | @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", required = true, dataType = "int"),
84 | @ApiImplicitParam(paramType = "query", name = "permissionIds", value = "权限ID,多个权限ID用英文逗号隔开", required = true, dataType = "int") })
85 | @RequiresPermissions(value = { "admin:permission:permission:set" })
86 | @RequestMapping(value = "/permission/set", method = RequestMethod.POST)
87 | public Return permissionSet(int roleId, String permissionIds) {
88 | return roleService.doSetPermissions(roleId, permissionIds);
89 | }
90 |
91 | @Autowired
92 | private RoleService roleService;
93 |
94 | @Autowired
95 | private RolePermissionService rolePermissionService;
96 | }
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/dao/PermissionDao.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.dao;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import org.springframework.data.jpa.repository.Query;
7 |
8 | import com.onecoderspace.base.component.common.dao.BaseDao;
9 | import com.onecoderspace.base.domain.Permission;
10 |
11 | public interface PermissionDao extends BaseDao{
12 |
13 | @Query(value="select perm.* from role_permission rp left join permission perm on rp.permission_id=perm.id where rp.role_id in(?1);",nativeQuery=true)
14 | List listByRoleIds(Set roles);
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/dao/RoleDao.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.dao;
2 |
3 | import java.util.Set;
4 |
5 | import com.onecoderspace.base.component.common.dao.BaseDao;
6 | import com.onecoderspace.base.domain.Role;
7 |
8 | public interface RoleDao extends BaseDao{
9 |
10 | Role findByCode(String code);
11 |
12 | Set findByIdIn(Set roleIds);
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/dao/RolePermissionDao.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.dao;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import org.springframework.data.jpa.repository.Modifying;
7 | import org.springframework.data.jpa.repository.Query;
8 | import org.springframework.transaction.annotation.Transactional;
9 |
10 | import com.onecoderspace.base.component.common.dao.BaseDao;
11 | import com.onecoderspace.base.domain.Permission;
12 | import com.onecoderspace.base.domain.RolePermission;
13 |
14 | public interface RolePermissionDao extends BaseDao{
15 |
16 | List findByRoleId(int roleId);
17 |
18 | @Transactional
19 | @Query(value = "delete from role_permission where role_id=?1 ", nativeQuery = true)
20 | @Modifying
21 | void deleleByRoleId(int roleId);
22 |
23 | List findByRoleIdIn(Set roles);
24 |
25 | @Query(value="select perm.* from role_permission rp left join permission perm on rp.permission_id=perm.id where rp.role_id in(?1);",nativeQuery=true)
26 | List listByRoleIds(Set roles);
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/dao/UserDao.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.dao;
2 |
3 | import com.onecoderspace.base.component.common.dao.BaseDao;
4 | import com.onecoderspace.base.domain.User;
5 |
6 | public interface UserDao extends BaseDao{
7 | User findByUsernameAndDel(String username, int del);
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/dao/UserRoleDao.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.dao;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.jpa.repository.Modifying;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.transaction.annotation.Transactional;
8 |
9 | import com.onecoderspace.base.component.common.dao.BaseDao;
10 | import com.onecoderspace.base.domain.UserRole;
11 |
12 | public interface UserRoleDao extends BaseDao{
13 |
14 | List findByUserId(int uid);
15 |
16 | @Transactional
17 | @Query(value = "delete from user_role where user_id=?1 ", nativeQuery = true)
18 | @Modifying
19 | void deleleByUserId(int uid);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/domain/Permission.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.domain;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import com.onecoderspace.base.component.common.domain.BaseModel;
11 |
12 | /**
13 | * 菜单及操作权限,树形结构
14 | */
15 | @Entity
16 | @Table(name = "permission")
17 | public class Permission implements BaseModel{
18 |
19 | private static final long serialVersionUID = 6581772362165179231L;
20 |
21 | @Id
22 | @GeneratedValue(strategy=GenerationType.AUTO)
23 | private Integer id;//主键
24 |
25 | @Column(name="type",columnDefinition="tinyint default 0")
26 | private int type; //权限类型 0菜单 1按钮 2 操作权限
27 |
28 | @Column(name="name",length=50)
29 | private String name; //权限名称,用来展示
30 |
31 | @Column(name="code",length=50)
32 | private String code; //权限的值,校验权限时使用
33 |
34 | private String url;//操作权限的url
35 |
36 | @Column(name="weight",columnDefinition="int default 10000")
37 | private int weight = 10000; //排序值,升序
38 |
39 | @Column(name="pid",columnDefinition="int default 0")
40 | private int pid; //父节点ID
41 |
42 | @Override
43 | public Integer getId() {
44 | return id;
45 | }
46 |
47 | public void setId(Integer id) {
48 | this.id = id;
49 | }
50 |
51 | public int getType() {
52 | return type;
53 | }
54 |
55 | public void setType(int type) {
56 | this.type = type;
57 | }
58 |
59 | public String getName() {
60 | return name;
61 | }
62 |
63 | public void setName(String name) {
64 | this.name = name;
65 | }
66 |
67 | public String getCode() {
68 | return code;
69 | }
70 |
71 | public void setCode(String code) {
72 | this.code = code;
73 | }
74 |
75 | public String getUrl() {
76 | return url;
77 | }
78 |
79 | public void setUrl(String url) {
80 | this.url = url;
81 | }
82 |
83 | public int getWeight() {
84 | return weight;
85 | }
86 |
87 | public void setWeight(int weight) {
88 | this.weight = weight;
89 | }
90 |
91 | public int getPid() {
92 | return pid;
93 | }
94 |
95 | public void setPid(int pid) {
96 | this.pid = pid;
97 | }
98 |
99 | @Override
100 | public String toString() {
101 | return "Permission [id=" + id + ", type=" + type + ", name=" + name
102 | + ", code=" + code + ", weight=" + weight + ", pid=" + pid
103 | + "]";
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/domain/Role.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.domain;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import com.onecoderspace.base.component.common.domain.BaseModel;
11 |
12 | /**
13 | * 角色
14 | */
15 | @Entity
16 | @Table(name = "role")
17 | public class Role implements BaseModel{
18 |
19 | private static final long serialVersionUID = 254681740752863107L;
20 |
21 | @Id
22 | @GeneratedValue(strategy=GenerationType.AUTO)
23 | private Integer id;//主键
24 |
25 | @Column(name="name",length=50)
26 | private String name; //角色名称,通常为中文,用于展示
27 |
28 | @Column(name="code",length=45)
29 | private String code; //角色的值,用来校验权限,通常为英文
30 |
31 | @Column(name="remark",length=255)
32 | private String remark; //备注
33 |
34 | @Override
35 | public Integer getId() {
36 | return id;
37 | }
38 |
39 | public void setId(Integer id) {
40 | this.id = id;
41 | }
42 |
43 | public String getName() {
44 | return name;
45 | }
46 |
47 | public void setName(String name) {
48 | this.name = name;
49 | }
50 |
51 | public String getCode() {
52 | return code;
53 | }
54 |
55 | public void setCode(String code) {
56 | this.code = code;
57 | }
58 |
59 | public String getRemark() {
60 | return remark;
61 | }
62 |
63 | public void setRemark(String remark) {
64 | this.remark = remark;
65 | }
66 |
67 |
68 | @Override
69 | public String toString() {
70 | return "Role [id=" + id + ", name=" + name + ", code=" + code
71 | + ", remark=" + remark + "]";
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/domain/RolePermission.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.domain;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import com.onecoderspace.base.component.common.domain.BaseModel;
11 |
12 | /**
13 | * 角色权限关联表
14 | */
15 | @Entity
16 | @Table(name = "role_permission")
17 | public class RolePermission implements BaseModel{
18 |
19 | private static final long serialVersionUID = 2562960339678855205L;
20 |
21 | @Id
22 | @GeneratedValue(strategy=GenerationType.AUTO)
23 | private Integer id;//主键
24 |
25 | @Column(name="role_id",columnDefinition="int default 0")
26 | private int roleId; //角色ID
27 |
28 | @Column(name="permission_id",columnDefinition="int default 0")
29 | private int permissionId; //权限ID
30 |
31 | @Override
32 | public Integer getId() {
33 | return id;
34 | }
35 |
36 | public void setId(Integer id) {
37 | this.id = id;
38 | }
39 |
40 | public int getRoleId() {
41 | return roleId;
42 | }
43 |
44 | public void setRoleId(int roleId) {
45 | this.roleId = roleId;
46 | }
47 |
48 | public int getPermissionId() {
49 | return permissionId;
50 | }
51 |
52 | public void setPermissionId(int permissionId) {
53 | this.permissionId = permissionId;
54 | }
55 |
56 | @Override
57 | public String toString() {
58 | return "RolePermission [id=" + id + ", roleId=" + roleId
59 | + ", permissionId=" + permissionId + "]";
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/domain/User.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.domain;
2 |
3 | import io.swagger.annotations.ApiModelProperty;
4 |
5 | import javax.persistence.Column;
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import javax.persistence.Table;
11 |
12 | import com.onecoderspace.base.component.common.domain.BaseModel;
13 |
14 | import java.sql.Timestamp;
15 |
16 | /**
17 | * 用户
18 | */
19 | @Entity
20 | @Table(name = "user")
21 | public class User implements BaseModel{
22 |
23 | private static final long serialVersionUID = -91221104520172449L;
24 |
25 | @Id
26 | @GeneratedValue(strategy=GenerationType.AUTO)
27 | private Integer id;//主键
28 |
29 | @ApiModelProperty(value="用户类别 0普通用户 1运营人员")
30 | @Column(columnDefinition="tinyint default 0")
31 | private int type = 0;
32 |
33 | @ApiModelProperty(value="账号")
34 | @Column(name="username",length=50)
35 | private String username;
36 |
37 | @ApiModelProperty(value="姓名")
38 | @Column(name="name",length=50)
39 | private String name;
40 |
41 | @ApiModelProperty(value="密码(md5(mix(password,salt)))")
42 | @Column(name="pwd",length=50)
43 | private String pwd;
44 |
45 | @ApiModelProperty(value="密码加密的“盐”")
46 | @Column(name="salt",length=16)
47 | private String salt;
48 |
49 | @ApiModelProperty(value="手机号")
50 | @Column(name="mobile",length=15)
51 | private String mobile;
52 |
53 | @ApiModelProperty(value="邮箱")
54 | @Column(name="email",length=50)
55 | private String email;
56 |
57 | @ApiModelProperty(value="昵称")
58 | @Column(name="nick_name",length=50)
59 | private String nickName;
60 |
61 | @ApiModelProperty(value="性别 0未设置 1男 2女")
62 | @Column(name="gender",columnDefinition="tinyint default 0")
63 | private int gender = 0;
64 |
65 | @ApiModelProperty(value="账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过")
66 | @Column(name="status",columnDefinition="tinyint default 0")
67 | private int status = 0;
68 |
69 | @ApiModelProperty(value="账号是否有效 1有效 0无效")
70 | @Column(name="enable",columnDefinition="tinyint default 1")
71 | private int enable = 0;
72 |
73 | @ApiModelProperty(value="用户头像 相对路径,不要带域名")
74 | @Column(name="avatar",length=255)
75 | private String avatar;
76 |
77 | @ApiModelProperty(value="注册时间")
78 | @Column(name="register_time")
79 | private Timestamp registerTime;
80 |
81 | @ApiModelProperty(value="最后更新人")
82 | @Column(name="updator",columnDefinition="int default 0")
83 | private int updator = 0;
84 |
85 | @ApiModelProperty(value="最后更新时间")
86 | @Column(name="update_time")
87 | private Timestamp updateTime;
88 |
89 | @ApiModelProperty(value="标记删除字段 1已删除 0未删除")
90 | @Column(name="del",columnDefinition="tinyint default 0")
91 | private int del = 0;
92 |
93 |
94 | //账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过
95 | public static final int STATUS_UNAUDIT = 0;
96 | public static final int STATUS_WAIT_AUDIT = 1;
97 | public static final int STATUS_AUDIT_PASS = 2;
98 | public static final int STATUS_AUDIT_UNPASS = -1;
99 |
100 | //用户类别 0普通用户 1运营人员
101 | public static final int TYPE_USER = 0;
102 | public static final int TYPE_OPERATOR = 1;
103 |
104 | @Override
105 | public Integer getId() {
106 | return id;
107 | }
108 |
109 | public void setId(Integer id) {
110 | this.id = id;
111 | }
112 |
113 | public int getType() {
114 | return type;
115 | }
116 |
117 | public void setType(int type) {
118 | this.type = type;
119 | }
120 |
121 | public String getUsername() {
122 | return username;
123 | }
124 |
125 | public void setUsername(String username) {
126 | this.username = username;
127 | }
128 |
129 | public String getName() {
130 | return name;
131 | }
132 |
133 | public void setName(String name) {
134 | this.name = name;
135 | }
136 |
137 | public String getPwd() {
138 | return pwd;
139 | }
140 |
141 | public void setPwd(String pwd) {
142 | this.pwd = pwd;
143 | }
144 |
145 | public String getSalt() {
146 | return salt;
147 | }
148 |
149 | public void setSalt(String salt) {
150 | this.salt = salt;
151 | }
152 |
153 | public String getMobile() {
154 | return mobile;
155 | }
156 |
157 | public void setMobile(String mobile) {
158 | this.mobile = mobile;
159 | }
160 |
161 | public String getEmail() {
162 | return email;
163 | }
164 |
165 | public void setEmail(String email) {
166 | this.email = email;
167 | }
168 |
169 | public String getNickName() {
170 | return nickName;
171 | }
172 |
173 | public void setNickName(String nickName) {
174 | this.nickName = nickName;
175 | }
176 |
177 | public int getGender() {
178 | return gender;
179 | }
180 |
181 | public void setGender(int gender) {
182 | this.gender = gender;
183 | }
184 |
185 | public int getStatus() {
186 | return status;
187 | }
188 |
189 | public void setStatus(int status) {
190 | this.status = status;
191 | }
192 |
193 | public int getEnable() {
194 | return enable;
195 | }
196 |
197 | public void setEnable(int enable) {
198 | this.enable = enable;
199 | }
200 |
201 | public String getAvatar() {
202 | return avatar;
203 | }
204 |
205 | public void setAvatar(String avatar) {
206 | this.avatar = avatar;
207 | }
208 |
209 | public Timestamp getRegisterTime() {
210 | return registerTime;
211 | }
212 |
213 | public void setRegisterTime(Timestamp registerTime) {
214 | this.registerTime = registerTime;
215 | }
216 |
217 | public int getUpdator() {
218 | return updator;
219 | }
220 |
221 | public void setUpdator(int updator) {
222 | this.updator = updator;
223 | }
224 |
225 | public Timestamp getUpdateTime() {
226 | return updateTime;
227 | }
228 |
229 | public void setUpdateTime(Timestamp updateTime) {
230 | this.updateTime = updateTime;
231 | }
232 |
233 | public int getDel() {
234 | return del;
235 | }
236 |
237 | public void setDel(int del) {
238 | this.del = del;
239 | }
240 |
241 | @Override
242 | public String toString() {
243 | return String
244 | .format("User [id=%s, type=%s, username=%s, name=%s, pwd=%s, salt=%s, mobile=%s, email=%s, nickName=%s, gender=%s, status=%s, enable=%s, avatar=%s, registerTime=%s, updator=%s, updateTime=%s, del=%s]",
245 | id, type, username, name, pwd, salt, mobile, email,
246 | nickName, gender, status, enable, avatar, registerTime,
247 | updator, updateTime, del);
248 | }
249 |
250 | }
251 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/domain/UserRole.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.domain;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.Table;
9 |
10 | import com.onecoderspace.base.component.common.domain.BaseModel;
11 |
12 | /**
13 | * 用户角色
14 | */
15 | @Entity
16 | @Table(name = "user_role")
17 | public class UserRole implements BaseModel{
18 |
19 | private static final long serialVersionUID = 5806516492008208503L;
20 |
21 | @Id
22 | @GeneratedValue(strategy=GenerationType.AUTO)
23 | private Integer id;//主键
24 |
25 | @Column(name="user_id",columnDefinition="int default 0")
26 | private int userId; //用户ID
27 |
28 | @Column(name="role_id",columnDefinition="int default 0")
29 | private int roleId; //角色ID
30 |
31 | @Override
32 | public Integer getId() {
33 | return id;
34 | }
35 |
36 | public void setId(Integer id) {
37 | this.id = id;
38 | }
39 |
40 | public int getUserId() {
41 | return userId;
42 | }
43 |
44 | public void setUserId(int userId) {
45 | this.userId = userId;
46 | }
47 |
48 | public int getRoleId() {
49 | return roleId;
50 | }
51 |
52 | public void setRoleId(int roleId) {
53 | this.roleId = roleId;
54 | }
55 |
56 | @Override
57 | public String toString() {
58 | return "UserRole [id=" + id + ", userId=" + userId + ", roleId="
59 | + roleId + "]";
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/filter/CsrfFilter.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.filter;
2 |
3 | import java.io.IOException;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | import javax.servlet.Filter;
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.FilterConfig;
12 | import javax.servlet.ServletException;
13 | import javax.servlet.ServletRequest;
14 | import javax.servlet.ServletResponse;
15 | import javax.servlet.http.HttpServletRequest;
16 | import javax.servlet.http.HttpServletResponse;
17 | import javax.servlet.http.HttpSession;
18 |
19 | import org.apache.commons.lang3.StringUtils;
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | import com.onecoderspace.base.util.AjaxResponseWriter;
24 | import com.onecoderspace.base.util.ServiceStatusEnum;
25 |
26 | /**
27 | * CSRF跨域请求伪造拦截
28 | * 除登录以外的post方法,都需要携带token,如果token为空或token错误,则返回异常提示
29 | * 注意在filter初始化参数内配置排除的url
30 | * @author yangwk
31 | */
32 | public class CsrfFilter implements Filter {
33 | private static Logger logger = LoggerFactory.getLogger(CsrfFilter.class);
34 |
35 | public List excludes = new ArrayList();
36 |
37 | private boolean isOpen = false;//是否开启该filter
38 |
39 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
40 | if(!isOpen){
41 | filterChain.doFilter(request, response);
42 | return ;
43 | }
44 | if(logger.isDebugEnabled()){
45 | logger.debug("csrf filter is running");
46 | }
47 |
48 | HttpServletRequest req = (HttpServletRequest) request;
49 | HttpServletResponse resp = (HttpServletResponse) response;
50 | HttpSession session = req.getSession();
51 | Object token = session.getAttribute("token");
52 | if(!"post".equalsIgnoreCase(req.getMethod()) || handleExcludeURL(req, resp) || token == null){
53 | filterChain.doFilter(request, response);
54 | return;
55 | }
56 |
57 | String requestToken = req.getParameter("token");
58 | if(StringUtils.isBlank(requestToken) || !requestToken.equals(token)){
59 | AjaxResponseWriter.write(req, resp, ServiceStatusEnum.ILLEGAL_TOKEN, "非法的token");
60 | return;
61 | }
62 | filterChain.doFilter(request, response);
63 | }
64 |
65 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
66 | if (excludes == null || excludes.isEmpty()) {
67 | return false;
68 | }
69 | String url = request.getServletPath();
70 | for (String pattern : excludes) {
71 | Pattern p = Pattern.compile("^" + pattern);
72 | Matcher m = p.matcher(url);
73 | if (m.find()) {
74 | return true;
75 | }
76 | }
77 | return false;
78 | }
79 |
80 | @Override
81 | public void init(FilterConfig filterConfig) throws ServletException {
82 | if(logger.isDebugEnabled()){
83 | logger.debug("csrf filter init~~~~~~~~~~~~");
84 | }
85 |
86 | String temp = filterConfig.getInitParameter("excludes");
87 | if (temp != null) {
88 | String[] url = temp.split(",");
89 | for (int i = 0; url != null && i < url.length; i++) {
90 | excludes.add(url[i]);
91 | }
92 | }
93 |
94 | temp = filterConfig.getInitParameter("isOpen");
95 | if(StringUtils.isNotBlank(temp) && "true".equals(isOpen)){
96 | isOpen = true;
97 | }
98 | }
99 |
100 | @Override
101 | public void destroy() {}
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/filter/LoginFilter.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.filter;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.Filter;
6 | import javax.servlet.FilterChain;
7 | import javax.servlet.FilterConfig;
8 | import javax.servlet.ServletException;
9 | import javax.servlet.ServletRequest;
10 | import javax.servlet.ServletResponse;
11 | import javax.servlet.http.HttpServletRequest;
12 | import javax.servlet.http.HttpServletResponse;
13 |
14 | import org.apache.shiro.SecurityUtils;
15 | import org.apache.shiro.subject.Subject;
16 |
17 | import com.onecoderspace.base.util.AjaxResponseWriter;
18 | import com.onecoderspace.base.util.ServiceStatusEnum;
19 |
20 | public class LoginFilter implements Filter {
21 |
22 | @Override
23 | public void destroy() {}
24 |
25 | @Override
26 | public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
27 | Subject currentUser = SecurityUtils.getSubject();
28 | if (!currentUser.isAuthenticated()) {
29 | HttpServletRequest req = (HttpServletRequest) request;
30 | HttpServletResponse res = (HttpServletResponse) response;
31 | AjaxResponseWriter.write(req, res, ServiceStatusEnum.UNLOGIN, "请登录");
32 | return;
33 | }
34 | chain.doFilter(request, response);
35 | }
36 |
37 | @Override
38 | public void init(FilterConfig filterConfig) throws ServletException {}
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/filter/ShiroSessionFilter.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.filter;
2 |
3 | import java.io.IOException;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | import javax.servlet.Filter;
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.FilterConfig;
12 | import javax.servlet.ServletException;
13 | import javax.servlet.ServletRequest;
14 | import javax.servlet.ServletResponse;
15 | import javax.servlet.http.HttpServletRequest;
16 | import javax.servlet.http.HttpServletResponse;
17 |
18 | import org.apache.commons.lang3.StringUtils;
19 | import org.apache.commons.lang3.math.NumberUtils;
20 | import org.apache.shiro.SecurityUtils;
21 | import org.apache.shiro.subject.Subject;
22 | import org.slf4j.Logger;
23 | import org.slf4j.LoggerFactory;
24 |
25 | /**
26 | * 通过拦截器设置shiroSession过期时间
27 | * @author yangwk
28 | */
29 | public class ShiroSessionFilter implements Filter {
30 | private static Logger logger = LoggerFactory.getLogger(ShiroSessionFilter.class);
31 |
32 | public List excludes = new ArrayList();
33 |
34 | private long serverSessionTimeout = 180000L;//ms
35 |
36 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
37 | if(logger.isDebugEnabled()){
38 | logger.debug("shiro session filter is open");
39 | }
40 |
41 | HttpServletRequest req = (HttpServletRequest) request;
42 | HttpServletResponse resp = (HttpServletResponse) response;
43 | if(handleExcludeURL(req, resp)){
44 | filterChain.doFilter(request, response);
45 | return;
46 | }
47 |
48 | Subject currentUser = SecurityUtils.getSubject();
49 | if(currentUser.isAuthenticated()){
50 | currentUser.getSession().setTimeout(serverSessionTimeout);
51 | }
52 | filterChain.doFilter(request, response);
53 | }
54 |
55 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
56 |
57 | if (excludes == null || excludes.isEmpty()) {
58 | return false;
59 | }
60 |
61 | String url = request.getServletPath();
62 | for (String pattern : excludes) {
63 | Pattern p = Pattern.compile("^" + pattern);
64 | Matcher m = p.matcher(url);
65 | if (m.find()) {
66 | return true;
67 | }
68 | }
69 |
70 | return false;
71 | }
72 |
73 | @Override
74 | public void init(FilterConfig filterConfig) throws ServletException {
75 | if(logger.isDebugEnabled()){
76 | logger.debug("shiro session filter init~~~~~~~~~~~~");
77 | }
78 | String temp = filterConfig.getInitParameter("excludes");
79 | if (temp != null) {
80 | String[] url = temp.split(",");
81 | for (int i = 0; url != null && i < url.length; i++) {
82 | excludes.add(url[i]);
83 | }
84 | }
85 | String timeout = filterConfig.getInitParameter("serverSessionTimeout");
86 | if(StringUtils.isNotBlank(timeout)){
87 | this.serverSessionTimeout = NumberUtils.toLong(timeout,1800L)*1000L;
88 | }
89 | }
90 |
91 | @Override
92 | public void destroy() {}
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/filter/XssFilter.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.filter;
2 |
3 | import java.io.IOException;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.regex.Matcher;
7 | import java.util.regex.Pattern;
8 |
9 | import javax.servlet.Filter;
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.FilterConfig;
12 | import javax.servlet.ServletException;
13 | import javax.servlet.ServletRequest;
14 | import javax.servlet.ServletResponse;
15 | import javax.servlet.http.HttpServletRequest;
16 | import javax.servlet.http.HttpServletResponse;
17 |
18 | import org.apache.commons.lang3.BooleanUtils;
19 | import org.apache.commons.lang3.StringUtils;
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | /**
24 | * 拦截防止xss注入
25 | * 通过Jsoup过滤请求参数内的特定字符
26 | * @author yangwk
27 | */
28 | public class XssFilter implements Filter {
29 | private static Logger logger = LoggerFactory.getLogger(XssFilter.class);
30 |
31 | private static boolean IS_INCLUDE_RICH_TEXT = false;//是否过滤富文本内容
32 |
33 | public List excludes = new ArrayList();
34 |
35 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
36 | if(logger.isDebugEnabled()){
37 | logger.debug("xss filter is open");
38 | }
39 |
40 | HttpServletRequest req = (HttpServletRequest) request;
41 | HttpServletResponse resp = (HttpServletResponse) response;
42 | if(handleExcludeURL(req, resp)){
43 | filterChain.doFilter(request, response);
44 | return;
45 | }
46 |
47 | XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT);
48 | filterChain.doFilter(xssRequest, response);
49 | }
50 |
51 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
52 |
53 | if (excludes == null || excludes.isEmpty()) {
54 | return false;
55 | }
56 |
57 | String url = request.getServletPath();
58 | for (String pattern : excludes) {
59 | Pattern p = Pattern.compile("^" + pattern);
60 | Matcher m = p.matcher(url);
61 | if (m.find()) {
62 | return true;
63 | }
64 | }
65 |
66 | return false;
67 | }
68 |
69 | @Override
70 | public void init(FilterConfig filterConfig) throws ServletException {
71 | if(logger.isDebugEnabled()){
72 | logger.debug("xss filter init~~~~~~~~~~~~");
73 | }
74 | String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
75 | if(StringUtils.isNotBlank(isIncludeRichText)){
76 | IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
77 | }
78 |
79 | String temp = filterConfig.getInitParameter("excludes");
80 | if (temp != null) {
81 | String[] url = temp.split(",");
82 | for (int i = 0; url != null && i < url.length; i++) {
83 | excludes.add(url[i]);
84 | }
85 | }
86 | }
87 |
88 | @Override
89 | public void destroy() {}
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/filter/XssHttpServletRequestWrapper.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.filter;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 | import javax.servlet.http.HttpServletRequestWrapper;
5 |
6 | import org.apache.commons.lang3.StringUtils;
7 |
8 | import com.onecoderspace.base.util.security.xss.JsoupUtil;
9 |
10 | /**
11 | * {@link XssHttpServletRequestWrapper}
12 | */
13 | public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
14 | HttpServletRequest orgRequest = null;
15 | private boolean isIncludeRichText = false;
16 |
17 | public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {
18 | super(request);
19 | orgRequest = request;
20 | this.isIncludeRichText = isIncludeRichText;
21 | }
22 |
23 | /**
24 | * 覆盖getParameter方法,将参数名和参数值都做xss过滤。
25 | * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
26 | * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
27 | */
28 | @Override
29 | public String getParameter(String name) {
30 | if(("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText){
31 | return super.getParameter(name);
32 | }
33 | name = JsoupUtil.clean(name);
34 | String value = super.getParameter(name);
35 | if (StringUtils.isNotBlank(value)) {
36 | value = JsoupUtil.clean(value);
37 | }
38 | return value;
39 | }
40 |
41 | @Override
42 | public String[] getParameterValues(String name) {
43 | String[] arr = super.getParameterValues(name);
44 | if(arr != null){
45 | for (int i=0;i
55 | * 如果需要获得原始的值,则通过super.getHeaders(name)来获取
56 | * getHeaderNames 也可能需要覆盖
57 | */
58 | @Override
59 | public String getHeader(String name) {
60 | name = JsoupUtil.clean(name);
61 | String value = super.getHeader(name);
62 | if (StringUtils.isNotBlank(value)) {
63 | value = JsoupUtil.clean(value);
64 | }
65 | return value;
66 | }
67 |
68 | /**
69 | * 获取最原始的request
70 | *
71 | * @return
72 | */
73 | public HttpServletRequest getOrgRequest() {
74 | return orgRequest;
75 | }
76 |
77 | /**
78 | * 获取最原始的request的静态方法
79 | *
80 | * @return
81 | */
82 | public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
83 | if (req instanceof XssHttpServletRequestWrapper) {
84 | return ((XssHttpServletRequestWrapper) req).getOrgRequest();
85 | }
86 |
87 | return req;
88 | }
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/PermissionService.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service;
2 |
3 | import org.springframework.data.domain.Sort;
4 |
5 | import com.onecoderspace.base.component.common.service.BaseService;
6 | import com.onecoderspace.base.domain.Permission;
7 |
8 | /**
9 | *菜单及操作权限,树形结构
10 | */
11 | public interface PermissionService extends BaseService{
12 |
13 | Iterable findAll(Sort sort);
14 |
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/RolePermissionService.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import com.onecoderspace.base.component.common.service.BaseService;
7 | import com.onecoderspace.base.domain.Permission;
8 | import com.onecoderspace.base.domain.RolePermission;
9 |
10 | /**
11 | *角色权限关联表
12 | */
13 | public interface RolePermissionService extends BaseService{
14 |
15 | List findByRoleId(int roleId);
16 |
17 | void deleleByRoleId(int roleId);
18 |
19 | List getPermissions(Set roles);
20 |
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/RoleService.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service;
2 |
3 | import java.util.Set;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 |
8 | import com.onecoderspace.base.component.common.service.BaseService;
9 | import com.onecoderspace.base.domain.Role;
10 | import com.onecoderspace.base.util.Return;
11 |
12 | /**
13 | *角色
14 | */
15 | public interface RoleService extends BaseService{
16 |
17 | Page listByPage(String name, Pageable pageable);
18 |
19 | Return doSetPermissions(int roleId, String permissionIds);
20 |
21 | Role findByCode(String code);
22 |
23 | Set findByIds(Set roleIds);
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/UserRoleService.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import com.onecoderspace.base.component.common.service.BaseService;
7 | import com.onecoderspace.base.domain.UserRole;
8 |
9 | /**
10 | *用户角色
11 | */
12 | public interface UserRoleService extends BaseService{
13 |
14 | List findByUserId(int uid);
15 |
16 | void deleleByUserId(int uid);
17 |
18 | /**
19 | * 添加角色
20 | * @author yangwk
21 | * @time 2017年7月28日 下午2:12:35
22 | * @param userId 用户ID
23 | * @param code 角色编码
24 | */
25 | void add(int id, String code);
26 |
27 |
28 | Set findRoleIds(int userId);
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service;
2 |
3 | import java.util.Map;
4 |
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.Pageable;
7 |
8 | import com.onecoderspace.base.component.common.service.BaseService;
9 | import com.onecoderspace.base.domain.User;
10 | import com.onecoderspace.base.util.Return;
11 |
12 | /**
13 | *用户
14 | */
15 | public interface UserService extends BaseService{
16 |
17 | User findByUsername(String username);
18 |
19 | /**
20 | * 设置密码
21 | * @author yangwk
22 | * @time 2017年7月27日 上午10:15:12
23 | * @param entity
24 | * @param pwd
25 | * @return
26 | */
27 | Return changePwd(User entity, String pwd);
28 |
29 | /**
30 | * 带条件分页查询
31 | * @author yangwk
32 | * @time 2017年7月27日 上午10:15:26
33 | * @param params
34 | * @param pageable
35 | * @return
36 | */
37 | Page listByPage(Map params,Pageable pageable);
38 |
39 | /**
40 | * 保存审核结果
41 | * @author yangwk
42 | * @time 2017年7月27日 上午10:14:11
43 | * @param entity 素材新
44 | * @param value 审核结果 1通过 0未通过
45 | * @param msg 备注新
46 | * @return
47 | */
48 | Return doAudit(User entity, int value, String msg);
49 |
50 | /**
51 | * 设置用户的角色
52 | * @author yangwk
53 | * @time 2017年7月27日 上午10:15:01
54 | * @param uid
55 | * @param roleIds
56 | * @return
57 | */
58 | Return doSetRoles(int uid, String roleIds);
59 |
60 | /**
61 | * 保存用户
62 | * @author yangwk
63 | * @time 2017年7月28日 下午1:37:24
64 | * @param user 用户信息
65 | * @param company 公司信息
66 | * @return
67 | */
68 | Return saveUser(User user);
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/impl/PermissionServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service.impl;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.data.domain.Sort;
5 | import org.springframework.stereotype.Service;
6 | import org.springframework.transaction.annotation.Transactional;
7 |
8 | import com.onecoderspace.base.component.common.dao.BaseDao;
9 | import com.onecoderspace.base.component.common.service.BaseServiceImpl;
10 | import com.onecoderspace.base.dao.PermissionDao;
11 | import com.onecoderspace.base.domain.Permission;
12 | import com.onecoderspace.base.service.PermissionService;
13 |
14 | @Transactional
15 | @Service("permissionService")
16 | public class PermissionServiceImpl extends BaseServiceImpl implements PermissionService{
17 |
18 | @Autowired
19 | private PermissionDao permissionDao;
20 |
21 | @Override
22 | public BaseDao getDAO() {
23 | return permissionDao;
24 | }
25 |
26 | @Override
27 | public Iterable findAll(Sort sort) {
28 | return this.permissionDao.findAll(sort);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/impl/RolePermissionServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service.impl;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import org.apache.commons.collections.CollectionUtils;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Service;
9 | import org.springframework.transaction.annotation.Transactional;
10 |
11 | import com.google.common.collect.Lists;
12 | import com.onecoderspace.base.component.common.dao.BaseDao;
13 | import com.onecoderspace.base.component.common.service.BaseServiceImpl;
14 | import com.onecoderspace.base.dao.PermissionDao;
15 | import com.onecoderspace.base.dao.RolePermissionDao;
16 | import com.onecoderspace.base.domain.Permission;
17 | import com.onecoderspace.base.domain.RolePermission;
18 | import com.onecoderspace.base.service.RolePermissionService;
19 |
20 | @Transactional
21 | @Service("rolePermissionService")
22 | public class RolePermissionServiceImpl extends BaseServiceImpl implements RolePermissionService{
23 |
24 | @Autowired
25 | private RolePermissionDao rolePermissionDao;
26 |
27 | @Override
28 | public BaseDao getDAO() {
29 | return rolePermissionDao;
30 | }
31 |
32 | @Override
33 | public List findByRoleId(int roleId) {
34 | return this.rolePermissionDao.findByRoleId(roleId);
35 | }
36 |
37 | @Override
38 | public void deleleByRoleId(int roleId) {
39 | this.rolePermissionDao.deleleByRoleId(roleId);
40 | }
41 |
42 | @Override
43 | public List getPermissions(Set roles) {
44 | if(CollectionUtils.isEmpty(roles)){
45 | return Lists.newArrayList();
46 | }
47 | List list = this.permissionDao.listByRoleIds(roles);
48 | return list;
49 | }
50 |
51 | @Autowired
52 | private PermissionDao permissionDao;
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/impl/RoleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service.impl;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Set;
6 |
7 | import javax.persistence.criteria.CriteriaBuilder;
8 | import javax.persistence.criteria.CriteriaQuery;
9 | import javax.persistence.criteria.Predicate;
10 | import javax.persistence.criteria.Root;
11 |
12 | import org.apache.commons.collections.CollectionUtils;
13 | import org.apache.commons.lang3.StringUtils;
14 | import org.apache.commons.lang3.math.NumberUtils;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.data.domain.Page;
17 | import org.springframework.data.domain.Pageable;
18 | import org.springframework.data.jpa.domain.Specification;
19 | import org.springframework.stereotype.Service;
20 | import org.springframework.transaction.annotation.Transactional;
21 |
22 | import com.google.common.collect.Sets;
23 | import com.onecoderspace.base.component.common.dao.BaseDao;
24 | import com.onecoderspace.base.component.common.service.BaseServiceImpl;
25 | import com.onecoderspace.base.dao.RoleDao;
26 | import com.onecoderspace.base.domain.Role;
27 | import com.onecoderspace.base.domain.RolePermission;
28 | import com.onecoderspace.base.service.RolePermissionService;
29 | import com.onecoderspace.base.service.RoleService;
30 | import com.onecoderspace.base.util.Return;
31 |
32 | @Transactional
33 | @Service("roleService")
34 | public class RoleServiceImpl extends BaseServiceImpl implements RoleService{
35 |
36 | @Autowired
37 | private RoleDao roleDao;
38 |
39 | @Override
40 | public BaseDao getDAO() {
41 | return roleDao;
42 | }
43 |
44 | @Override
45 | public Page listByPage(final String name, Pageable pageable) {
46 | Specification spec = new Specification() {
47 | @Override
48 | public Predicate toPredicate(Root root,CriteriaQuery> query,CriteriaBuilder cb) {
49 | List list = new ArrayList();
50 | if(StringUtils.isNotBlank(name)){
51 | list.add(cb.like(root.get("name").as(String.class), String.format("%%%s%%", name)));
52 | }
53 | Predicate[] p = new Predicate[list.size()];
54 | return cb.and(list.toArray(p));
55 | }
56 | };
57 | Page page = roleDao.findAll(spec, pageable);
58 | return page;
59 | }
60 |
61 | @Override
62 | public Return doSetPermissions(int roleId, String permissionIds) {
63 | rolePermissionService.deleleByRoleId(roleId);
64 | String[] arr = permissionIds.split(",");
65 | for (String permissionId : arr) {
66 | RolePermission entity = new RolePermission();
67 | entity.setRoleId(roleId);
68 | entity.setPermissionId(NumberUtils.toInt(permissionId));
69 | rolePermissionService.save(entity);
70 | }
71 | return Return.success();
72 | }
73 |
74 | @Override
75 | public Role findByCode(String code) {
76 | return this.roleDao.findByCode(code);
77 | }
78 |
79 | @Override
80 | public Set findByIds(Set roleIds) {
81 | if(CollectionUtils.isEmpty(roleIds)){
82 | return Sets.newHashSet();
83 | }
84 | return this.roleDao.findByIdIn(roleIds);
85 | }
86 |
87 | @Autowired
88 | private RolePermissionService rolePermissionService;
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/impl/UserRoleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service.impl;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 | import org.springframework.transaction.annotation.Transactional;
9 |
10 | import com.google.common.collect.Sets;
11 | import com.onecoderspace.base.component.common.dao.BaseDao;
12 | import com.onecoderspace.base.component.common.service.BaseServiceImpl;
13 | import com.onecoderspace.base.dao.UserRoleDao;
14 | import com.onecoderspace.base.domain.Role;
15 | import com.onecoderspace.base.domain.UserRole;
16 | import com.onecoderspace.base.service.RoleService;
17 | import com.onecoderspace.base.service.UserRoleService;
18 |
19 | @Transactional
20 | @Service("userRoleService")
21 | public class UserRoleServiceImpl extends BaseServiceImpl implements UserRoleService{
22 |
23 | @Autowired
24 | private UserRoleDao userRoleDao;
25 |
26 | @Override
27 | public BaseDao getDAO() {
28 | return userRoleDao;
29 | }
30 |
31 | @Override
32 | public List findByUserId(int uid) {
33 | return userRoleDao.findByUserId(uid);
34 | }
35 |
36 | @Override
37 | public void deleleByUserId(int uid) {
38 | userRoleDao.deleleByUserId(uid);
39 | }
40 |
41 | @Override
42 | public void add(int userId, String code) {
43 | Role role = this.roleService.findByCode(code);
44 | if(role == null){
45 | return ;
46 | }
47 | UserRole userRole = new UserRole();
48 | userRole.setUserId(userId);
49 | userRole.setRoleId(role.getId());
50 | this.userRoleDao.save(userRole);
51 | }
52 |
53 | @Override
54 | public Set findRoleIds(int userId) {
55 | List list = this.userRoleDao.findByUserId(userId);
56 | Set ids = Sets.newHashSet();
57 | for(UserRole entity : list){
58 | ids.add(entity.getRoleId());
59 | }
60 | return ids;
61 | }
62 |
63 | @Autowired
64 | private RoleService roleService;
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.service.impl;
2 |
3 | import java.sql.Timestamp;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | import javax.persistence.criteria.CriteriaBuilder;
9 | import javax.persistence.criteria.CriteriaQuery;
10 | import javax.persistence.criteria.Predicate;
11 | import javax.persistence.criteria.Root;
12 |
13 | import org.apache.commons.lang3.StringUtils;
14 | import org.apache.commons.lang3.math.NumberUtils;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.data.domain.Page;
17 | import org.springframework.data.domain.PageRequest;
18 | import org.springframework.data.domain.Pageable;
19 | import org.springframework.data.domain.Sort;
20 | import org.springframework.data.domain.Sort.Direction;
21 | import org.springframework.data.jpa.domain.Specification;
22 | import org.springframework.stereotype.Service;
23 | import org.springframework.transaction.annotation.Transactional;
24 |
25 | import com.onecoderspace.base.component.common.dao.BaseDao;
26 | import com.onecoderspace.base.component.common.service.BaseServiceImpl;
27 | import com.onecoderspace.base.dao.UserDao;
28 | import com.onecoderspace.base.domain.User;
29 | import com.onecoderspace.base.domain.UserRole;
30 | import com.onecoderspace.base.service.UserRoleService;
31 | import com.onecoderspace.base.service.UserService;
32 | import com.onecoderspace.base.util.Constants;
33 | import com.onecoderspace.base.util.LoginSessionHelper;
34 | import com.onecoderspace.base.util.Return;
35 | import com.onecoderspace.base.util.SaltMD5Util;
36 |
37 | @Transactional
38 | @Service("userService")
39 | public class UserServiceImpl extends BaseServiceImpl implements UserService{
40 |
41 | @Autowired
42 | private UserDao userDao;
43 |
44 | @Override
45 | public BaseDao getDAO() {
46 | return userDao;
47 | }
48 |
49 | @Override
50 | public User findByUsername(String username) {
51 | return userDao.findByUsernameAndDel(username,Constants.DEL_NO);
52 | }
53 |
54 | @Override
55 | public Return changePwd(User entity, String pwd) {
56 | String salt = SaltMD5Util.getSalt();
57 | entity.setPwd(SaltMD5Util.encode(pwd, salt));
58 | entity.setSalt(salt);
59 | userDao.save(entity);
60 | return Return.success();
61 | }
62 |
63 | @Override
64 | public Page listByPage(final Map params,Pageable pageable){
65 | Specification spec = new Specification() {
66 | @Override
67 | public Predicate toPredicate(Root root,CriteriaQuery> query,CriteriaBuilder cb) {
68 | List list = new ArrayList();
69 | String type = params.get("type");
70 | String status= params.get("status");
71 | String username = params.get("username");
72 | String name = params.get("name");
73 |
74 | if(StringUtils.isNotBlank(type)){
75 | list.add(cb.equal(root.get("type").as(Integer.class), NumberUtils.toInt(type)));
76 | }
77 | if(StringUtils.isNotBlank(status)){
78 | list.add(cb.equal(root.get("status").as(Integer.class), NumberUtils.toInt(status)));
79 | }
80 | if(StringUtils.isNotBlank(username)){
81 | list.add(cb.like(root.get("username").as(String.class), String.format("%%%s%%", username)));
82 | }
83 | if(StringUtils.isNotBlank(name)){
84 | list.add(cb.like(root.get("name").as(String.class), String.format("%%%s%%", name)));
85 | }
86 | list.add(cb.equal(root.get("del"), Constants.DEL_NO));
87 | Predicate[] p = new Predicate[list.size()];
88 | return cb.and(list.toArray(p));
89 |
90 | //in条件查询
91 | /*List ids = Lists.newArrayList();
92 | ids.add(1);
93 | ids.add(2);
94 | In in = cb.in(root.get("id").as(Integer.class));
95 | in.value(1);
96 | in.value(2);
97 | return cb.or(in);*/
98 | }
99 | };
100 | Page page = userDao.findAll(spec, pageable);
101 | return page;
102 | }
103 |
104 | @Override
105 | public Return doAudit(User entity, int value, String msg) {
106 | if(value == 1){
107 | entity.setStatus(User.STATUS_AUDIT_PASS);
108 | } else {
109 | entity.setStatus(User.STATUS_AUDIT_UNPASS);
110 | }
111 | int currentUid = LoginSessionHelper.getCurrentUserId();
112 | entity.setUpdator(currentUid);
113 | entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
114 | userDao.save(entity);
115 | Pageable pageable = new PageRequest(0, 10, new Sort(Direction.DESC, "updateTime"));
116 | Page page = userDao.findAll(pageable);
117 |
118 | return Return.success();
119 | }
120 |
121 | @Override
122 | public Return doSetRoles(int uid, String roleIds) {
123 | userRoleService.deleleByUserId(uid);
124 | String[] arr = roleIds.split(",");
125 | for (String roleId : arr) {
126 | UserRole entity = new UserRole();
127 | entity.setUserId(uid);
128 | entity.setRoleId(NumberUtils.toInt(roleId));
129 | userRoleService.save(entity);
130 | }
131 | return Return.success();
132 | }
133 |
134 | @Override
135 | public Return saveUser(User user) {
136 | this.userDao.save(user);
137 |
138 | String code = user.getType() == User.TYPE_OPERATOR ? Constants.ROLE_CODE_OPERATOR : Constants.ROLE_CODE_USER;
139 | this.userRoleService.add(user.getId(),code);
140 |
141 | return Return.success();
142 | }
143 |
144 | @Autowired
145 | private UserRoleService userRoleService;
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/AjaxResponseWriter.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 | import java.util.Map;
6 |
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import com.google.common.collect.Maps;
11 |
12 | /**
13 | * 当前端通过ajax请求时,直接将返回结果写回前端
14 | * @author yangwk
15 | */
16 | public class AjaxResponseWriter {
17 |
18 | /**
19 | * 写回数据到前端
20 | * @param request
21 | * @param response
22 | * @param status {@link ServiceStatusEnum}
23 | * @param message 返回的描述信息
24 | * @throws IOException
25 | */
26 | public static void write(HttpServletRequest request,HttpServletResponse response,ServiceStatusEnum status,String message) throws IOException{
27 | String contentType = "application/json";
28 | response.setContentType(contentType);
29 | response.setCharacterEncoding("UTF-8");
30 | response.setHeader("Access-Control-Allow-Credentials", "true");
31 | response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
32 |
33 | Map map = Maps.newLinkedHashMap();
34 | map.put("service_status", status.code);
35 | map.put("description", message);
36 | String result = JacksonHelper.toJson(map);
37 | PrintWriter out = response.getWriter();
38 | try{
39 | out.print(result);
40 | out.flush();
41 | } finally {
42 | out.close();
43 | }
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/Constants.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | public class Constants {
4 |
5 | /**已删除*/
6 | public static final int DEL_YES = 1;
7 |
8 | /**未删除*/
9 | public static final int DEL_NO = 0;
10 |
11 |
12 | /**普通用户*/
13 | public static final String ROLE_CODE_USER = "user";
14 | /**操作员*/
15 | public static final String ROLE_CODE_OPERATOR = "operator";
16 | /**管理员*/
17 | public static final String ROLE_CODE_ADMIN = "admin";
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/DateUtils.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.sql.Timestamp;
4 | import java.util.Calendar;
5 |
6 | import org.apache.commons.lang3.StringUtils;
7 | import org.joda.time.DateTime;
8 |
9 | public class DateUtils {
10 |
11 | public final static String DATE_FORMAT_DEFAULT = "yyyy-MM-dd";
12 | public final static String DATE_FORMAT_TIME = "yyyy-MM-dd HH:mm";
13 | public final static String DATE_FORMAT_ALL = "yyyy-MM-dd HH:mm:ss";
14 | public final static String DATE_CHINA_DEFAULT = "yyyy年MM月dd日";
15 |
16 | /**
17 | * 获取指定日期前后num天的日期
18 | * @author yangwk
19 | * @time 2017年9月14日 上午11:13:18
20 | * @param date
21 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期
22 | * @return
23 | */
24 | public static String getDay(String date,int num){
25 | return getDay(date, num,DATE_FORMAT_DEFAULT);
26 | }
27 |
28 | /**
29 | * 获取指定日期前后num天的日期
30 | * @author yangwk
31 | * @time 2017年9月14日 上午11:13:18
32 | * @param date
33 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期
34 | * @param format 日期格式
35 | * @return
36 | */
37 | public static String getDay(String date,int num,String format){
38 | long t = parseStringToLong(date);
39 | return getDay(t, num, DATE_FORMAT_DEFAULT);
40 | }
41 |
42 | /**
43 | * 获取指定日期前后num天的日期
44 | * @author yangwk
45 | * @time 2017年9月14日 上午11:13:18
46 | * @param date
47 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期
48 | * @return
49 | */
50 | public static String getDay(long date,int num){
51 | return getDay(date, num, DATE_FORMAT_DEFAULT);
52 | }
53 |
54 | /**
55 | * 获取指定日期前后num天的日期
56 | * @author yangwk
57 | * @time 2017年9月14日 上午11:13:18
58 | * @param date
59 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期
60 | * @param format 日期格式
61 | * @return
62 | */
63 | public static String getDay(long date,int num,String format){
64 | Calendar calendar = Calendar.getInstance();
65 | calendar.setTimeInMillis(date);
66 | calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+num);
67 | return longToString(calendar.getTimeInMillis(),format);
68 | }
69 |
70 | /**
71 | * 将毫秒时间转换为yyyy-MM-dd格式的时间
72 | * @author yangwenkui
73 | * @time 2017年10月6日 下午5:56:40
74 | * @param time 毫秒数
75 | * @return
76 | */
77 | public static String longToString(long time) {
78 | return longToString(time, DATE_FORMAT_DEFAULT);
79 | }
80 |
81 | /**
82 | * 将毫秒时间转换为指定格式的时间
83 | * @author yangwenkui
84 | * @time 2017年10月6日 下午5:56:40
85 | * @param time 毫秒数
86 | * @param format 日期格式
87 | * @return
88 | */
89 | public static String longToString(long time, String format) {
90 | if (StringUtils.isBlank(format)) {
91 | format = DATE_FORMAT_DEFAULT;
92 | }
93 | DateTime dTime = new DateTime(time);
94 | return dTime.toString(format);
95 | }
96 |
97 | /**
98 | * 获取今天开始的时间
99 | * @author yangwenkui
100 | * @time 2017年10月6日 下午5:58:18
101 | * @return
102 | */
103 | public static Timestamp getTodayStartTime() {
104 | Calendar cal = Calendar.getInstance();
105 | cal.set(Calendar.HOUR_OF_DAY, 0);
106 | cal.set(Calendar.SECOND, 0);
107 | cal.set(Calendar.MINUTE, 0);
108 | cal.set(Calendar.MILLISECOND, 001);
109 | return new Timestamp(cal.getTimeInMillis());
110 | }
111 |
112 | /**
113 | * 获取指定日期开始的当日开始时间
114 | * @author yangwenkui
115 | * @time 2017年10月6日 下午5:58:33
116 | * @param date
117 | * @return
118 | */
119 | public static long getDayStartTime(String date) {
120 | Calendar cal = Calendar.getInstance();
121 | cal.setTimeInMillis(parseStringToLong(date));
122 | cal.set(Calendar.HOUR_OF_DAY, 0);
123 | cal.set(Calendar.SECOND, 0);
124 | cal.set(Calendar.MINUTE, 0);
125 | cal.set(Calendar.MILLISECOND, 001);
126 | return cal.getTimeInMillis();
127 | }
128 |
129 | /**
130 | * 获取指定日期结束时间
131 | * @author yangwenkui
132 | * @time 2017年10月6日 下午5:58:58
133 | * @param date
134 | * @return
135 | */
136 | public static long getDayEndTime(String date) {
137 | Calendar cal = Calendar.getInstance();
138 | cal.setTimeInMillis(parseStringToLong(date));
139 | cal.set(Calendar.HOUR_OF_DAY, 23);
140 | cal.set(Calendar.SECOND, 59);
141 | cal.set(Calendar.MINUTE, 59);
142 | cal.set(Calendar.MILLISECOND, 999);
143 | return cal.getTimeInMillis();
144 | }
145 |
146 | /**
147 | * 获得当前日期
148 | */
149 | public static String getCurrentTime() {
150 | return getCurrentTime("yyyy-MM-dd");
151 | }
152 |
153 | /**
154 | * 获得当前时间
155 | * @param format 日期格式
156 | * @return
157 | */
158 | public static String getCurrentTime(String format) {
159 | DateTime dTime = new DateTime();
160 | return dTime.toString(format);
161 | }
162 |
163 | /**
164 | * 将字符串类型的日期转换为毫秒数
165 | * @author yangwenkui
166 | * @time 2017年10月6日 下午6:00:27
167 | * @param dateStr
168 | * @return
169 | */
170 | public static long parseStringToLong(String dateStr) {
171 | dateStr = dateStr.trim();
172 | if (dateStr.length() == 19 || dateStr.length() == 23) {
173 | try {
174 | java.util.Calendar cal = java.util.Calendar.getInstance();
175 | cal.set(Integer.parseInt(dateStr.substring(0, 4)),
176 | Integer.parseInt(dateStr.substring(5, 7)) - 1,
177 | Integer.parseInt(dateStr.substring(8, 10)),
178 | Integer.parseInt(dateStr.substring(11, 13)),
179 | Integer.parseInt(dateStr.substring(14, 16)),
180 | Integer.parseInt(dateStr.substring(17, 19)));
181 | cal.set(java.util.Calendar.MILLISECOND, 0);
182 | return (cal.getTime().getTime());
183 | } catch (Exception e) {
184 | return 0;
185 | }
186 |
187 | } else if (dateStr.length() == 16) {
188 | try {
189 | java.util.Calendar cal = java.util.Calendar.getInstance();
190 | cal.set(Integer.parseInt(dateStr.substring(0, 4)),
191 | Integer.parseInt(dateStr.substring(5, 7)) - 1,
192 | Integer.parseInt(dateStr.substring(8, 10)),
193 | Integer.parseInt(dateStr.substring(11, 13)),
194 | Integer.parseInt(dateStr.substring(14, 16)));
195 | cal.set(java.util.Calendar.MILLISECOND, 0);
196 | return (cal.getTime().getTime());
197 | } catch (Exception e) {
198 | return 0;
199 | }
200 |
201 | } else if (dateStr.length() == 14) {
202 | try {
203 | java.util.Calendar cal = java.util.Calendar.getInstance();
204 | cal.set(Integer.parseInt(dateStr.substring(0, 4)),
205 | Integer.parseInt(dateStr.substring(4, 6)) - 1,
206 | Integer.parseInt(dateStr.substring(6, 8)),
207 | Integer.parseInt(dateStr.substring(8, 10)),
208 | Integer.parseInt(dateStr.substring(10, 12)),
209 | Integer.parseInt(dateStr.substring(12, 14)));
210 | cal.set(java.util.Calendar.MILLISECOND, 0);
211 | return (cal.getTime().getTime());
212 | } catch (Exception e) {
213 | return 0;
214 | }
215 | } else if (dateStr.length() == 10 || dateStr.length() == 11) {
216 | try {
217 | java.util.Calendar cal = java.util.Calendar.getInstance();
218 | cal.set(Integer.parseInt(dateStr.substring(0, 4)),
219 | Integer.parseInt(dateStr.substring(5, 7)) - 1,
220 | Integer.parseInt(dateStr.substring(8, 10)), 0, 0, 0);
221 | cal.set(java.util.Calendar.MILLISECOND, 0);
222 | return (cal.getTime().getTime());
223 | } catch (Exception e) {
224 | return 0;
225 | }
226 | } else if (dateStr.length() == 8 ) {
227 | try {
228 | java.util.Calendar cal = java.util.Calendar.getInstance();
229 | cal.set(Integer.parseInt(dateStr.substring(0, 4)),
230 | Integer.parseInt(dateStr.substring(4, 6)) - 1,
231 | Integer.parseInt(dateStr.substring(6, 8)), 0, 0, 0);
232 | cal.set(java.util.Calendar.MILLISECOND, 0);
233 | return (cal.getTime().getTime());
234 | } catch (Exception e) {
235 | return 0;
236 | }
237 | } else {
238 | try {
239 | return Long.parseLong(dateStr);
240 | } catch (Exception e) {
241 | return 0;
242 | }
243 |
244 | }
245 | }
246 |
247 | public static void main(String[] args) {
248 | System.out.println(getDay(System.currentTimeMillis(), -30));
249 | }
250 | }
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/FileUtil.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.io.IOException;
6 | import java.util.List;
7 |
8 | import org.apache.commons.io.IOUtils;
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 |
12 | import com.google.common.collect.Lists;
13 |
14 | public class FileUtil {
15 | private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
16 |
17 | /**
18 | * 读取文件内的所有行
19 | * @author yangwk
20 | * @time 2017年9月12日 上午9:46:33
21 | * @param filePath 文件完整路径
22 | * @return
23 | */
24 | public static List getLines(String filePath){
25 | FileInputStream inputStream = null;
26 | List lines = Lists.newArrayList();
27 | try {
28 | inputStream = new FileInputStream(new File(filePath));
29 | lines = IOUtils.readLines(inputStream);
30 | } catch (Exception e) {
31 | logger.error("read file due to error",e);
32 | }finally {
33 | try {
34 | if(inputStream != null){
35 | inputStream.close();
36 | }
37 | } catch (IOException e) {
38 | logger.error("close inputStream due to error",e);
39 | }
40 | }
41 | return lines;
42 | }
43 |
44 | /**
45 | * 写入文件
46 | * @author yangwk
47 | * @time 2017年9月14日 下午1:44:23
48 | * @param file
49 | * @param lines
50 | */
51 | public static void writeLines(File file, List lines) {
52 | try {
53 | org.apache.commons.io.FileUtils.writeLines(file, lines, "\n");
54 | } catch (IOException e) {
55 | logger.error("write lines due to error",e);
56 | }
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/HttpServletHelper.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.util.Map;
4 |
5 | import javax.servlet.http.Cookie;
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | import org.apache.commons.lang3.ArrayUtils;
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.springframework.web.context.request.RequestContextHolder;
12 | import org.springframework.web.context.request.ServletRequestAttributes;
13 |
14 | import com.google.common.base.Joiner;
15 | import com.google.common.base.Joiner.MapJoiner;
16 | import com.google.common.base.Splitter;
17 | import com.google.common.collect.Maps;
18 |
19 | public class HttpServletHelper {
20 |
21 | public static String getCookie(HttpServletRequest request, String key) {
22 | Cookie[] cookies = request.getCookies();
23 |
24 | if(ArrayUtils.isEmpty(cookies)){
25 | return StringUtils.EMPTY;
26 | }
27 |
28 | for (Cookie cookie : cookies) {
29 | if(StringUtils.equals(cookie.getName(), key) ){
30 | return cookie.getValue();
31 | }
32 | }
33 | return StringUtils.EMPTY;
34 | }
35 |
36 |
37 | public static void delCookie(HttpServletResponse response,String key){
38 | Cookie del= new Cookie(key,null);
39 | del.setMaxAge(0);
40 | response.addCookie(del);
41 | }
42 |
43 | public static void delCookie(HttpServletResponse response,String key,String path,String domain){
44 | Cookie del= new Cookie(key,null);
45 | del.setMaxAge(0);
46 | if(StringUtils.isNotBlank(path)){
47 | del.setPath(path);
48 | }
49 | if(StringUtils.isNotBlank(domain)){
50 | del.setDomain(domain);
51 | }
52 | response.addCookie(del);
53 | }
54 |
55 | public static void addCookie(HttpServletResponse response, Cookie cookie){
56 | response.addCookie(cookie);
57 | }
58 |
59 |
60 | //Set-Cookie: =[; =][; expires=][; domain=]=[; path=][; secure][; HttpOnly]
61 | public static void addCookieHttpOnly(HttpServletResponse response, Cookie cookie){
62 |
63 | int maxAge = cookie.getMaxAge();
64 | if(maxAge==0){
65 | return;
66 | }
67 | StringBuilder sb = new StringBuilder(cookie.getName());
68 | sb.append("=");
69 | sb.append(cookie.getValue());
70 |
71 | if(maxAge>0){
72 | sb.append(";").append("Max-Age=").append(cookie.getMaxAge());
73 | }
74 |
75 | if(StringUtils.isNotBlank(cookie.getDomain())){
76 | sb.append(";").append("Domain=").append(cookie.getDomain());
77 | }
78 | if(StringUtils.isNotBlank(cookie.getPath())){
79 | sb.append(";").append("Path=").append(cookie.getPath());
80 | }
81 | sb.append("; HttpOnly");
82 |
83 | String cookieStr = sb.toString();
84 | response.addHeader("Set-Cookie", cookieStr);
85 | //response.setHeader("Set-Cookie", cookieStr); //错误用法,其他cookie会被覆盖
86 | }
87 |
88 |
89 | private static final String SESSION_KEY_CALLBACK = "cb_url";
90 | public static void setCallBackUrl(HttpServletRequest request){
91 |
92 | String callback = getCurrentUrl(request);// eg. /iapp/study/me.do?a=b
93 | request.getSession().setAttribute(SESSION_KEY_CALLBACK, callback);
94 | }
95 |
96 |
97 | public static String getCallBackUrlAndClean(HttpServletRequest request){
98 | String callback =(String) request.getSession().getAttribute(SESSION_KEY_CALLBACK);
99 |
100 | if(StringUtils.isNotBlank(callback)){
101 | request.getSession().removeAttribute(SESSION_KEY_CALLBACK);
102 | }
103 | return callback;
104 | }
105 |
106 | public static String getCurrentUrl(HttpServletRequest request){
107 | return Joiner.on("?").skipNulls().join(request.getRequestURL().toString(), request.getQueryString()); // eg. http://xxx:xx/iapp/study/me.do?a=b
108 |
109 | }
110 |
111 |
112 | /**
113 | * 获取跟路径
114 | * @param request
115 | * @return
116 | */
117 | public static String getRootPath(HttpServletRequest request){
118 | String rootPath = String.format("%s:%s%s", request.getServerName(),request.getServerPort(),request.getContextPath());
119 | return rootPath;
120 | }
121 |
122 | /**
123 | * 获取绝对路径
124 | * @param request
125 | * @param relativePath
126 | * @return
127 | */
128 | public static String getAbsolutePath(HttpServletRequest request,
129 | String relativePath) {
130 | return String.format("http://%s/%s", getRootPath(request),relativePath);
131 | }
132 |
133 |
134 | private static MapJoiner queryStringMapJoiner = Joiner.on("&").withKeyValueSeparator("=");
135 |
136 | public static String replaceQueryString(String queryString, String key, String value) {
137 | Map myMap = Splitter.on("&").trimResults().withKeyValueSeparator("=").split(queryString);
138 | myMap = Maps.newHashMap(myMap);
139 | myMap.put(key, value);
140 | return queryStringMapJoiner.join(myMap);
141 | }
142 |
143 | public static String removeParamQueryString(String queryString, String key) {
144 | Map myMap = Splitter.on("&").trimResults().withKeyValueSeparator("=").split(queryString);
145 | myMap = Maps.newHashMap(myMap);
146 | myMap.remove(key);
147 | return queryStringMapJoiner.join(myMap);
148 | }
149 |
150 | public static String getRequestUri(){
151 | HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
152 | //获取请求的URL
153 | String requestUri = request.getRequestURI();
154 | return requestUri;
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/JacksonHelper.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.io.IOException;
4 | import java.util.Collection;
5 | import java.util.Map;
6 | import java.util.Map.Entry;
7 |
8 | import org.codehaus.jackson.map.ObjectMapper;
9 | import org.codehaus.jackson.type.JavaType;
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 |
13 | public class JacksonHelper {
14 |
15 | private static final ObjectMapper mapper = new ObjectMapper();
16 |
17 | private static Logger logger = LoggerFactory.getLogger(JacksonHelper.class);
18 |
19 |
20 | /**
21 | * 将对象转化为json
22 | * @author yangwenkui
23 | * @time 2017年3月16日 下午2:55:10
24 | * @param obj 待转化的对象
25 | * @return 当转化发生异常时返回null
26 | */
27 | public static String toJson(Object obj){
28 | if(obj == null){
29 | return null;
30 | }
31 | try {
32 | return mapper.writeValueAsString(obj);
33 | } catch (IOException e) {
34 | logger.error(String.format("obj=[%s]", obj.toString()), e);
35 | }
36 | return null;
37 | }
38 |
39 | /**
40 | * 将json转化为对象
41 | * @author yangwenkui
42 | * @time 2017年3月16日 下午2:56:26
43 | * @param json json对象
44 | * @param clazz 待转化的对象类型
45 | * @return 当转化发生异常时返回null
46 | */
47 | public static T fromJson(String json,Class clazz){
48 | if(json == null){
49 | return null;
50 | }
51 | try {
52 | return mapper.readValue(json, clazz);
53 | } catch (IOException e) {
54 | logger.error(String.format("json=[%s]", json), e);
55 | }
56 | return null;
57 | }
58 |
59 | /**
60 | * 将json对象转化为集合类型
61 | * @author yangwenkui
62 | * @time 2017年3月16日 下午2:57:15
63 | * @param json json对象
64 | * @param collectionClazz 具体的集合类的class,如:ArrayList.class
65 | * @param clazz 集合内存放的对象的class
66 | * @return
67 | */
68 | @SuppressWarnings("rawtypes")
69 | public static Collection fromJson(String json,Class extends Collection> collectionClazz,Class clazz){
70 | if(json == null){
71 | return null;
72 | }
73 | try {
74 | Collection collection = mapper.readValue(json, getCollectionType(collectionClazz,clazz));
75 | return collection;
76 | } catch (IOException e) {
77 | logger.error(String.format("json=[%s]", json), e);
78 | }
79 | return null;
80 | }
81 |
82 | private static JavaType getCollectionType(Class> collectionClass, Class>... elementClasses) {
83 | return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
84 | }
85 |
86 | public static void main(String[] args) {
87 | String s = "{\"ss\":\"12\",\"dd\":\"33\",\"tt\":23}";
88 | @SuppressWarnings("unchecked")
89 | Map map = fromJson(s, Map.class);
90 | for (Entry entry : map.entrySet()) {
91 | System.out.println(entry);
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/JsUtils.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.util.List;
6 |
7 | import javax.script.ScriptEngine;
8 | import javax.script.ScriptEngineManager;
9 | import javax.script.ScriptException;
10 |
11 | import org.apache.commons.io.IOUtils;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | public class JsUtils {
16 | private static Logger logger = LoggerFactory.getLogger(JsUtils.class);
17 |
18 | /**
19 | * 获取js代码内的某个变量值
20 | * @author yangwk
21 | * @time 2017年9月7日 下午1:57:46
22 | * @param jsCode
23 | * @param property
24 | * @return
25 | */
26 | public static String getProperty(String jsCode,String property){
27 | try {
28 | ScriptEngineManager manager = new ScriptEngineManager();
29 | ScriptEngine engine = manager.getEngineByName("javascript");
30 | engine.eval(jsCode);
31 | String value = (String) engine.get(property);
32 | return value;
33 | } catch (ScriptException e) {
34 | logger.error(String.format("jsCode=%s,property=%s", jsCode,property),e);
35 | }
36 | return "";
37 | }
38 |
39 | public static void main(String[] args) throws Exception {
40 | List list = IOUtils.readLines(new FileInputStream(new File("D:/workspace/crawler-task/doc/test.js")));
41 | System.out.println(getProperty(list.get(0), "code"));
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/ListOptionHelper.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 |
4 | import java.util.ArrayList;
5 | import java.util.Collection;
6 | import java.util.HashSet;
7 | import java.util.List;
8 | import java.util.Set;
9 |
10 | import org.apache.commons.lang3.StringUtils;
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.google.common.base.Joiner;
15 | import com.google.common.collect.Lists;
16 |
17 | public class ListOptionHelper {
18 |
19 | private static Logger logger = LoggerFactory.getLogger(JacksonHelper.class);
20 |
21 | /**
22 | * 获取在first集合内而不在second集合内的元素
23 | * @param first
24 | * @param second
25 | * @return
26 | */
27 | public static List getDiffList(Collection first, Collection second) {
28 | long t = System.currentTimeMillis();
29 | Set sameString = new HashSet(second);
30 | List result = new ArrayList(first.size());
31 | for (String s : first) {
32 | if (!sameString.contains(s)) {
33 | result.add(s);
34 | }
35 | }
36 | if(System.currentTimeMillis() - t > 1){
37 | logger.debug("getDiffList with list first.size={},sencond.size={},use time={}ms",first.size(),second.size(),System.currentTimeMillis()-t);
38 | }
39 |
40 | return result;
41 | }
42 |
43 | /**
44 | * 获得在list内同时在list2内的元素
45 | * 注意:在结果集内并不去重,如果list内本身有重复,返回的结果内可能包含相同元素
46 | * @param list
47 | * @param list2
48 | * @return
49 | */
50 | public static List getSameElements(Collection list, Collection list2) {
51 | long t = System.nanoTime();
52 | Set set = new HashSet(list2);
53 | List sameElements = new ArrayList(list.size());
54 | for(String item : list){
55 | if(set.contains(item)){
56 | sameElements.add(item);
57 | }
58 | }
59 | if(logger.isDebugEnabled()){
60 | logger.debug("getSameElements list.size={},list2.size={},use time={}ns",list.size(),list2.size(),System.nanoTime()-t);
61 | }
62 | return sameElements;
63 | }
64 |
65 |
66 | /**
67 | * 判断集合list和list2内是否有相同元素
68 | * @param list
69 | * @param list2
70 | * @return
71 | */
72 | public static boolean hasSameItem(List list,List list2){
73 | for (String item : list) {
74 | if(list2.contains(item)){
75 | return true;
76 | }
77 | }
78 | return false;
79 | }
80 |
81 | /**
82 | * 辅助方法,将字符串分割转换为list
83 | * @author yangwenkui
84 | * @time 2017年1月10日 下午4:22:20
85 | * @param provinceIds
86 | * @return
87 | */
88 | public static List stringToList(String str,String split) {
89 | if(StringUtils.isBlank(str)){
90 | return Lists.newArrayList();
91 | }
92 | String[] arr = str.split(split);
93 | List list = new ArrayList(arr.length);
94 | for(String item : arr){
95 | if(StringUtils.isNotBlank(item)){
96 | list.add(item);
97 | }
98 | }
99 | return list;
100 | }
101 |
102 | public static void main(String[] args) {
103 |
104 | for(int j=0;j<20;j++){
105 | List all = Lists.newArrayList();
106 | for(int i=1000000;i<1001500;i++){
107 | all.add(String.valueOf(i));
108 | }
109 |
110 | List hasSend = Lists.newArrayList();
111 | for(int i=1000000;i<1000500;i++){
112 | hasSend.add(String.valueOf(i));
113 | }
114 | long t = System.nanoTime();
115 | // List list = getDiffList1(all, hasSend);//12ms
116 | // all.removeAll(hasSend);//9ms
117 | List list = getDiffList(all, hasSend);//2ms 当前选用 20次调用时平均耗时0.2ms
118 | // List list = getSameElements1(all, hasSend);//8ms
119 | // List list = getSameElements2(all, hasSend);//6ms
120 | // List list = getSameElements(all, hasSend);//1ms 当前选用
121 | System.out.println(System.nanoTime()-t);
122 | System.out.println("size="+list.size()+JacksonHelper.toJson(list));
123 | }
124 | }
125 |
126 |
127 |
128 |
129 |
130 | /**以下方法因低效,放弃使用*/
131 | // public static List getDiffList1(List firstList, List secondList) {
132 | // if(CollectionUtils.isEmpty(firstList)){
133 | // return Lists.newArrayList();
134 | // }
135 | // if(CollectionUtils.isEmpty(secondList)){
136 | // return firstList;
137 | // }
138 | //
139 | // List results = Lists.newArrayList();
140 | // for(String item : firstList){
141 | // if(!secondList.contains(item)){
142 | // results.add(item);
143 | // }
144 | // }
145 | // return results;
146 | // }
147 |
148 | // @SuppressWarnings("unchecked")
149 | // public static List getSameElements1(List list, List list2) {
150 | // return new ArrayList(CollectionUtils.intersection(list, list2));
151 | // }
152 |
153 | // public static List getSameElements2(List list, List list2) {
154 | // List sameElements = Lists.newArrayList();
155 | // for(String item : list){
156 | // if(list2.contains(item)){
157 | // sameElements.add(item);
158 | // }
159 | // }
160 | // return sameElements;
161 | // }
162 |
163 | }
164 |
165 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/LoginSessionHelper.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import org.apache.shiro.SecurityUtils;
4 | import org.apache.shiro.subject.Subject;
5 | import org.springframework.web.context.request.RequestContextHolder;
6 |
7 | public class LoginSessionHelper {
8 |
9 | /**
10 | * 返回当前用户ID
11 | * @return
12 | */
13 | public static int getCurrentUserId(){
14 | Subject currentUser = SecurityUtils.getSubject();
15 | if(currentUser == null || currentUser.getPrincipal() == null){
16 | return 0;
17 | }
18 | Integer userId = (Integer) currentUser.getPrincipal();
19 | return userId;
20 | }
21 |
22 | /**
23 | * 返回当前用户唯一标记,当用户已登录,返回用户ID,当用户未登录,返回sessionId
24 | * @return
25 | */
26 | public static String getCurrentUserKey(){
27 | Subject currentUser = SecurityUtils.getSubject();
28 | Integer userId = (Integer) currentUser.getPrincipal();
29 | if(userId == null){
30 | String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
31 | return sessionId;
32 | }
33 | return String.valueOf(userId);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/MD5.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.security.MessageDigest;
4 |
5 |
6 |
7 | /**MD5加密算法
8 | * @author songsp 2010-1-13
9 | *
10 | */
11 | public class MD5 {
12 | public final static String encodeMd5(String s) {
13 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
14 | 'a', 'b', 'c', 'd', 'e', 'f' };
15 | try {
16 | byte[] strTemp = s.getBytes();
17 | MessageDigest mdTemp = MessageDigest.getInstance("MD5");//返回实现MD5摘要算法的 MessageDigest 对象
18 | mdTemp.update(strTemp);//使用指定的字节更新摘要
19 | byte[] md = mdTemp.digest();// 得到md5算法结果 //通过执行诸如填充之类的最终操作完成哈希计算
20 | int j = md.length;
21 | char str[] = new char[j * 2];
22 | int k = 0;
23 | for (int i = 0; i < j; i++) {
24 | byte byte0 = md[i];
25 | str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 分成高低4位处理
26 | str[k++] = hexDigits[byte0 & 0xf];
27 | }
28 | return new String(str);
29 | } catch (Exception e) {
30 | return null;
31 | }
32 | }
33 |
34 |
35 |
36 | public static void main(String[] args) {
37 | String key = System.currentTimeMillis()+"";
38 | System.out.println(key);
39 | System.out.println(MD5.encodeMd5("md5cenwavepublickey"+key+"cenwave1000001"));
40 | System.out.println(MD5.encodeMd5("bosskey2010-05-30 16:00:002010-06-08 15:59:59"));
41 |
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/OperationCheck.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | public class OperationCheck {
4 |
5 | /**
6 | * 校验数据拥有者是否是当前用户
7 | * @author yangwk
8 | * @time 2017年7月27日 上午9:52:05
9 | * @param uid 数据拥有者ID
10 | * @return
11 | */
12 | public static boolean isOwnerCurrentUser(int uid){
13 | if(uid == LoginSessionHelper.getCurrentUserId()){
14 | return true;
15 | }
16 | return false;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/RandomUtils.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.util.Random;
4 |
5 | public class RandomUtils {
6 |
7 | private static final int[] numArr = {0,1,2,3,4,5,6,7,8,9};
8 |
9 | /**
10 | * 随机获取两位数字
11 | * @author yangwk
12 | * @time 2017年7月28日 下午3:26:44
13 | * @param length 数字长度
14 | * @return
15 | */
16 | public static String randomNum(int length){
17 | StringBuilder builder = new StringBuilder();
18 | Random random = new Random();
19 | for(int i=0;i i){
57 | builder.append(saltLast.charAt(i));
58 | }
59 | builder.append(pwd.charAt(i));
60 | }
61 | if(saltLast.length() > pwd.length()){
62 | builder.append(saltLast.substring(pwd.length()));
63 | }
64 | return builder.toString();
65 | }
66 |
67 | public static void main(String[] args) {
68 | String salt = "HpsuQ2d4FkqjGU01";//getSalt();
69 | System.err.println(salt);
70 | System.err.println(encode("eva2017admin", salt));
71 | }
72 |
73 | }
74 |
75 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/ServiceStatusEnum.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | /**
4 | * 全局性状态码
5 | * @author yangwk
6 | */
7 | public enum ServiceStatusEnum {
8 | UNLOGIN("0001"), //未登录
9 | ILLEGAL_TOKEN("0002"),//非法的token
10 | ;
11 | public String code;
12 |
13 | private ServiceStatusEnum(String code){
14 | this.code = code;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/SpringContextUtil.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.util.Locale;
4 |
5 | import org.springframework.beans.BeansException;
6 | import org.springframework.context.ApplicationContext;
7 | import org.springframework.context.ApplicationContextAware;
8 | import org.springframework.stereotype.Component;
9 |
10 | @Component
11 | public class SpringContextUtil implements ApplicationContextAware {
12 |
13 | private static ApplicationContext context;
14 |
15 | @SuppressWarnings("static-access")
16 | @Override
17 | public void setApplicationContext(ApplicationContext contex)
18 | throws BeansException {
19 | this.context=contex;
20 | }
21 | public static Object getBean(String beanName){
22 | return context.getBean(beanName);
23 | }
24 |
25 | public static T getBean(Class requiredType){
26 | return context.getBean(requiredType);
27 | }
28 |
29 | public T getBean(String name, Class requiredType) {
30 | return context.getBean(name, requiredType);
31 | }
32 |
33 | public static String getMessage(String key){
34 | return context.getMessage(key, null, Locale.getDefault());
35 | }
36 |
37 | public static ApplicationContext getApplicationContext(){
38 | return context;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/onecoderspace/base/util/ThreadLocalUtils.java:
--------------------------------------------------------------------------------
1 | package com.onecoderspace.base.util;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * 注意在线程内部使用完后手动调用remove方法,避免某些使用线程池的地方出现内存泄漏|数据错误等诡异问题
8 | * @author Administrator
9 | *
10 | */
11 | public final class ThreadLocalUtils {
12 | private static final ThreadLocal