日期:2014-05-17  浏览次数:20972 次

Filter:为什么过滤后输出的结果是这样的
public class LoginFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化中...");
}

public void destroy() {

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;

HttpSession session = httpServletRequest.getSession();

System.out.println("开始过滤....");

if (httpServletRequest.getServletPath().indexOf("login.jsp") > 0) {
System.out.println("放过该请求...");
chain.doFilter(request, response);
} else {

String user = (String) session.getAttribute("login");

if (user != null) {
System.out.println("已登录,取消过滤...");
chain.doFilter(request, response);

} else {
System.out.println("未登录,跳转到登录页面...");
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
}
}
System.out.println("完成过滤....");
}
}


public class LoginServlet extends HttpServlet {

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

public String notNull(String param) {
return param == null ? "" : param;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String username = notNull(request.getParameter("username"));
String password = notNull(request.getParameter("password"));

if (username.equals("douya0808") && password.equals("123456")) {// 直接给xxxxLoginTest/servlet/LoginServlet会由于没传值而报出NullPointer
System.out.println("信息正确,跳转页面中...");
session.setAttribute("login", "LoginSuccess!");
response.sendRedirect(request.getContextPath() + "/success.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}

}
}


	<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/LoginServlet</url-pattern>
</servlet-mapping>