web中 filter基于不同请求(ajax,url)过滤返回不同结果

时间:2022-02-03 18:29:22

public class LoginFilter implements Filter{

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException
{

HttpServletRequest httpRequest = (HttpServletRequest) request;

HttpServletResponse httpResponse = (HttpServletResponse) response;

String requestType = httpRequest.getHeader("X-Requested-With");
PrintWriter out = null;
try
{
if (requestType != null && requestType.equals("XMLHttpRequest"))
{
out = response.getWriter();
JSONObject json = new JSONObject();
json.put("rspCode", "logintimeout");
json.put("rspDesc", "登陆超时");
out.write(json.toString());
out.flush();
}
else
{
httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
}
}
catch (Exception e)
{


}
finally
{
if (out != null)
{
out.close();
}
}


}

}