【JavaEE】进阶 · 个人博客系统(2)
文章目录
- 【JavaEE】进阶 · 个人博客系统(2)
- 1. 统一返回格式处理
- 1.1 统一返回类common.CommonResult
- 1.2 统一返回处理器component.ResponseAdvice
- 2. 统一异常处理
- 3. 拦截器实现
- 3.1 全局变量SESSION_KEY
- 3.2 session工具类SessionUtils
- 3.3 拦截器 UserInterceptor
- 3.4 配置类 AppConfig
【JavaEE】进阶 · 个人博客系统(2)
【JavaEE】Spring全家桶实现AOP-统一处理_s:103的博客-CSDN博客
为了让代码更加低耦合,高内聚,符合单一设计原则,所以进行一些统一处理!
1. 统一返回格式处理
1.1 统一返回类common.CommonResult
@Data
public class CommonResult {private int code; //状态码private String msg; //状态码描述信息private Object data; //返回数据public static CommonResult success(Object data) {CommonResult result = new CommonResult();result.setCode(200);result.setMsg("成功");result.setData(data);return result;}public static CommonResult success(Object data, String msg) {CommonResult result = new CommonResult();result.setCode(200);result.setMsg(msg);result.setData(data);return result;}public static CommonResult fail(int code, String msg) {CommonResult result = new CommonResult();result.setCode(code);result.setMsg(msg);return result;}public static CommonResult fail(int code, String msg, Object data) {CommonResult result = new CommonResult();result.setCode(code);result.setMsg(msg);result.setData(data);return result;}}
1.2 统一返回处理器component.ResponseAdvice
@ControllerAdvice
@ResponseBody
public class ResponseAdvice implements ResponseBodyAdvice {@Overridepublic boolean supports(MethodParameter returnType, Class converterType) {return true;//我要重写~}@Autowiredprivate ObjectMapper objectMapper;//Spring中自带了个 Bean是 ObjectMapper,所以可以注入@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType,MediaType selectedContentType, Class selectedConverterType,ServerHttpRequest request, ServerHttpResponse response) {if(body instanceof Result) {//body 有 Result对象向上转型而来(已经包装好了的)~return body;}if(body instanceof String) {try {return objectMapper.writeValueAsString(Result.success(body));} catch (JsonProcessingException e) {e.printStackTrace();}}return Result.success(body);}
}
当然,统一返回处理,一般针对的是(百密一疏的缺漏情况),controller里的接口mapping中,没有使用CommonResult类的包装方法的mapping,即默认的一个返回处理,而 平常我们写的时候,都是自己调用CommonResult类的包装方法 ~
- String类型进行统一返回,响应的类型还是text/html,所以前端得手动将json字符串转化为json对象,
jQuery.parseJSON()
- 如果手动调用了CommonResult类的包装方法,则没有这个问题,因为接口方法的返回值是非String类型,默认是json
2. 统一异常处理
@RestControllerAdvice
public class ExceptionAdvice {@ExceptionHandler(Exception.class)public Object exceptionAdvice(Exception e) {return CommonResult.fail(-1, e.getMessage());}
}
3. 拦截器实现
3.1 全局变量SESSION_KEY
3.2 session工具类SessionUtils
通过这个工具类,我们可以调用一个方法去获取当前登录用户:
public class SessionUtils {/*** 得到当前登录用户* @param request* @return*/public static UserInfo getUser(HttpServletRequest request) {HttpSession session = request.getSession(false);return session == null ? null : (UserInfo) session.getAttribute(ApplicationVariable.SESSION_KEY);}
}
3.3 拦截器 UserInterceptor
@Component
public class UserInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("执行了拦截器!");//业务逻辑if (SessionUtils.getUser(request) != null) {return true;//用户登录}response.sendRedirect("blog_login.html");return false;}
}
3.4 配置类 AppConfig
@Configuration//不是Configurable!
public class AppConfig implements WebMvcConfigurer {@Autowiredprivate UserInterceptor userInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(userInterceptor).addPathPatterns("/**").excludePathPatterns("/blog_login.html").excludePathPatterns("blog_detail.html").excludePathPatterns("blog_register.html").excludePathPatterns("blog_lists.html").excludePathPatterns("/css/**").excludePathPatterns("/editor.md").excludePathPatterns("/img/**").excludePathPatterns("/js/**").excludePathPatterns("/sql/**");}
}
随着功能的实现,根据业务逻辑,判断其是否要进行排除!目前仅仅将一些静态资源排除~
文章到此结束!谢谢观看
可以叫我 小马,我可能写的不好或者有错误,但是一起加油鸭🦆!代码:myblog_system · 游离态/马拉圈2023年9月 - 码云 - 开源中国 (gitee.com)