Servlet filter provides a filter layer between the client and the servlet. When the client invokes the request, at that time servlet filter will perform the pre-process steps to filter the request before completing the request, also it will perform the post-processing steps before sending it to the client.
Here are some common filter usage cases.
- Logging
- Auditing
- Transaction management
- Security
1. Create a module project.
- Go to Liferay workspace project → modules → new.
- Select other → Liferay → Liferay Module Project and Click on “Next”.
- Enter the project name.
- Select “Project Template Name” as “war-hook” and click on “Next”.
- Enter a Package name and click on the “Finish”. The necessary file structure will be created as below.
2. Create a servlet filter class and implement with the Filter class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.ignek.portal.web.hook; public class ServletFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Called ServletFilter.init(" + filterConfig + ") where hello=" + filterConfig.getInitParameter("hello")); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException { String uri = (String) servletRequest.getAttribute(WebKeys.INVOKER_FILTER_URI); System.out.println("Called ServletFilter.doFilter(" + servletRequest + ", " + servletResponse + ", "+ filterChain + ") for URI " + uri); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } } |
Filter interface provides the following life cycle methods.
- init(): It is used to initialize the filter.
- doFilter(): It is used to perform filtering tasks.
- destroy(): Clean up the filter’s unneeded resources.
3. Add below mapping in Liferay-hook.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?xml version="1.0"?> <!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 7.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_7_2_0.dtd"> <hook> <portal-properties>portal.properties</portal-properties> <servlet-filter> <servlet-filter-name>ServletFilter</servlet-filter-name> <servlet-filter-impl>com.ignek.portal.web.hook.ServletFilter</servlet-filter-impl> <init-param> <param-name>hello</param-name> <param-value>world</param-value> </init-param> </servlet-filter> <servlet-filter-mapping> <servlet-filter-name>ServletFilter</servlet-filter-name> <url-pattern>/group/*</url-pattern> <url-pattern>/user/*</url-pattern> <url-pattern>/web/*</url-pattern> <url-pattern>*.jsp</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </servlet-filter-mapping> </hook> |