Thursday, May 20, 2010

AuthFilter in JSF

AuthFilter is a server side validation to check whether userId is null and if it is null redirects back to login page

1) Creating AuthFilter class in security package.

/*
* Checks userId is null or not
*/
package security;

import java.io.IOException;
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;
import javax.servlet.http.HttpSession;

/**
*
* @author Subin
*/
public class AuthFilter implements Filter {

public void init(FilterConfig arg0) throws ServletException {
}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest) req;
HttpServletResponse hres = (HttpServletResponse) res;
HttpSession session = hreq.getSession();
String path = hreq.getPathTranslated();
System.out.println("Context Path: " + hreq.getContextPath() + " Servelet Path: " + hreq.getServletPath());
String domainPath = hreq.getContextPath() + hreq.getServletPath();
System.out.println("User Ip address: " + hreq.getRemoteHost());
//Redirects application to login.jsp if userId is null
if (session.getAttribute("userId") == null ) {
System.out.println("Parameter: " + hreq.getPathTranslated() + " ");
hres.sendRedirect(domainPath + "/login.jsp");
return;
}
arg2.doFilter(req, res);
}

public void destroy() {
}
}


2) Mapping Filter in web.xml

<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>security.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

No comments:

Post a Comment