JavaWeb攔截器配置
阿新 • • 發佈:2022-03-20
頁面請求攔截
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { System.out.println("許可權攔截啟動"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request1 = (HttpServletRequest) request; HttpServletResponse response1 = (HttpServletResponse) response; if (request1.getSession().getAttribute(Constants.USER_SESSION)==null) { request1.setAttribute("error","請先登入!"); request1.getRequestDispatcher("/login.jsp").forward(request1,response1); }else { chain.doFilter(request,response); } } public void destroy() { System.out.println("攔截器銷燬"); } }
請求及響應編碼配置
import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { System.out.println("過濾器初始化"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); chain.doFilter(request,response); } public void destroy() { } }