1、创建 CharEncodingFilter.java
package com.by.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
//设置编码格式
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//放行,即调用servlet
filterChain.doFilter(req,resp);
}
@Override
public 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 {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public 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获取user
Object 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.jsp
response.sendRedirect("login.jsp");
}
}
@Override
public void destroy() {
}
}
2、 配置 web.xml
3、结果