配置过滤器,通过mapping的url-pattern将访问页面截住,通过import javax.servlet.Filter来进行一些校验处理,
,实现innt(),doFilter(),destory()然后转向页面
代码:
public class AccessFilter extends HttpServlet implements Filter {
private FilterConfig filterConfig; //Handle the passed-in FilterConfig
private String loginPage;
private String[] pageBeforeLogin;
private final String[] DEFAULT_LOGIN_PAGE={"/login.jsp"};
/**
* 获取InitParameter
* 登录页、不用登录就可以访问的页
* @param filterConfig FilterConfig
* @throws ServletException
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
try
{
loginPage=filterConfig.getInitParameter("loginPage");
}
catch(java.lang.Exception e)
{
loginPage=DEFAULT_LOGIN_PAGE[0];
}
try
{
pageBeforeLogin=(loginPage + "," + filterConfig.getInitParameter("pageBeforeLogin")).split(",");
}
catch(Exception e)
{
}
}
//Process the request/response pair
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;
//先判断是否已经登录
HttpSession session= req.getSession();
if(session!=null&&session.getAttribute(SystemGlobals.LOGINUSERID)!=null){
doNext(request, response, filterChain);
return;
}
//clientRequest 记录真正的被请求的 URL 比如 /index.jsp;/login.jsp;/
String clientRequest = req.getServletPath();
System.out.println(clientRequest);
for (int i=0;i<pageBeforeLogin.length;i++)
{
if (pageBeforeLogin[i].equalsIgnoreCase(clientRequest))
{
doNext(request,response,filterChain);
return;
}
}
//运行到此处说明必须转到登录界面
try
{
//RequestDispatcher rd = this.filterConfig.getServletContext().getRequestDispatcher(loginPage); // req.getRequestDispatcher(loginPage);
//rd.forward(request, res);
res.sendRedirect(req.getContextPath()+ loginPage);
return;
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void doNext(ServletRequest request, ServletResponse response, FilterChain filterChain)
{
try {
filterChain.doFilter(request, response);
}
catch(ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
}
catch(IOException iox) {
filterConfig.getServletContext().log(iox.getMessage());
}
}
//Clean up resources
public void destroy() {
}
}
web.xml配置:
<filter>
<filter-name>sessionloginchecker</filter-name>
<filter-class>com.itsv.chy.system.permission.AccessFilter</filter-class>
<init-param>
<param-name>loginPage</param-name>
<param-value>/system/login.jsp</param-value>
</init-param>
<init-param>
<param-name>pageBeforeLogin</param-name>
<param-value>/login.do,/logout.do</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>sessionloginchecker</filter-name>
<url-pattern>index.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>sessionloginchecker</filter-name>
<url-pattern>/accessAction.do</url-pattern>
</filter-mapping>