在SpringMVC或SpringBoot中通常我们使用拦截器来拦截未登录的用户访问后台页面,如果调用接口是通过 Vue 之类的框架,我们后端通常直接返回 JSON,所以可以在拦截器里,将报错通过 response 传过前端。
代码如下
111
代码如下
- package com.example.sens.Interceptor;
- import cn.hutool.json.JSONObject;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.PrintWriter;
- /**
- * @author 言曌
- * @date 2018-05-03 11:40
- */
- @Component
- public class SecurityInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
- //这里可以根据session的用户是否登录
- if (request.getSession().getAttribute("user") == null) {
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json; charset=utf-8");
- PrintWriter out = null;
- try {
- JSONObject res = new JSONObject();
- res.put("success", false);
- res.put("message", "用户未登录!");
- out = response.getWriter();
- out.append(res.toString());
- return false;
- } catch (Exception e) {
- e.printStackTrace();
- response.sendError(500);
- return false;
- }
- }
- return true;
- }
- }
111
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏