1、需要shiro的core核心依赖
<!-- shiro-spring权限管理 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.0</version>
</dependency>
<!-- shiro 缓存 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>
<!-- shiro控制按钮显示 -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<!-- 如果需要捕捉到ajax权限异常,core很关键 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
2、捕捉异常帮助类,实现方法只要控制层继承这个类就行了(我的所有返回值都是一个格式,所以status 状态 msg 错误消息 我就能直接提醒用户)
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* 拦截没有权限的ajax请求帮助类
* @author fanyuke
* @date 2019年8月11日10:39:22
*/
public class BaseController {
/**
* 权限异常 拦截ajax
* @param request
* @param response
* @return
*/
@ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class})
public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
if (Commons.isAjaxRequest(request)) {
// 输出JSON
Map<String, String> map = new HashMap<>();
map.put("status", "0");
map.put("msg", "您没有权限.");
writeJson(map, response);
return null;
} else {
try {
// 如果不是ajax的请求 那就跳转到没有权限的页面
response.sendRedirect("/error/403");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/**
* 输出json
* @param map
* @param response
*/
private void writeJson(Map<String, String> map, HttpServletResponse response) {
PrintWriter out = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
out = response.getWriter();
out.write(Commons.mapReturnJsonObject(map).toJSONString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
3、Commons.isAjaxRequest Commons是我自己的工具包 补上上面的方法
/**
* 判断是否为AJAX请求
* @param request
* @return 返回true为ajax请求,fasle为非ajax请求
* @date 2018年9月25日 上午10:04:31
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
boolean isAsynReq = false;
String xRequestedWith = request.getHeader("X-Requested-With");
// 判断是否为ajax请求
isAsynReq = StringUtils.isNotEmpty(xRequestedWith)
&& StringUtils.indexOf(xRequestedWith, "XMLHttpRequest") > -1;
// json 请求头的也是ajax请求
if (!isAsynReq) {
isAsynReq = StringUtils.indexOf(request.getHeader("accept"), "application/json") > -1;
}
return isAsynReq;
}