package com.demo.filter;
import com.data.SessionUser;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author jhirror
* @version basic 1.0 2017-01-24
* @create 2018-01-24 17:03
* @desc 权限filter demo
**/
//也可以在web.xml中配置
@WebFilter("*")
public class AuthenticationFilter implements Filter {
/**
* Default constructor.
*/
public AuthenticationFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
boolean pass = false;
if(request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
httpRequest.setCharacterEncoding("UTF-8");
String contextPath = httpRequest.getContextPath();
String url = httpRequest.getRequestURI();
String action = httpRequest.getParameter("action");
SessionUser user = SessionUser.getFromSession(httpRequest.getSession());
if(user == null) {
if(url.equals(contextPath + "/index.html") ||
url.startsWith(contextPath + "/index.jsp") ||
url.startsWith(contextPath + "/com/public/") ||
url.startsWith(contextPath + "/admin/public/") ||
url.startsWith(contextPath + "/administrator/public/") ) {
pass = true;
}
else if(url.equals(contextPath + "/data")) {
if(action != null && action.startsWith("pub.")) {
pass = true;
}
}
}
else {
pass = true;
}
// pass the request along the filter chain
if(pass) {
if(url.endsWith(".html") || url.endsWith(".js") || url.endsWith(".css")) {
response.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, response);
}
else {
HttpServletResponse httpResponse = (HttpServletResponse) response;
if(url.equals(contextPath + "/data")) {
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
//httpResponse.sendRedirect(contextPath + "/index.jsp");
}
else {
httpResponse.sendRedirect(contextPath + "/index.jsp");
}
}
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}