login.jsp
<a href="index.jsp">进入主页</a>
web.xml
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.lyq.service.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
loginFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession();
if(session.getAttribute("user") == null){
res.sendRedirect("error.jsp");
}
}
注释:将ServletRequest request, ServletResponse response里的request和resp强制转换为HttpServletRequest类型的 req和HttpServletResponse类型的 res
然后绑定HttpSession类型的session
如果获取到的已绑定session的user不存在,重定向到error.jsp,实际上未绑定session到user上
error.jsp
<h1>对不起,您还没有登录!</h1>
java web 书籍P84