How to check the requested page has a valid user with filter class IN JAVA, JSF?
// login validation method && set attribute
// UserBean.java
public String reuestedUrl() {
boolean check = loginBo.validateLogin(getUsername(), getPassword(), testlabConstants.USER_TYPE_ADMIN);
if (check) {
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpSession session = (HttpSession) ectx.getSession(false);
session.setAttribute("VALID_USER", "YES");
return "reuestedUrl?faces-redirect=true";
} else {
String msg = "Invalid Username/Password.";
setLoginfailuremsg(msg);
return "index?faces-redirect=true";
}
}
// filter class for every page & this will work for every page by include filter in web.xml file
RestrictPageFilter.java
package xyz.utils;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RestrictPageFilter implements Filter{
FilterConfig fc;
@Override
public void init(FilterConfig filterConfig) throws ServletException{
fc=filterConfig;
}
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse resp=(HttpServletResponse) response;
HttpSession session=req.getSession();
String pageRequested=req.getRequestURL().toString();
// System.out.println("pageRequested::"+pageRequested);
// System.out.println("Valid user::"+session.getAttribute("VALID_USER"));
if(session.getAttribute("VALID_USER")==null){
RequestDispatcher rd=req.getRequestDispatcher("/faces/index.xhtml?faces-redirect=true");
rd.forward(request, response);
//resp.sendRedirect("/faces/index.xhtml?faces-redirect=true");
}else{
chain.doFilter(request, response);
}
}
@Override
public void destroy(){
}
}
// web.xml file
<filter>
<filter-name>restrict</filter-name>
<filter-class>testlab.utils.RestrictPageFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>restrict</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
No comments:
Post a Comment