1 在web.xml中配置filter(要放在字符集过滤器之后,否则字符过滤会失效)
<!-- 登录拦截 --> <filter> <display-name>LoginFilter</display-name> <filter-name>LoginFilter</filter-name> <filter-class>com.xxx.common.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.拦截器类(登录,注册,静态文件.js.CSS等不进行过滤,放过去)
package com.xxx.common;import java.io.IOException;import java.io.Writer;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.sPRingframework.beans.factory.annotation.Autowired;import org.springframework.context.applicationContext;import org.springframework.stereotype.Component;import org.springframework.web.context.support.WebApplicationContextUtils;import com.xxx.entity.User;import com.xxx.service.LoginService;import com.xxx.util.CommonUtil;public class LoginFilter implements Filter { private LoginService loginService; public LoginService getLoginService() { return loginService; } public void setLoginService(LoginService loginService) { this.loginService = loginService; } public LoginFilter() { } /** * 初始化 */ public void init(FilterConfig config) throws ServletException { ServletContext context = config.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(context); loginService = (LoginService) ctx.getBean(LoginService.class); } public void destroy() { loginService = null; } /** * 登录拦截 */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; String path = CommonUtil.getRequestURL(httpRequest); if (path.indexOf("/tologin") != -1 || path.indexOf("/login") != -1 || path.indexOf("/include") != -1) { chain.doFilter(req, res); } else { User user = loginService.getCurrentUser(); if (user == null) { boolean isAjaxRequest = isAjaxRequest(httpRequest); if (isAjaxRequest) { httpResponse.setCharacterEncoding("UTF-8"); Writer out = httpResponse.getWriter(); JSONObject jsonObj = new JSONObject(); jsonObj.put("success", false); jsonObj.put("code", "noLogin"); jsonObj.put("message", "请您先登录系统!"); out.write(jsonObj.toString()); out.flush(); out.close(); } else { httpResponse.sendRedirect("/项目路径/Login/tologin"); } } else { chain.doFilter(req, res); } } } /** * 判断是否为Ajax请求 * * @param request * HttpServletRequest * @return 是true, 否false */ public static boolean isAjaxRequest(HttpServletRequest request) { String requestType = request.getHeader("X-Requested-With"); return requestType != null && "xmlhttpRequest".equals(requestType); }}
新闻热点
疑难解答