package com.example.jz.auth; import cn.hutool.json.JSONUtil; import com.example.jz.modle.R; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author 安瑾然 * @data 2022/7/18 - 10:35 AM * @description 无权访问配置 */ @Component public class MyAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { R r = new R<>(); r.setCode(403); r.setMsg("无权访问"); r.setData(null); // 设置返回消息类型 httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8"); httpServletResponse.setCharacterEncoding("utf-8"); httpServletResponse.setContentType("application/json;charset=UTF-8"); // 返回给请求端 PrintWriter writer = httpServletResponse.getWriter(); writer.write(JSONUtil.toJsonStr(r)); writer.flush(); writer.close(); } }