如果用户没有登录,则不能访问manager目录下的任何资源,即必须登陆后,才能对图书后台数据进行管理。
一. 编写ManagerFilter进行权限检查
在filter包下编写ManagerFilter类实现Filter接口并重写Filter方法。
package server.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class ManagerFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpSession session = httpServletRequest.getSession();
Object user = session.getAttribute("user");
if(user == null){ //如果用户没有登录,则跳到登录页面
servletRequest.getRequestDispatcher("/pages/user/login.jsp").forward(servletRequest,servletResponse);
return;
}else { //如果用户已经登录,则让其访问请求的资源
filterChain.doFilter(servletRequest,servletResponse);
}
}
}
在web.xml中配置拦截路径
<filter-mapping>
<filter-name>ManagerFilter</filter-name>
<url-pattern>/pages/manager/*</url-pattern> <!-- 配置拦截路径,该路径下的资源不可以访问-->
<url-pattern>/manager/bookServlet</url-pattern> <!-- 还需拦截BookServlet类,防止直接通过访问该类下的方法来访问请求的资源-->
</filter-mapping>