@ControllerAdvice -- 处理异常示例
Class : SessionInterceptor
package com.estate.web.filter; import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.ucenter.api.exception.SessionException;
import com.ucenter.api.exception.SignatureException;
import com.ucenter.api.exception.TimeOutException;
import com.ucenter.api.session.bean.Result;
import com.ucenter.api.session.service.IWebSessionService; public class SessionInterceptor extends HandlerInterceptorAdapter {
@Resource
private IWebSessionService webSessionService; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从request中获取sessionid
String sessionid = request.getParameter("sessionid");
if (StringUtils.isBlank(sessionid)) {
// 从cookies中获取sessionid
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("sessionid".equals(cookie.getName())) {
sessionid = cookie.getValue();
}
}
}
}
if (StringUtils.isBlank(sessionid))
throw new SessionException();
// 获取时间戳
long timestamp = NumberUtils.toLong(request.getParameter("timestamp"), 0);
if (timestamp <= 0)
throw new TimeOutException();
// 获取签名
String signature = request.getParameter("signature");
if (StringUtils.isBlank(signature))
throw new SignatureException();
// dubbo校验
Result result = webSessionService.checkSessionid(sessionid, signature, timestamp); // 校验成功,将sessionid放入request对象中
request.setAttribute("sessionid", sessionid);
request.setAttribute("ecid", result.getEcid());
request.setAttribute("uid", result.getUid());
return true; } @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
}
Class : GlobalExceptionHandler
package com.xindatai.ibs.web.exception; import java.io.IOException; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ucenter.api.exception.SessionException;
import com.ucenter.api.exception.SignatureException;
import com.ucenter.api.exception.TimeOutException;
import com.xindatai.common.web.resp.BaseRespWriter; @ControllerAdvice
public class GlobalExceptionHandler {
public static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "IOException occured")
@ExceptionHandler(IOException.class)
@ResponseBody
public void handleIOException() {
// returning 404 error code
} @ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler(TimeOutException.class)
public void timeOutException(HttpServletRequest request, HttpServletResponse response, TimeOutException ex) throws IOException {
outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
// return JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect);
} @ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler(SessionException.class)
public void sessionException(HttpServletRequest request, HttpServletResponse response, SessionException ex) throws IOException {
outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
// return JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect);
} // @ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler(SignatureException.class)
public void tokenException(HttpServletRequest request, HttpServletResponse response, SignatureException ex) throws IOException {
outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
} @ExceptionHandler
@ResponseBody
public void handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
LOGGER.error("API Exception! ", e);
BaseRespWriter writer = new BaseRespWriter();
writer.setErrMsg("API Exception!");
outputMessage(response, JSON.toJSONString(writer));
} @ResponseStatus(HttpStatus.OK)
@ResponseBody
@ExceptionHandler(BindException.class)
public void bindException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
LOGGER.error("Param Exception! ", e);
BaseRespWriter writer = new BaseRespWriter();
writer.setErrMsg("Param Exception!");
outputMessage(response, JSON.toJSONString(writer));
} private void outputMessage(HttpServletResponse response, String errMsg) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/json");
ServletOutputStream os = response.getOutputStream();
os.write(errMsg.getBytes("utf-8"));
} }
啦啦啦
@ControllerAdvice -- 处理异常示例的更多相关文章
- @ControllerAdvice 拦截异常并统一处理(转载)
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
- @ControllerAdvice全局异常拦截
@ControllerAdvice 拦截异常并统一处理 在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder ...
- Spring Boot 系列(八)@ControllerAdvice 拦截异常并统一处理
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
- Spring Boot 系列 @ControllerAdvice 拦截异常并统一处理
ControllerAdvice用法解析 简介 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置. 注解了@Controller的类的方法可以使用@Exception ...
- @ControllerAdvice 拦截异常并统一处理
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
- 精通Spring Boot---使用@ControllerAdvice处理异常
在Spring 3.2中,新增了@ControllerAdvice.@RestControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@Mode ...
- SpringBoot - @ControllerAdvice 处理异常
在Spring 3.2中,新增了@ControllerAdvice.@RestControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@Mode ...
- 使用@ControllerAdvice处理异常
在Spring 3.2中,新增了@ControllerAdvice.@RestControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@Mode ...
- SpringBoot 之 @ControllerAdvice 拦截异常并统一处理
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
随机推荐
- PCL几种采样方法
(1)下采样 Downsampling 一般下采样是通过构造一个三维体素栅格,然后在每个体素内用体素内的所有点的重心近似显示体素中的其他点,这样体素内所有点就用一个重心点来表示,进行下采样的来达到滤 ...
- Fix missing src/main/java folder in Eclipse Maven Project – 2 build path entries are missing
新建项目没有src/main/java 和 src/main/resources 两个source文件的解决方法: Step 1 : Create a Maven Webapp project. Ri ...
- @Resource、@Autowired跟default-autowire区别联系
@Resource.@Autowired和default-autowire区别联系 今天看了一工程,里面既有default-autowire,又有@Autowired,还有@Resource.我就不明 ...
- Spring,hibernate,struts的面试笔试题(含答案)
Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Sesssion 4.创建事务Transation 5.持久 ...
- 一图让你看懂CSS盒子模型
- Android学习之SQLite基础
1.新建MySQLiteHelper类继承自SQLiteOpenHelper public class MySQLiteHelper extends SQLiteOpenHelper { privat ...
- Android下ListView上下滑动背景变黑
老问题,Google一下就能找到N多答案,为方便自己日后查阅,记录如下: 手指在ListView上下滚动时,ListViewItem背景变黑,因为在滚动的时候为了提升性能做了优化,为提高滚动的性能,A ...
- pandas 的算术运算和数据对齐
pandas 还有一个重要的功能,就是他可以对不同索引的对象进行算数运算.对象相加, 如果存在不同的索引对,则结果的索引就是该索引对的并集. 先来个例子 Series In [33]: s1 = Se ...
- Oralce数据库的优化(面试必问题)
(1) 选择最有效率的表名顺序(只在基于规则的优化器中有效):ORACLE 的解析器按照从右到左的顺序处理FROM子句中的表名,FROM子句中写在最后的表(基础表 driving table)将被最先 ...
- (原创)Linux下一定要4字节地址对齐操作
Linux下一定要4字节地址对齐操作:“血”的教训,一定不要忘记!!! 当然不仅仅是Linux下,所有的32位机都应该如此!!!