Servlet Filter


1) Filter is dependent on Servlet container, which is a part of Servlet specification. Three interface classes are defined in Servlet API: Filter, filterchain and filterconfig.

2) the basic function is to intercept the process of calling Servlet, so as to realize some special functions before and after the response processing of Servlet.

3) it is necessary to register and set the resources it can intercept in the web.xml file.



public class UserNoFilter implements Filter { 
	private FilterConfig filterConfig; //Get parameter configuration

	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig = fConfig;
	 * Business logic judgment
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		String initUser = filterConfig.getInitParameter("userNo");
		String userNo = request.getParameter("userNo");//Get user account from submit request
			request.setAttribute("message", "Incorrect user name");
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		chain.doFilter(request, response);
	public void destroy() {


web.xml parameters

	<!-- Configure filters -->



1) specify encoding format

filterChain.doFilter(request, response);

2) whether the user can log in and access the menu


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

Keywords: Java xml JSP encoding Session

Added by chrispols on Sun, 08 Dec 2019 21:27:23 +0200