This article brings you a brief introduction to Servlet filter Filter (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Features
1) Filter depends on the Servlet container and is part of the Servlet specification. Three interface classes are defined in the Servlet API: Filter, FilterChain, FilterConfig.
2) The basic function is to intercept the process of calling Servlet, so as to implement some special functions before and after the Servlet performs response processing.
3) You need to register and set the resources it can intercept in the web.xml file.
Encoding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class UserNoFilter implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig = fConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String initUser = filterConfig.getInitParameter( "userNo" );
String userNo = request.getParameter( "userNo" );
if (!initUser.equals(userNo)){
request.setAttribute( "message" , "用户名不正确" );
request.getRequestDispatcher( "/index.jsp" ).forward(request, response);
return ;
}
chain.doFilter(request, response);
}
public void destroy() {
}
}
|
Copy after login
web.xml parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!-- 配置过滤器 -->
<filter>
<display-name>UserNoFilter</display-name>
<filter-name>UserNoFilter</filter-name>
<filter- class >com.demo.filter.UserNoFilter</filter- class >
<init-param>
<param-name>userNo</param-name>
<param-value>admin</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UserNoFilter</filter-name>
<url-pattern>/hello.jsp</url-pattern>
</filter-mapping>
|
Copy after login
Application
1) Specify encoding format
1 2 | request.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
|
Copy after login
2) Whether the user is logged in and whether the user can access the menu
1 2 3 | String userId=(String) session.getAttribute( "userId" );
if (userId ==null){
}
|
Copy after login
The above is the detailed content of A brief introduction to Servlet filter Filter (with examples). For more information, please follow other related articles on the PHP Chinese website!