这是我的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服务器日志中,运行项目时完全没有错误。甚至不使用“ System.out.println(id);”将URI打印出来所以我假设过滤器甚至没有被注入。
谁能看到我的代码有任何问题? sevlet配置文件未运行
最佳答案
您已将oyur过滤器映射到/MyFilter
<url-pattern>/MyFilter</url-pattern>
且与您要求的网址不符
/user/Surname1993
这样您的过滤器就不会被调用