我正在使用Java Filter来测试身份验证。如果用户输入正确的用户ID和密码组合,则过滤器会有效地将它们转发给servlet。但是,如果输入了错误信息,则会将用户发送回他们来自的登录页面。出于某种原因,当他们被发送回登录页面时," login.html"而是显示文件。以下是过滤器的代码:
package com.simpleServletDemo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
/**
*
* @author Not Important
*/
@WebFilter("/MyFilterChecker")
public class MyFilterChecker implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String userID = request.getParameter("txtUser");
String password = request.getParameter("txtPassword");
PrintWriter out = response.getWriter();
if (userID.equals("notimpotant@gmail.com") && password.equals("password12345")) {
out.print("Success!");
chain.doFilter(request, response); //Sends Request and response to next resource
} else {
out.print("Incorrect Username or Password!");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
dispatcher.include(request, response);
}
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
}
}
我哪里出错了?谢谢!
我还包含了web.xml文件来显示映射:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>MyLoginServlet</servlet-name>
<servlet-class>com.simpleServletDemo.MyLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyLoginServlet</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFilterChecker</filter-name>
<filter-class>com.simpleServletDemo.MyFilterChecker</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilterChecker</filter-name>
<url-pattern>/Login</url-pattern>
</filter-mapping>
</web-app>
答案 0 :(得分:2)
将dispatcher.include()方法更改为dispatcher.forward()方法。您还可以使用response.redirect()方法转发到login.html文件。