日期:2014-05-20  浏览次数:21078 次

jap过滤器的问题
filter 过滤器代码

----------------------------------

package 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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class fhjFilter implements Filter {

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("doFilter");
Cookie[] cookies = ((HttpServletRequest) request).getCookies();
boolean isLogined = false;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("currentLoginUser")) {
isLogined = true;
break;
}
}
}

if (isLogined == true) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendRedirect("login.jsp");
}
}

public void init(FilterConfig filterConfig) throws ServletException {
}

}

servlet代码

---------------

package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaveCookie extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("currentLoginUser", "win");
response.addCookie(cookie);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}

}
login.jsp代码
----------------

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<a href="saveCooke">保存Cookie</a>
</body>
</html>


b.jsp代码---------------

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
bbbbbbbbbbbbbbb
</body>
</html>


a.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
aaaaaaaaaa
</body>
</html>

我想a和b页面必须通过login.jsp登录之后才能访问他 但是我的过滤器有问题 一运行a.jsp或者b.jsp
给我输出
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter
doFilter这么多输出语句 过滤器配置正确 就是跳转不过去login.jsp 在ie上就是显示不了login.jsp请高手运行以下代码

------解决方案--------------------
debug调试下。或者在
if (isLogined == true) {