过滤器

import java.io.IOException;
import java.io.PrintWriter; 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;

publicclass LogonFilter implements Filter {

privatestaticfinal String LOGON_URI ="LOGON_URI";

privatestaticfinal String HOME_URI ="HOME_URI";

private String logon_page;

private String home_page;

publicvoid destroy() {
// TODO Auto-generated method stub
}

publicvoid doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
httpResp.setContentType("text/html");
httpResp.setCharacterEncoding("utf-8");
HttpSession session = httpReq.getSession();
PrintWriter out = httpResp.getWriter();
// 得到用户请求的URI
String request_uri = httpReq.getRequestURI();
// 得到web应用程序的上下文路径
String ctxPath = httpReq.getContextPath();
// 去除上下文路径,得到剩余部分的路径
String uri = request_uri.substring(ctxPath.length());
// 判断用户访问的是否是登录页面
if (uri.equals(logon_page) || uri.equals(home_page)) {
chain.doFilter(request, response);
return;
} else {
// 如果访问的不是登录页面,则判断用户是否已经登录
if (session.getAttribute("user") !=""&& session.getAttribute("user") !=null) {
chain.doFilter(request, response);
return;
} else {
out.println("<script language=\"javaScript\">"
+"parent.location.href='"+ctxPath+logon_page+"'"
+"</script>");
//httpReq.getRequestDispatcher(logon_page).forward(httpReq,httpResp);
return;
}
}
}

publicvoid init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
// 从部署描述符中获取登录页面和首页的URI
logon_page = config.getInitParameter(LOGON_URI);
home_page = config.getInitParameter(HOME_URI);
// System.out.println(logon_page);
if (null== logon_page ||null== home_page) {
thrownew ServletException("没有找到登录页面或主页");
}
}

}



WEB.XML

filter>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<filter-name>LogonFilter</filter-name>
<filter-class>LogonFilter</filter-class>
<init-param>
<param-name>LOGON_URI</param-name>
<param-value>/management/jsp/index.jsp</param-value>
</init-param>
<init-param>
<param-name>HOME_URI</param-name>
<param-value>/management/jsp/</param-value>
</init-param>
</filter>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值