package com.yibo.epoch.config;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Author: ljj
* @Description:
* @Date: 2017-06-20 17:35
*/
@Slf4j
@Configuration
public class MyWebFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(MyWebFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//设置允许跨域访问
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
//response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization,"
+ " Content-Type, Accept, Connection, User-Agent, Cookie,token");
//OPTIONS请求直接放行
if("OPTIONS".equals(request.getMethod())) {
logger.info("放行OPTIONS请求");
chain.doFilter(request, response);
return;
}
//权限校验
if(!checkAuthority()) {
writeFailure(response);
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
/**权限校验*/
private boolean checkAuthority() {
//TODO 这里进行权限检查
return true;
}
/**校验失败返回*/
private void writeFailure(HttpServletResponse response) {
// 让浏览器用utf8来解析返回的数据
response.setHeader("Content-type", "application/json;charset=UTF-8");
// 告诉servlet用UTF-8转码,而不是用默认的ISO8859
response.setCharacterEncoding("UTF-8");
JSONObject result = new JSONObject();
result.put("status", "error");
result.put("message", "你没有权限!");
PrintWriter writer;
try {
writer = response.getWriter();
writer.write(result.toJSONString());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}