SSH框架一般在登录时,都有过滤器Filter,防止在未登录的情况下访问不该访问的页面
1、首先写一下Filter的类来实现Filter接口
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.lovecar.entity.Admin;
public class LoginFilter extends HttpServlet implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;
HttpSession session = servletRequest.getSession();
//获得用户请求的URI
String path = servletRequest.getRequestURI();
Admin admin = (Admin) session.getAttribute("admin");
//无需过滤的页面
if(path.indexOf("adminlogin.jsp") > -1){
chain.doFilter(servletRequest, servletResponse);
return ;
}
if(admin == null || "".equals(admin)){
//跳转到登陆页面,这里使用了绝对路径
servletResponse.sendRedirect(servletRequest.getContextPath()+"/adminlogin.jsp");
}else{
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2、web.xml里配置需要登录权限验证
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.lovecar.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>