这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<display-name>MyFilter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>AB_DB.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/MyFilter</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>Profile</display-name>
<servlet-name>Profile</servlet-name>
<servlet-class>AB_DB.Profile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/Profile</url-pattern>
</servlet-mapping>
</web-app>
这是我尝试过的过滤器servlet
package AB_DB;
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.HttpServletRequest;
public class MyFilter implements Filter {
public MyFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String requri = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length() + 1);
System.out.println(requri);
//if request uri starts with user/ then system will forward the request to Profile servlet
if (requri.startsWith("user/")) {
//get userid from request uri
String id = requri.substring(5);
System.out.println(id);
//set attribute "user" with userid value
request.setAttribute("user", id);
//forward the request to Profile servlet
request.getRequestDispatcher("/Profile")
.forward(request, response);
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
然而,在GlassFish 4服务器日志中,运行项目时根本没有错误。这个URI甚至没有被‘System.out.println(id);’打印出来,所以我假设这个过滤器甚至没有被注入。
谁能看到任何问题与我的代码?未运行servlet概要文件
您已经将您的过滤器映射到/MyFilter
<url-pattern>/MyFilter</url-pattern>
和你请求的URL不匹配
/user/Surname1993
所以你的过滤器不会被调用