<% Object user = session.getAttribute("user"); // 如果等于null,说明还没有登录 if (user == null) { request.getRequestDispatcher("/login.jsp").forward(request,response); return; } %>
public class AdminFilter implements Filter { /** * doFilter 方法,专门用于拦截请求。可以做权限检查 */ @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"); // 如果等于null,说明还没有登录 if (user == null) { servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse); return; } else { // 让程序继续往下访问用户的目标资源 filterChain.doFilter(servletRequest,servletResponse); } } }
web.xml
<!--filter 标签用于配置一个Filter 过滤器--> <filter> <!--给filter 起一个别名--> <filter-name>AdminFilter</filter-name> <!--配置filter 的全类名--> <filter-class>com.atguigu.filter.AdminFilter</filter-class> </filter> <!--filter-mapping 配置Filter 过滤器的拦截路径--> <filter-mapping> <!--filter-name 表示当前的拦截路径给哪个filter 使用--> <filter-name>AdminFilter</filter-name> <!--url-pattern 配置拦截路径 / 表示请求地址为:http://ip:port/工程路径/ 映射到IDEA 的web 目录 /admin/* 表示请求地址为:http://ip:port/工程路径/admin/* --> <url-pattern>/admin/*</url-pattern> </filter-mapping>
doFilter()
@Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("2.Filter 的init(FilterConfig filterConfig)初始化"); // 1、获取Filter 的名称filter-name 的内容 System.out.println("filter-name 的值是:" + filterConfig.getFilterName()); // 2、获取在web.xml 中配置的init-param 初始化参数 System.out.println("初始化参数username 的值是:" + filterConfig.getInitParameter("username")); System.out.println("初始化参数url 的值是:" + filterConfig.getInitParameter("url")); // 3、获取ServletContext 对象 System.out.println(filterConfig.getServletContext()); }
web.xml
<!--filter 标签用于配置一个Filter 过滤器--> <filter> <!--给filter 起一个别名--> <filter-name>AdminFilter</filter-name> <!--配置filter 的全类名--> <filter-class>com.atguigu.filter.AdminFilter</filter-class> <init-param> <param-name>username</param-name> <param-value>root</param-value> </init-param> <init-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost3306/test</param-value> </init-param> </filter>
<url-pattern>/target.jsp</url-pattern>
http://ip:port/工程路径/target.jsp
<url-pattern>/admin/*</url-pattern>
http://ip:port/工程路径/admin/*
<url-pattern>*.html</url-pattern>
<url-pattern>*.do</url-pattern>
<url-pattern>*.action</url-pattern>