权限校验过滤器:
对应的servlet文件(login.jsp)中的doPost()方法中添加:
String returnUri=request.getParameter("return_uri");//return_uri是用户访问对应的页面之前会访问的页面,通过这个值可以返回对应页面。
在登录成功(在登录功能下)的判断语句下添加:
request.getSession.setAttribute("flag","_success");//如果登录成功,在当前对象中保存一个名称为flag的变量的值为_success
if(returnUri!=null){
rd=request.getRequestDispatcher(returnUri);//RequestDispatcher rd=null;
rd.forward(request,response);
}else{
rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request,response);
}
在登录失败的判断语句下添加:
request.getSession.setAttribute("flag","_error");
reuqest.setAttribute("msg","用户名或密码错误");
rd=request.getRequestDispatcher("login.jsp");
rd.forward(request,response);
-》在对应的jsp文件中添加隐藏域:
<%if(request.getAttribute("return_uri")!=null){%>
<input type="hidden" name="return-uri" value="<%=request.getAttribute("return_uri")%>" />
<%}%>
-》新建过滤器 -》 编写doFilter()方法中的业务逻辑:
HttpServletRequset req=(HttpServletRequest)request;
HttpServletResponse resp=(HttpServletResponse)response;
String sp=req.getServletPath();
HttpSession session=req.getSession();
String flag=(String)session.getAttribute("flag");
if(sp!=null&&(sp.equals.("/login.jsp")||sp.equals.("/index.jsp"))){//如果访问的是默认页面或登录界面(即一些不需经过权限授予即可以访问的页面),就直接将请求转发给下一个组件处理
chain.doFilter(request,response);
}else{
if(flag!=null&&flag,equals("_success")){
chain.doFilter(request,response);
}else if(flag!=null&&flag,equals("_error")){
req.setAttribute("msg","登录失败,请重新登录<br/>");
req.setAttribute("return_uri",sp);
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
}else{
req.setAttribute("msg","您尚未登录,请登录<br/>");
req.setAttribute("return_uri",sp);
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
}
}
-》接下来在web.xml配置一下(将编写的过滤器等配置好):
<filter>
<filter-name>PermissionFilter</filter-name>
<filter-class>hp.filter.PermissionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PermissionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>