Initial use of Java Filter filter

Recently, the client put forward a small request in the project, requesting to add a mac whitelist management mechanism. Set-top boxes in the white list are allowed to access the portal interface, and those not in the white list are blocked. It is too troublesome to add judgment on all interfaces, so consider using Java interface filter to achieve this function.

Filter

Java developers use Filter technology to intercept all web resources managed by the web server: such as Jsp, action, static image files or static html files, etc., so as to realize some special functions.

  The Servlet API provides a Filter interface. When developing a web application, if the written Java class implements this interface, the Java class is called a Filter. Through Filter technology, developers

It can realize that the user can intercept the access request and response before accessing a certain target resource.

create filter

package com.inspur.portal.core.filter;import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.inspur.portal.core.common.SystemConstant;

public class AuthorityFilter implements Filter {
private static Logger log = Logger.getLogger(AuthorityFilter.class);
/**
* 需要排除的页面 接口
*/

private String excludedPages;
private String[] excludedPageArray;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("filter初始化");
excludedPages = filterConfig.getInitParameter("excludedPages");
if (StringUtils.isNotEmpty(excludedPages)) {
excludedPageArray = excludedPages.split(",");
}
return;
}


@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { boolean isExcludedPage = false; for (String page : excludedPageArray) {// Determine whether it is outside the filtered url if (((HttpServletRequest) request).getServletPath().equals(page)) { isExcludedPage = true; break; } } Map<String, Object> map = new HashMap<String, Object>(); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8 "); // Outside of filtering url if (isExcludedPage) { chain.doFilter(request, response); // Let the target resource execute, release } else { String mac = request.getParameter("mac"); if (SystemConstant .MAC_WHITE_LIST.contains(mac)) {
















chain.doFilter(request, response); // Let the target resource execute, release
} else { PrintWriter out = response.getWriter(); map.put("flag", false); map.put("msg", "No The permission"); out.write(JSON.toJSONString(map)); out.flush(); out.close(); } } } @Override public void destroy() { log.info("filter filter destroyed" ); } }
















A brief explanation of the above code:

First create the AuthorityFilter class to implement the Filter interface, and implement its three methods, init, doFiter and destroy. The init method is the method called when the filter is initialized, the init method above

The function of the code is to obtain the url resources that are not within the interception range through the filterConfig.getInitParameter method, and then put these resources into the excludedPageArray. If you need to intercept all, then in

In the init method, you don't need to do any processing, just add a print.

In the doFilter method, the code is used to determine whether the url resource is intercepted or released. If the url resource is in the excludedPageArray, release it directly, because these resources do not need to be intercepted. because our purpose is

In order to judge whether the accessing mac is in our white list, we judge by the passed mac. If the mac is in the white list, let it go; if it is not in the white list, intercept it and return the flag as false, prompting

No permission to access.

Processing in web.xml

Add the following configuration to web.xml:

<!--Configuration filter-->
    <filter>
        <filter-name>MacWhiteFilter</filter-name>
        <filter-class>com.inspur.portal.core.filter.AuthorityFilter</filter-class>
        <init- param>    
  <param-name>excludedPages</param-name>    
  <param-value>/addOrUpdateStbinfo</param-value>    
  </init-param>  
    </filter>
   
    <!--Map filter-->
    <filter- mapping>
        <filter-name>MacWhiteFilter</filter-name>
        <!--"/*" means to intercept all requests-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

Needless to say, filter-name and filter-class are used to define the Filter name and corresponding class, init-param is used to define resources that are not within the interception range, and param-name corresponds to the above

The excludedPages variable in the AuthorityFilter class, /addOrUpdateStbinfo represents the url that is not within the interception range. param-name and param-value are set according to their own situation, as long as they are with

The variables in the AuthorityFilter class and the URL of the web application can correspond. Of course, you can also define init-param as a resource that needs to be intercepted, as long as if (isExcludedPage) in the AuthorityFilter class

Just make good judgments. It depends on your own situation. If you need to intercept all interface urls, you don't need to set init-param. After defining the filter, don't forget to define the corresponding filter-mapping.

Well, the basic functions of Filter in Java have been realized so far, and the picture below shows the effect. The mac whitelist I set is [345678], mac=2 is not in my whitelist, and I return no permission.

When I call addOrUpdateStbinfo, because the url is not within the interception range, it will be released regardless of whether the mac is in the whitelist or not.

If you have any questions or opinions, please exchange and correct them in the comment area~~~

Finally, play a wave of advertising. Search the public account "Buy and save" on WeChat, and get coupons when you shop on Taobao, and you can save money when you shop.

 

 

Guess you like

Origin blog.csdn.net/fanguoddd/article/details/78009439