Add java filters in grails application
Posted By : Deepak Agrawal | 19-Dec-2014
This blog explain how to add web.xml file in grails application to add java filters.
And An example to describe the use of filters.
Steps:
1. First we need to add web.xml file in grails application.
Use grails install-templates command to add web.xml. You can find web.xml in application/src/templates/war folder.
2. now Create filter by implementing javax.servlet.Filter
package com.dcx.secured;
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpServletResponse;
public class BrowserAuthenticationFiltor implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
PrintWriter wr=response.getWriter();
wr.write("Generate response from filter");
wr.close();
//uncomment this line if you want to to send request to next resource
//arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
3. Now add BrowserAuthenticationFilter in web.xml file:
Add these lines in web.xml file before DelegatingFilterProxy Filter. So that BrowserAuthenticationFilter will be first filter to execute.
<filter>
<filter-name>browserAuthenticationFiltor</filter-name>
<filter-class>com.dcx.secured.BrowserAuthenticationFiltor</filter-class>
</filter>
<filter-mapping>
<filter-name>browserAuthenticationFiltor</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Now you have successfully configured filters in grails application. Similarly we can add servlets or other resource to our web.xml file.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Deepak Agrawal
Deepak is an bright developer with experience in Groovy and Grails. He is well versed with AngularJS.