1、创建 CharEncodingFilter.java
package com.by.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharEncodingFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {//设置编码格式req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=utf-8");//放行,即调用servletfilterChain.doFilter(req,resp);}@Overridepublic void destroy() {}
}
2、创建 LoginFilter.java
package com.by.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) resp;//直接放行: “login.jsp”和“/”String uri = request.getRequestURI();if(uri.contains("login") || uri.endsWith("/")){System.out.println("uri:"+uri+"中包含login或以/结尾 --> 直接放行");//放行chain.doFilter(req,resp);//结束return;}//1、从session获取userObject user = request.getSession().getAttribute("user");//2、获取到user,则放行if(user != null){System.out.println("用户已登录 --> 直接放行");//放行chain.doFilter(req,resp);//结束return;}else{System.out.println("用户未登录 --> 重定向到 login.jsp");//3、没有获取到user,则重定向到login.jspresponse.sendRedirect("login.jsp");}}@Overridepublic void destroy() {}
}
2、 配置 web.xml
3、结果