码迷,mamicode.com
首页 > 编程语言 > 详细

javaweb登陆过滤器实现

时间:2018-09-14 18:21:09      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:getc   code   public   over   end   ext   配置   color   ini   

在web.xml中配置登陆过滤器:

<!-- 配置登陆过滤器 -->
    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>weijiabin.BBS.Utils.LoginFilter</filter-class>
        <init-param>
            <param-name>passUrl</param-name>
            <param-value>index;login;FunctionServlet</param-value>
           </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
           <url-pattern>/*</url-pattern>
    </filter-mapping>
上边代码中的param-value用来设置不进行拦截的地址关键字(以;作为分隔符),在下边过滤器代码中用passUrl表示

然后写过滤器代码:
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	String passUrl = "";
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		 HttpServletRequest httpRequest=(HttpServletRequest)arg0;
	        HttpServletResponse httpResponse=(HttpServletResponse)arg1;
	        HttpSession session=httpRequest.getSession();
	        String[] strArray = passUrl.split(";");
          //下边循环作用是依次检查访问的url中是否包含passurl中的关键字,如果包含则不进行拦截 for (String str : strArray) { if (str.equals(""))//如果在上边配置中设置的url为空,则说明都需要进行拦截,跳过此循环 continue; if (httpRequest.getRequestURL().indexOf(str) >= 0) { arg2.doFilter(httpRequest, httpResponse); return; } } if(session.getAttribute("sessionUser")!=null){ arg2.doFilter(httpRequest, httpResponse); } else{ httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.jsp"); } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub passUrl = arg0.getInitParameter("passUrl"); } }

  

javaweb登陆过滤器实现

标签:getc   code   public   over   end   ext   配置   color   ini   

原文地址:https://www.cnblogs.com/ITDreamer/p/9647981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!