Home >Java >javaTutorial >A brief introduction to Servlet filter Filter (with examples)

A brief introduction to Servlet filter Filter (with examples)

不言
不言forward
2018-11-24 16:54:343539browse

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

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() {
		 
	} 

}

web.xml parameters

	<!-- 配置过滤器 -->
	<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>

Application

1) Specify encoding format

request.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);

2) Whether the user is logged in and whether the user can access the menu

String userId=(String) session.getAttribute("userId");
if (userId ==null){
}

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete