Servlet Filter

Characteristic

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.

 

Code

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
		
		if(!initUser.equals(userNo)){
			request.setAttribute("message", "Incorrect user name");
			request.getRequestDispatcher("/index.jsp").forward(request, response);
			return;
		}
		
		chain.doFilter(request, response);
	} 
	
	public void destroy() {
		 
	} 

}

web.xml parameters

	<!-- Configure filters -->
	<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 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