当前位置: 代码迷 >> Web前端 >> 如何用filterServlet判断Session是否登录
  详细解决方案

如何用filterServlet判断Session是否登录

热度:325   发布时间:2013-10-22 16:16:51.0
怎么用filterServlet判断Session是否登录?

webapps\
???????\index.jsp
???????\common
???????.......
???????\文件夹
根目录只留有一个index.jsp登录用
不过滤掉
过滤相关的文件夹
如:
<filter-mapping>
????<filter-name>hello</filter-name>
????<url-pattern>/common/*</url-pattern>
</filter-mappint>
<filter-mapping>
????<filter-name>hello</filter-name>
????<url-pattern>/xxx/*</url-pattern>
</filter-mappint>

?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//设置servlet过滤代码段
public class SessionFilter implements Filter {
protected FilterConfig filterConfig;

// 初始化
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {

HttpServletRequest httprequest = (HttpServletRequest) request;
HttpSession session = httprequest.getSession();
HttpServletResponse httpresponse = (HttpServletResponse) response;

String UserId = (String) session.getAttribute("UserId");

if (UserId == null) {

System.out.println("filter:session is null ");
/*
 * httpresponse.sendRedirect(httprequest.getContextPath() +
 * "/Hello.do");
 */
httpresponse.setContentType("text/html; charset=UTF-8");
PrintWriter out = httpresponse.getWriter();
String strURL = "<script   language=\"javascript\">";
strURL += "window.open('" + httprequest.getContextPath()
+ "/index.jsp" + "','_parent')";
strURL += "</script>";
out.println(strURL);
return;

}
chain.doFilter(request, response);
}

public void destroy() {
this.filterConfig = null;
}
}

?

  相关解决方案