5.1 问题描述
对于类似于书城这种网站,并不是所有的页面都可以直接访问的,比如购物车页面,订单页面等等都需要登陆过后才能访问。
5.2 解决方案
加入过滤器,代码如下:
package book.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@WebFilter(urlPatterns = {"*.do", "*.html"},
initParams = {
@WebInitParam(name="bai", value = "/book/page.do?operate=page&page=user/login,/book/user.do?null")
})
public class SessionFilter implements Filter {
List<String> baiList = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String bai = filterConfig.getInitParameter("bai");
String[] baiStrings = bai.split(",");
baiList = Arrays.asList(baiStrings);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestURI = request.getRequestURI();
String queryString = request.getQueryString();
String requestURL = requestURI + "?" + queryString;
System.out.println(requestURI);
System.out.println(queryString);
if(baiList.contains(requestURL)){
filterChain.doFilter(request, response);
} else {
HttpSession session = request.getSession();
Object currUser = session.getAttribute("currUser");
if(currUser != null){
filterChain.doFilter(request, response);
} else {
response.sendRedirect("page.do?operate=page&page=user/login");
}
}
}
@Override
public void destroy() {
Filter.super.destroy();
}
}