Shiro控制没有登录时,返回指定JSON格式数据

Shiro框架在未登录时,需要返回JSON数据,需要新增ShiroUserFilter文件。

ShiroUserFilter过滤文件

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.web.filter.authc.UserFilter;
import com.alibaba.fastjson.JSON;

public class ShiroUserFilter extends UserFilter {

@Override
protected void redirectToLogin(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
  servletResponse.setContentType("application/json; charset=utf-8");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put("code", 401);
  response.put("msg", "未登录或登录超时。请重新登录");
  String json = JSON.toJSONString(response);
  servletResponse.getWriter().write(json);
}
}

ShiroConfig文件的ShiroFilterFactoryBean方法

public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
       
        Map<String, Filter> filters=new HashMap<>();
        filters.put("authc", new ShiroUserFilter());
        shiroFilter.setFilters(filters);
       
        shiroFilter.setUnauthorizedUrl("/");

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }
正在加载评论...