Home > Java > Java Tutorial > body text

A brief introduction to Servlet filter Filter (with examples)

不言
Release: 2018-11-24 16:54:34
forward
3304 people have browsed it

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

}
Copy after login

web.xml parameters

	
	
		UserNoFilter
		UserNoFilter
		com.demo.filter.UserNoFilter
		
			userNo
			admin
		
	
	
		UserNoFilter
		/hello.jsp 
	
Copy after login

Application

1) Specify encoding format

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

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!