给JSP页面加过滤器

很简单的一个功能,如果用户没有登录之前访问其他页面时转到登录页面.用过滤器来实现.
一、在web-xml 中添加:
<filter><!-- 是否登录用户的验证filter -->
  	<filter-name>author</filter-name>
  	<filter-class>lw.filter.AuthorFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/grsz/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/khcx/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/khpf/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/tjbb/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/tjjs/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/main.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>author</filter-name>
  	<url-pattern>/top.jsp</url-pattern>
  </filter-mapping>

实现类的代码如下:
package lw.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthorFilter  implements Filter  {
	
	private  String strRedirect = "";

	protected FilterConfig filterConfig;

	public void destroy() {
		// TODO Auto-generated method stub
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub	
		HttpServletRequest hreq = (HttpServletRequest) req;

		HttpServletResponse hres = (HttpServletResponse) res;
	
		HttpSession session = hreq.getSession(true);

		String isLogin = "";
		strRedirect  =  "http://"  +  hreq.getServerName()  +  ":"  +  hreq.getServerPort()  +hreq.getContextPath()+ "/login.jsp";  
		System.out.println("web  URL  路径:"+strRedirect);
		try {
			if (null != session.getAttribute("isLogin")) {
				isLogin = session.getAttribute("isLogin").toString();
			}
			if (isLogin.equals("true")) {
				System.out.println("验证通过");
				chain.doFilter(req, res);

			} else {
	
				hres.sendRedirect(strRedirect);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig = arg0;
	}

}


获得login路径的过程:
"http://"  +  hreq.getServerName()  +  ":"  +  hreq.getServerPort()  +hreq.getContextPath()+ "/login.jsp"; 

你可能感兴趣的:(xml,Web,jsp,servlet,UP)