Commit 9a56ec743c53748fd85e1fec7211d01c25c66599
1 parent
c849dbc7
增加权限及全局异常统一封装
Showing
9 changed files
with
516 additions
and
29 deletions
src/main/java/com/zteits/oa/api/base/annotation/NoAuth.java
0 → 100644
1 | +package com.zteits.oa.api.base.annotation; | ||
2 | + | ||
3 | +import java.lang.annotation.Documented; | ||
4 | +import java.lang.annotation.ElementType; | ||
5 | +import java.lang.annotation.Retention; | ||
6 | +import java.lang.annotation.RetentionPolicy; | ||
7 | +import java.lang.annotation.Target; | ||
8 | + | ||
9 | +/** | ||
10 | + * Copyright: Copyright (c) 2017 zteits | ||
11 | + * | ||
12 | + * @ClassName: com.clouds.common.annotation | ||
13 | + * @Description: 此注解为不进行权限校验的注解,标注到方法、类上 | ||
14 | + * @version: v1.0.0 | ||
15 | + * @author: atao | ||
16 | + * @date: 2017/7/10 下午7:07 | ||
17 | + * Modification History: | ||
18 | + * Date Author Version Description | ||
19 | + * ---------------------------------------------------------* | ||
20 | + * 2017/7/10 atao v1.0.0 创建 | ||
21 | + */ | ||
22 | +@Documented | ||
23 | +@Retention(RetentionPolicy.RUNTIME) | ||
24 | +@Target({ElementType.METHOD, ElementType.TYPE}) | ||
25 | +public @interface NoAuth { | ||
26 | + /** | ||
27 | + * 描述 | ||
28 | + * @return | ||
29 | + */ | ||
30 | + String desc() default ""; | ||
31 | + | ||
32 | + /** | ||
33 | + * 测试环境下是否需要权限认证 默认不需要 | ||
34 | + * @return | ||
35 | + */ | ||
36 | + boolean dev() default false; | ||
37 | + | ||
38 | + /** | ||
39 | + * 生产环境下是否需要权限认证 默认需要 | ||
40 | + * @return | ||
41 | + */ | ||
42 | + boolean pro() default true; | ||
43 | + | ||
44 | + | ||
45 | +} |
src/main/java/com/zteits/oa/api/base/bean/BizResult.java
@@ -39,7 +39,7 @@ public class BizResult<T> extends ResultBean<ErrorCode, T>{ | @@ -39,7 +39,7 @@ public class BizResult<T> extends ResultBean<ErrorCode, T>{ | ||
39 | 39 | ||
40 | public BizResult(T data) { | 40 | public BizResult(T data) { |
41 | super(data); | 41 | super(data); |
42 | - this.errCode=ErrorType.BIZ_SUCCESS; | 42 | + this.errCode=ErrorType.BIZ_SUCCESS.getCode(); |
43 | this.errMsg = ErrorType.BIZ_SUCCESS.getMsg(); | 43 | this.errMsg = ErrorType.BIZ_SUCCESS.getMsg(); |
44 | 44 | ||
45 | } | 45 | } |
@@ -49,7 +49,7 @@ public class BizResult<T> extends ResultBean<ErrorCode, T>{ | @@ -49,7 +49,7 @@ public class BizResult<T> extends ResultBean<ErrorCode, T>{ | ||
49 | } | 49 | } |
50 | 50 | ||
51 | public void setErrorInfo(ErrorType errType, String errMsg){ | 51 | public void setErrorInfo(ErrorType errType, String errMsg){ |
52 | - this.errCode = errType; | 52 | + this.errCode = errType.getCode(); |
53 | this.errMsg = errMsg; | 53 | this.errMsg = errMsg; |
54 | this.success = false; | 54 | this.success = false; |
55 | } | 55 | } |
src/main/java/com/zteits/oa/api/base/bean/ResultBean.java
@@ -13,7 +13,7 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | @@ -13,7 +13,7 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | ||
13 | boolean success; | 13 | boolean success; |
14 | String errMsg; | 14 | String errMsg; |
15 | DATA data; | 15 | DATA data; |
16 | - CODE errCode; | 16 | + String errCode; |
17 | String helpMsg; | 17 | String helpMsg; |
18 | 18 | ||
19 | public ResultBean() { | 19 | public ResultBean() { |
@@ -28,24 +28,24 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | @@ -28,24 +28,24 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | ||
28 | this.success = success; | 28 | this.success = success; |
29 | } | 29 | } |
30 | public ResultBean(CODE errCode) { | 30 | public ResultBean(CODE errCode) { |
31 | - this.errCode = errCode; | 31 | + this.errCode = errCode.getCode(); |
32 | this.success = false; | 32 | this.success = false; |
33 | } | 33 | } |
34 | public ResultBean(CODE errCode,String errMsg) { | 34 | public ResultBean(CODE errCode,String errMsg) { |
35 | - this.errCode = errCode; | 35 | + this.errCode = errCode.getCode(); |
36 | this.errMsg = errMsg; | 36 | this.errMsg = errMsg; |
37 | this.success = false; | 37 | this.success = false; |
38 | } | 38 | } |
39 | 39 | ||
40 | public ResultBean(CODE errCode,String errMsg, DATA data) { | 40 | public ResultBean(CODE errCode,String errMsg, DATA data) { |
41 | - this.errCode = errCode; | 41 | + this.errCode = errCode.getCode(); |
42 | this.errMsg = errMsg; | 42 | this.errMsg = errMsg; |
43 | this.data = data; | 43 | this.data = data; |
44 | this.success = false; | 44 | this.success = false; |
45 | } | 45 | } |
46 | 46 | ||
47 | public ResultBean(boolean success, CODE errCode,String errMsg, DATA data) { | 47 | public ResultBean(boolean success, CODE errCode,String errMsg, DATA data) { |
48 | - this.errCode = errCode; | 48 | + this.errCode = errCode.getCode(); |
49 | this.errMsg = errMsg; | 49 | this.errMsg = errMsg; |
50 | this.data = data; | 50 | this.data = data; |
51 | this.success = success; | 51 | this.success = success; |
@@ -88,7 +88,7 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | @@ -88,7 +88,7 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | ||
88 | * 重新初始化bean的所有属性 | 88 | * 重新初始化bean的所有属性 |
89 | */ | 89 | */ |
90 | public void init(boolean success, CODE errCode,String errMsg, DATA data) { | 90 | public void init(boolean success, CODE errCode,String errMsg, DATA data) { |
91 | - this.errCode = errCode; | 91 | + this.errCode = errCode.getCode(); |
92 | this.errMsg = errMsg; | 92 | this.errMsg = errMsg; |
93 | this.data = data; | 93 | this.data = data; |
94 | this.success = success; | 94 | this.success = success; |
@@ -119,10 +119,10 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | @@ -119,10 +119,10 @@ public class ResultBean<CODE extends ErrorCode,DATA> implements Serializable { | ||
119 | 119 | ||
120 | 120 | ||
121 | } | 121 | } |
122 | - public ErrorCode getErrCode() { | 122 | + public String getErrCode() { |
123 | return errCode; | 123 | return errCode; |
124 | } | 124 | } |
125 | - public void setErrCode(CODE errCode) { | 125 | + public void setErrCode(String errCode) { |
126 | this.errCode = errCode; | 126 | this.errCode = errCode; |
127 | } | 127 | } |
128 | /** | 128 | /** |
src/main/java/com/zteits/oa/configuration/ControllerExceptionHandler.java
0 → 100644
1 | +package com.zteits.oa.configuration; | ||
2 | + | ||
3 | +import java.util.List; | ||
4 | +import java.util.UUID; | ||
5 | + | ||
6 | +import javax.servlet.http.HttpServletRequest; | ||
7 | +import javax.servlet.http.HttpServletResponse; | ||
8 | +import javax.validation.ConstraintViolationException; | ||
9 | + | ||
10 | +import org.slf4j.Logger; | ||
11 | +import org.slf4j.LoggerFactory; | ||
12 | +import org.springframework.beans.factory.annotation.Value; | ||
13 | +import org.springframework.boot.autoconfigure.web.AbstractErrorController; | ||
14 | +import org.springframework.boot.autoconfigure.web.ErrorAttributes; | ||
15 | +import org.springframework.core.Ordered; | ||
16 | +import org.springframework.core.annotation.Order; | ||
17 | +import org.springframework.http.HttpStatus; | ||
18 | +import org.springframework.http.ResponseEntity; | ||
19 | +import org.springframework.stereotype.Controller; | ||
20 | +import org.springframework.validation.BindingResult; | ||
21 | +import org.springframework.web.bind.MethodArgumentNotValidException; | ||
22 | +import org.springframework.web.bind.annotation.ControllerAdvice; | ||
23 | +import org.springframework.web.bind.annotation.ExceptionHandler; | ||
24 | +import org.springframework.web.bind.annotation.RequestMapping; | ||
25 | +import org.springframework.web.bind.annotation.ResponseBody; | ||
26 | +import org.springframework.web.bind.annotation.ResponseStatus; | ||
27 | +import org.springframework.web.servlet.ModelAndView; | ||
28 | +import org.springframework.web.servlet.NoHandlerFoundException; | ||
29 | + | ||
30 | +import com.alibaba.fastjson.JSON; | ||
31 | +import com.alibaba.fastjson.JSONObject; | ||
32 | +import com.zteits.oa.api.base.annotation.NoAuth; | ||
33 | +import com.zteits.oa.api.base.bean.BizResult; | ||
34 | +import com.zteits.oa.api.base.constants.ErrorType; | ||
35 | +import com.zteits.oa.api.base.exception.AppException; | ||
36 | +import com.zteits.oa.api.base.exception.BizException; | ||
37 | +import com.zteits.oa.util.BeanValidatorsUtils; | ||
38 | + | ||
39 | + | ||
40 | +/** | ||
41 | + * 通用错误处理器 | ||
42 | + * | ||
43 | + * Copyright: Copyright (c) 2017 zteits | ||
44 | + * | ||
45 | + * @ClassName: ControllerExceptionHandler.java | ||
46 | + * @Description: | ||
47 | + * @version: v1.0.0 | ||
48 | + * @author: zhaowg | ||
49 | + * @date: 2017年5月8日 上午11:50:23 | ||
50 | + * Modification History: | ||
51 | + * Date Author Version Description | ||
52 | + * ---------------------------------------------------------* | ||
53 | + * 2017年5月8日 zhaowg v1.0.0 创建 | ||
54 | + */ | ||
55 | +@Order(Ordered.HIGHEST_PRECEDENCE) | ||
56 | +@ControllerAdvice | ||
57 | +@Controller | ||
58 | +@RequestMapping("${server.error.path:${error.path:/error}}") | ||
59 | +public class ControllerExceptionHandler extends AbstractErrorController { | ||
60 | + | ||
61 | + public ControllerExceptionHandler(ErrorAttributes errorAttributes) { | ||
62 | + super(errorAttributes); | ||
63 | + } | ||
64 | + | ||
65 | + private static final Logger log = LoggerFactory.getLogger(ControllerExceptionHandler.class); | ||
66 | + | ||
67 | + @Value("${server.error.path:${error.path:/error}}") | ||
68 | + private static String errorPath = "/error"; | ||
69 | + | ||
70 | + /** | ||
71 | + * 500错误. | ||
72 | + * | ||
73 | + * @param req | ||
74 | + * @param rsp | ||
75 | + * @param ex | ||
76 | + * @return | ||
77 | + * @throws Exception | ||
78 | + */ | ||
79 | + @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) | ||
80 | + @ExceptionHandler(Exception.class) | ||
81 | + @NoAuth | ||
82 | + public ResponseEntity<BizResult<?>> serverError(HttpServletRequest req, HttpServletResponse rsp, Exception ex) throws Exception { | ||
83 | + String uuid = UUID.randomUUID().toString().toUpperCase().replace("-", ""); | ||
84 | + log.error("\n############################ "+uuid+",请求地址:{},500错误 #############################",req.getRequestURI()); | ||
85 | + BizResult<?> BizResult = null; | ||
86 | + if(ex instanceof AppException) { | ||
87 | + AppException bizException = (AppException)ex; | ||
88 | + BizResult = new BizResult<>(bizException.getErrCode(),bizException.getErrMsg()); | ||
89 | + log.error("\n############################ "+uuid+",后场返回的错误信息为: #############################\n"+bizException.getErrMsg()); | ||
90 | + }else if(ex instanceof ConstraintViolationException){ | ||
91 | + List<String> errMsgs = BeanValidatorsUtils.extractPropertyAndMessageAsList((ConstraintViolationException)ex, ": "); | ||
92 | + BizResult = new BizResult<>(ErrorType.PARAM_NOT_VALID, JSON.toJSONString(errMsgs)); | ||
93 | + }else{ | ||
94 | + BizResult = new BizResult<>(ErrorType.SYSTEM_ERROR,ex.getMessage()); | ||
95 | + log.error("\n############################ "+uuid+",前台报错堆栈信息为: #############################",ex); | ||
96 | + } | ||
97 | + | ||
98 | + log.info("封装后的错误信息:\n"+JSONObject.toJSON(BizResult)); | ||
99 | + return new ResponseEntity<>(BizResult, HttpStatus.OK); | ||
100 | + } | ||
101 | + | ||
102 | + /** | ||
103 | + * 404的拦截. | ||
104 | + * | ||
105 | + * @param request | ||
106 | + * @param response | ||
107 | + * @param ex | ||
108 | + * @return | ||
109 | + * @throws Exception | ||
110 | + */ | ||
111 | + @ResponseStatus(code = HttpStatus.NOT_FOUND) | ||
112 | + @ExceptionHandler(NoHandlerFoundException.class) | ||
113 | + @NoAuth | ||
114 | + public ResponseEntity<?> notFound(HttpServletRequest request, HttpServletResponse response, Exception ex) | ||
115 | + throws Exception { | ||
116 | + log.error("请求地址:{},404错误", request.getRequestURI(), ex); | ||
117 | + BizResult<?> BizResult = new BizResult<>(ErrorType.RESOURCE_NOT_EXISTS); | ||
118 | + log.info("封装后的错误信息:\n"+JSONObject.toJSON(BizResult)); | ||
119 | + return new ResponseEntity<>(BizResult, HttpStatus.OK); | ||
120 | + } | ||
121 | + | ||
122 | + /** | ||
123 | + * 400 参数不完整错误. | ||
124 | + * | ||
125 | + * @param req | ||
126 | + * @param rsp | ||
127 | + * @param ex | ||
128 | + * @return | ||
129 | + * @throws Exception | ||
130 | + */ | ||
131 | + @ResponseStatus(code = HttpStatus.BAD_REQUEST) | ||
132 | + @ExceptionHandler(MethodArgumentNotValidException.class) | ||
133 | + @NoAuth | ||
134 | + public ResponseEntity<?> methodArgumentNotValidException(HttpServletRequest req, HttpServletResponse rsp, | ||
135 | + MethodArgumentNotValidException ex) throws Exception { | ||
136 | + log.error("请求地址:{},400错误:", req.getRequestURI(),ex); | ||
137 | + | ||
138 | + BindingResult result = ex.getBindingResult(); | ||
139 | + List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors(); | ||
140 | + StringBuffer msg = new StringBuffer(); | ||
141 | + msg.append("["); | ||
142 | + fieldErrors.stream().forEach(fieldError -> { | ||
143 | + msg.append(fieldError.getField() + ":" + fieldError.getDefaultMessage()); | ||
144 | + }); | ||
145 | + msg.append("]"); | ||
146 | + | ||
147 | + BizResult<?> BizResult = new BizResult<>(ErrorType.PARAM_NOT_VALID, msg.toString()); | ||
148 | + log.info("封装后的错误信息:\n"+JSONObject.toJSON(BizResult)); | ||
149 | + return new ResponseEntity<>(BizResult, HttpStatus.OK); | ||
150 | + } | ||
151 | + | ||
152 | + @RequestMapping | ||
153 | + @ResponseBody | ||
154 | + @NoAuth | ||
155 | + public ResponseEntity<?> handleErrors(HttpServletRequest request, HttpServletResponse response) throws Exception { | ||
156 | + HttpStatus status = getStatus(request); | ||
157 | + if (status == HttpStatus.NOT_FOUND) { | ||
158 | + return notFound(request, response, new BizException(ErrorType.RESOURCE_NOT_EXISTS)); | ||
159 | + } | ||
160 | + | ||
161 | + if (status == HttpStatus.BAD_REQUEST){ | ||
162 | + return new ResponseEntity<BizResult>( new BizResult<>(ErrorType.PARAM_NOT_VALID, "参数异常"), | ||
163 | + HttpStatus.OK); | ||
164 | + } | ||
165 | + | ||
166 | + if (status == HttpStatus.INTERNAL_SERVER_ERROR){ | ||
167 | + return serverError(request, response, new BizException(ErrorType.APP_ERROR)); | ||
168 | + } | ||
169 | + | ||
170 | + | ||
171 | + return new ResponseEntity<BizResult>( new BizResult<>(ErrorType.APP_ERROR, "系统异常"), | ||
172 | + HttpStatus.OK); | ||
173 | + } | ||
174 | + | ||
175 | + @RequestMapping(produces = "text/html") | ||
176 | + @NoAuth | ||
177 | + public ModelAndView handleHtml(HttpServletRequest request, HttpServletResponse response) throws Exception { | ||
178 | + return null; | ||
179 | + } | ||
180 | + | ||
181 | + @Override | ||
182 | + @NoAuth | ||
183 | + public String getErrorPath() { | ||
184 | + return errorPath; | ||
185 | + } | ||
186 | +} | ||
0 | \ No newline at end of file | 187 | \ No newline at end of file |
src/main/java/com/zteits/oa/configuration/WebMvcConfig.java
1 | package com.zteits.oa.configuration; | 1 | package com.zteits.oa.configuration; |
2 | 2 | ||
3 | +import org.slf4j.Logger; | ||
4 | +import org.slf4j.LoggerFactory; | ||
5 | +import org.springframework.beans.factory.annotation.Autowired; | ||
3 | import org.springframework.context.annotation.Configuration; | 6 | import org.springframework.context.annotation.Configuration; |
4 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; | 7 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; |
5 | -import org.springframework.web.servlet.config.annotation.InterceptorRegistration; | ||
6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; | 8 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; |
7 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; | 9 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; |
8 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; | 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; |
9 | 11 | ||
12 | +import com.zteits.oa.configuration.auth.AuthInterceptor; | ||
13 | + | ||
10 | @Configuration | 14 | @Configuration |
11 | @EnableWebMvc | 15 | @EnableWebMvc |
12 | public class WebMvcConfig extends WebMvcConfigurerAdapter { | 16 | public class WebMvcConfig extends WebMvcConfigurerAdapter { |
13 | 17 | ||
18 | + private Logger logger = LoggerFactory.getLogger(WebMvcConfig.class); | ||
19 | + | ||
20 | + @Autowired | ||
21 | + private AuthInterceptor authInterceptor; | ||
22 | + | ||
14 | @Override | 23 | @Override |
15 | public void addResourceHandlers(ResourceHandlerRegistry registry) { | 24 | public void addResourceHandlers(ResourceHandlerRegistry registry) { |
16 | registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); | 25 | registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); |
@@ -20,23 +29,20 @@ public class WebMvcConfig extends WebMvcConfigurerAdapter { | @@ -20,23 +29,20 @@ public class WebMvcConfig extends WebMvcConfigurerAdapter { | ||
20 | .addResourceLocations("classpath:/META-INF/resources/webjars/"); | 29 | .addResourceLocations("classpath:/META-INF/resources/webjars/"); |
21 | 30 | ||
22 | } | 31 | } |
23 | - | ||
24 | /** | 32 | /** |
25 | - * 实现登陆拦截.<br/> | ||
26 | - */ | ||
27 | -// @Override | ||
28 | -// public void addInterceptors(InterceptorRegistry registry) { | ||
29 | -// InterceptorRegistration addInterceptor = null;//registry.addInterceptor(); | ||
30 | -// | ||
31 | -// addInterceptor.excludePathPatterns("/error"); | ||
32 | -// | ||
33 | -// addInterceptor.excludePathPatterns("/login**"); | ||
34 | -// | ||
35 | -// addInterceptor.addPathPatterns("/**"); | ||
36 | -// | ||
37 | -// | ||
38 | -// | ||
39 | -// } | ||
40 | - | 33 | + * sessionid 拦截 |
34 | + */ | ||
35 | + @Override | ||
36 | + public void addInterceptors(InterceptorRegistry registry) { | ||
37 | + //添加验证拦截器 | ||
38 | + registry.addInterceptor(authInterceptor) | ||
39 | + .addPathPatterns("/**") | ||
40 | + .excludePathPatterns("/oauth/**") | ||
41 | + .excludePathPatterns("/selectItem/**") | ||
42 | + .excludePathPatterns("/swagger-ui.html/**") | ||
43 | + .excludePathPatterns("/swagger-resources/**") | ||
44 | + .excludePathPatterns("/v2/**"); | ||
45 | + } | ||
46 | + | ||
41 | 47 | ||
42 | -} | 48 | + } |
src/main/java/com/zteits/oa/configuration/auth/AuthInterceptor.java
0 → 100644
1 | +package com.zteits.oa.configuration.auth; | ||
2 | + | ||
3 | +import java.io.PrintWriter; | ||
4 | +import java.util.List; | ||
5 | + | ||
6 | +import javax.servlet.http.HttpServletRequest; | ||
7 | +import javax.servlet.http.HttpServletResponse; | ||
8 | +import javax.servlet.http.HttpSession; | ||
9 | + | ||
10 | +import org.slf4j.Logger; | ||
11 | +import org.slf4j.LoggerFactory; | ||
12 | +import org.springframework.http.HttpStatus; | ||
13 | +import org.springframework.stereotype.Component; | ||
14 | +import org.springframework.util.CollectionUtils; | ||
15 | +import org.springframework.web.method.HandlerMethod; | ||
16 | +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; | ||
17 | + | ||
18 | +import com.alibaba.fastjson.JSONObject; | ||
19 | +import com.zteits.oa.api.base.annotation.NoAuth; | ||
20 | +import com.zteits.oa.api.base.bean.BizResult; | ||
21 | +import com.zteits.oa.api.base.constants.ErrorType; | ||
22 | +import com.zteits.oa.api.base.constants.SessionEnum; | ||
23 | +import com.zteits.oa.api.dto.asraop.LoginOathRes; | ||
24 | + | ||
25 | +/** | ||
26 | + * Copyright: Copyright (c) 2017 zteits | ||
27 | + * | ||
28 | + * @ClassName: com.clouds.common.web.auth | ||
29 | + * @Description: | ||
30 | + * @version: v1.0.0 | ||
31 | + * @author: atao | ||
32 | + * @date: 2017/5/11 上午9:34 | ||
33 | + * Modification History: | ||
34 | + * Date Author Version Description | ||
35 | + * ---------------------------------------------------------* | ||
36 | + * 2017/5/11 atao v1.0.0 创建 | ||
37 | + */ | ||
38 | +@Component | ||
39 | +public class AuthInterceptor extends HandlerInterceptorAdapter { | ||
40 | + | ||
41 | + private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class); | ||
42 | + | ||
43 | + private static final String MIME_JSON = "application/json;charset=UTF-8"; | ||
44 | + | ||
45 | +// @Autowired | ||
46 | +// private RedisCacheUtil redisCacheUtil; | ||
47 | + | ||
48 | + //在请求进入controller前进行拦截 | ||
49 | + @Override | ||
50 | + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) | ||
51 | + throws Exception { | ||
52 | + log.info("===开始校验用户权限校验======"); | ||
53 | + log.info("===开始校验用户权限校验 url为{}",request.getRequestURI()); | ||
54 | + if(!isNeedAuth(handler)){ | ||
55 | + log.info("===不需要进行权限校验"); | ||
56 | + return true; | ||
57 | + } | ||
58 | + HttpSession session = request.getSession(); | ||
59 | + System.out.println(request.getRequestURI()); | ||
60 | + System.out.println("获取到的session="+session.getId()); | ||
61 | + //定义初始化的变量 | ||
62 | + Object object = session.getAttribute(SessionEnum.USER_INFO.key()); | ||
63 | + if (null == object) { | ||
64 | + log.info("===权限校验,用户未登陆!"); | ||
65 | + setErrorResult(response, ErrorType.AUTH_TOKEN_NOT_EXISTS); | ||
66 | + return false; | ||
67 | + } | ||
68 | + //LoginOathRes userInfo = (LoginOathRes)object; | ||
69 | + | ||
70 | + | ||
71 | + | ||
72 | + return true; | ||
73 | + } | ||
74 | + | ||
75 | + /** | ||
76 | + * 返回错误结果 | ||
77 | + * | ||
78 | + * @param response | ||
79 | + * @param errortype 错误类型 | ||
80 | + * @throws Exception | ||
81 | + */ | ||
82 | + private void setErrorResult(HttpServletResponse response, ErrorType errortype) throws Exception { | ||
83 | + log.info("===校验用户权限 校验失败: ErrorType:errorCode={},errMsg={}", errortype.getCode(), errortype.getMsg()); | ||
84 | + PrintWriter writer = response.getWriter(); | ||
85 | + response.setCharacterEncoding("UTF-8"); | ||
86 | + response.setHeader("Content-type", MIME_JSON); | ||
87 | + response.setContentType(MIME_JSON); | ||
88 | + BizResult<?> bizResult = new BizResult<>(errortype); | ||
89 | + response.setStatus(HttpStatus.OK.value()); | ||
90 | + writer.write(JSONObject.toJSON(bizResult).toString()); | ||
91 | + writer.close(); | ||
92 | + } | ||
93 | + | ||
94 | + /** | ||
95 | + * 判断此次请求是否需要进行鉴权 | ||
96 | + * @param handler | ||
97 | + * @return true 需要权限校验 false 不需要权限校验 | ||
98 | + */ | ||
99 | + private boolean isNeedAuth(Object handler){ | ||
100 | + log.info("==权限校验 判断是否需要进行权限校验"); | ||
101 | + boolean flag = true; | ||
102 | + if(handler instanceof HandlerMethod){ | ||
103 | + | ||
104 | + HandlerMethod handlerMethod = (HandlerMethod)handler; | ||
105 | + log.info("===访问的Controller 为{},请求的方法为{}",handlerMethod.getBeanType().getName(),handlerMethod.getMethod().getName()); | ||
106 | + | ||
107 | + log.info(handlerMethod.getBeanType().getName()); | ||
108 | + | ||
109 | + boolean authFlag=handlerMethod.getBeanType().isAnnotationPresent(NoAuth.class); | ||
110 | + if(authFlag){ | ||
111 | + //如果Controller类上标注了NoAuth,整个类里面的方法都不需要进行权限校验 | ||
112 | + return !authFlag; | ||
113 | + } | ||
114 | + | ||
115 | + authFlag = handlerMethod.hasMethodAnnotation(NoAuth.class); | ||
116 | + return !authFlag; | ||
117 | + } | ||
118 | + log.info("==权限校验 判断是否需要进行权限校验 flag={}",flag); | ||
119 | + return flag; | ||
120 | + } | ||
121 | + | ||
122 | +} | ||
123 | + | ||
124 | + |
src/main/java/com/zteits/oa/report/biz/AsraProjectServiceImpl.java
@@ -10,6 +10,8 @@ import org.springframework.stereotype.Service; | @@ -10,6 +10,8 @@ import org.springframework.stereotype.Service; | ||
10 | 10 | ||
11 | import com.alibaba.fastjson.JSONObject; | 11 | import com.alibaba.fastjson.JSONObject; |
12 | import com.zteits.oa.api.base.bean.BizResult; | 12 | import com.zteits.oa.api.base.bean.BizResult; |
13 | +import com.zteits.oa.api.base.constants.ErrorType; | ||
14 | +import com.zteits.oa.api.base.exception.BizException; | ||
13 | import com.zteits.oa.api.dto.asraproject.AsraProjectDTO; | 15 | import com.zteits.oa.api.dto.asraproject.AsraProjectDTO; |
14 | import com.zteits.oa.api.dto.param.AsraProjecQueryReq; | 16 | import com.zteits.oa.api.dto.param.AsraProjecQueryReq; |
15 | import com.zteits.oa.api.service.report.query.AsraProjectService; | 17 | import com.zteits.oa.api.service.report.query.AsraProjectService; |
@@ -36,6 +38,9 @@ public class AsraProjectServiceImpl implements AsraProjectService { | @@ -36,6 +38,9 @@ public class AsraProjectServiceImpl implements AsraProjectService { | ||
36 | List<AsraProject> list = asraProjectDao.queryAsraProjectForList(asraProjecQueryReq); | 38 | List<AsraProject> list = asraProjectDao.queryAsraProjectForList(asraProjecQueryReq); |
37 | ListCopyUtil.listCopyProperties(list, listDTO, AsraProjectDTO.class); | 39 | ListCopyUtil.listCopyProperties(list, listDTO, AsraProjectDTO.class); |
38 | logger.info("---begin查询项目信息list"); | 40 | logger.info("---begin查询项目信息list"); |
41 | + if(true){ | ||
42 | + throw new BizException(ErrorType.BIZ_ERROR,"adadsad"); | ||
43 | + } | ||
39 | return new BizResult<List<AsraProjectDTO>>(listDTO); | 44 | return new BizResult<List<AsraProjectDTO>>(listDTO); |
40 | } | 45 | } |
41 | 46 |
src/main/java/com/zteits/oa/report/web/AsraProjectController.java
@@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RestController; | @@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RestController; | ||
13 | 13 | ||
14 | import com.alibaba.fastjson.JSONObject; | 14 | import com.alibaba.fastjson.JSONObject; |
15 | import com.zteits.oa.api.base.bean.BizResult; | 15 | import com.zteits.oa.api.base.bean.BizResult; |
16 | +import com.zteits.oa.api.base.constants.ErrorType; | ||
17 | +import com.zteits.oa.api.base.exception.BizException; | ||
16 | import com.zteits.oa.api.dto.asraproject.AsraProjectDTO; | 18 | import com.zteits.oa.api.dto.asraproject.AsraProjectDTO; |
17 | import com.zteits.oa.api.dto.param.AsraProjecQueryReq; | 19 | import com.zteits.oa.api.dto.param.AsraProjecQueryReq; |
18 | import com.zteits.oa.api.service.report.query.AsraProjectService; | 20 | import com.zteits.oa.api.service.report.query.AsraProjectService; |
src/main/java/com/zteits/oa/util/BeanValidatorsUtils.java
0 → 100644
1 | +/** | ||
2 | + * Copyright (c) 2005-2012 springside.org.cn | ||
3 | + */ | ||
4 | +package com.zteits.oa.util; | ||
5 | + | ||
6 | +import java.util.List; | ||
7 | +import java.util.Map; | ||
8 | +import java.util.Set; | ||
9 | + | ||
10 | +import javax.validation.ConstraintViolation; | ||
11 | +import javax.validation.ConstraintViolationException; | ||
12 | +import javax.validation.Validation; | ||
13 | +import javax.validation.Validator; | ||
14 | + | ||
15 | +import com.google.common.collect.Lists; | ||
16 | +import com.google.common.collect.Maps; | ||
17 | + | ||
18 | +/** | ||
19 | + * JSR303 Validator(Hibernate Validator)工具类. | ||
20 | + * | ||
21 | + * ConstraintViolation中包含propertyPath, message 和invalidValue等信息. | ||
22 | + * 提供了各种convert方法,适合不同的i18n需求: | ||
23 | + * 1. List<String>, String内容为message | ||
24 | + * 2. List<String>, String内容为propertyPath + separator + message | ||
25 | + * 3. Map<propertyPath, message> | ||
26 | + * | ||
27 | + * 详情见wiki: https://github.com/springside/springside4/wiki/HibernateValidator | ||
28 | + * @author calvin | ||
29 | + * @version 2013-01-15 | ||
30 | + */ | ||
31 | +public class BeanValidatorsUtils { | ||
32 | + | ||
33 | + private static Validator validator = Validation.buildDefaultValidatorFactory() | ||
34 | + .getValidator(); | ||
35 | + /** | ||
36 | + * 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException. | ||
37 | + */ | ||
38 | + @SuppressWarnings({ "unchecked", "rawtypes" }) | ||
39 | + public static void validateWithException(Object object) | ||
40 | + throws ConstraintViolationException { | ||
41 | + Set constraintViolations = validator.validate(object); | ||
42 | + if (!constraintViolations.isEmpty()) { | ||
43 | + throw new ConstraintViolationException(constraintViolations); | ||
44 | + } | ||
45 | + } | ||
46 | + | ||
47 | + /** | ||
48 | + * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>中为List<message>. | ||
49 | + */ | ||
50 | + public static List<String> extractMessage(ConstraintViolationException e) { | ||
51 | + return extractMessage(e.getConstraintViolations()); | ||
52 | + } | ||
53 | + | ||
54 | + /** | ||
55 | + * 辅助方法, 转换Set<ConstraintViolation>为List<message> | ||
56 | + */ | ||
57 | + @SuppressWarnings("rawtypes") | ||
58 | + public static List<String> extractMessage(Set<? extends ConstraintViolation> constraintViolations) { | ||
59 | + List<String> errorMessages = Lists.newArrayList(); | ||
60 | + for (ConstraintViolation violation : constraintViolations) { | ||
61 | + errorMessages.add(violation.getMessage()); | ||
62 | + } | ||
63 | + return errorMessages; | ||
64 | + } | ||
65 | + | ||
66 | + /** | ||
67 | + * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为Map<property, message>. | ||
68 | + */ | ||
69 | + public static Map<String, String> extractPropertyAndMessage(ConstraintViolationException e) { | ||
70 | + return extractPropertyAndMessage(e.getConstraintViolations()); | ||
71 | + } | ||
72 | + | ||
73 | + /** | ||
74 | + * 辅助方法, 转换Set<ConstraintViolation>为Map<property, message>. | ||
75 | + */ | ||
76 | + @SuppressWarnings("rawtypes") | ||
77 | + public static Map<String, String> extractPropertyAndMessage(Set<? extends ConstraintViolation> constraintViolations) { | ||
78 | + Map<String, String> errorMessages = Maps.newHashMap(); | ||
79 | + for (ConstraintViolation violation : constraintViolations) { | ||
80 | + errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage()); | ||
81 | + } | ||
82 | + return errorMessages; | ||
83 | + } | ||
84 | + | ||
85 | + /** | ||
86 | + * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath message>. | ||
87 | + */ | ||
88 | + public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e) { | ||
89 | + return extractPropertyAndMessageAsList(e.getConstraintViolations(), " "); | ||
90 | + } | ||
91 | + | ||
92 | + /** | ||
93 | + * 辅助方法, 转换Set<ConstraintViolations>为List<propertyPath message>. | ||
94 | + */ | ||
95 | + @SuppressWarnings("rawtypes") | ||
96 | + public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations) { | ||
97 | + return extractPropertyAndMessageAsList(constraintViolations, " "); | ||
98 | + } | ||
99 | + | ||
100 | + /** | ||
101 | + * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath +separator+ message>. | ||
102 | + */ | ||
103 | + public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) { | ||
104 | + return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator); | ||
105 | + } | ||
106 | + | ||
107 | + /** | ||
108 | + * 辅助方法, 转换Set<ConstraintViolation>为List<propertyPath +separator+ message>. | ||
109 | + */ | ||
110 | + @SuppressWarnings("rawtypes") | ||
111 | + public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations, | ||
112 | + String separator) { | ||
113 | + List<String> errorMessages = Lists.newArrayList(); | ||
114 | + for (ConstraintViolation violation : constraintViolations) { | ||
115 | + errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage()); | ||
116 | + } | ||
117 | + return errorMessages; | ||
118 | + } | ||
119 | +} | ||
0 | \ No newline at end of file | 120 | \ No newline at end of file |