Retain querystring on POST - jsf

I am implementing forget password function. It will send a link to the user to reset his password. It looks something like this http://localhost:9080/BelsizeWeb/faces/login_pwchange.xhtml?id=yPvRp9xwUTXAY9fQpuNnuEBqT+twZ0rBraVKdcsJRi4=
While the user is still on this page, when the user click button to change and login, and if there is password mismatch, it will prompt with a faces message and the link on address bar should still contains id=yPvRp9xwUTXAY9fQpuNnuEBqT+twZ0rBraVKdcsJRi4=. But currently the link on address bar does not include the querystring.
I am using MyFaces 2.0, xhtml. Well, it hit null pointer exception because the querystring is null. I am using RequestScoped for Login_pwchange.java.
login_pwchange.xhtml
<f:metadata>
<f:event listener="#{pc_Login_pwchange.onPageLoadBegin}" type="preRenderView"></f:event>
<f:viewParam name="id" value="#{pc_Login_pwchange.w_login.token}" />
</f:metadata>
<h:body>
<h:form id="form1" enctype="multipart/form-data" prependId="false">
<p:commandButton ajax="false" type="submit" value="Change and Login"
id="login_pwchange_change" styleClass="commandButton"
action="#{pc_Login_pwchange.doLogin_pwchange_changeAction}"
style="width:150px" disabled="#{pc_Login_pwchange.w_login.disabled}">
<f:param name="id" value="#{pc_Login_pwchange.w_login.token}" />
</p:commandButton>
</h:form>
</h:body>
faces-config.xml
<navigation-rule>
<from-view-id>/login_pwchange.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>xxxxxx</from-outcome>
<to-view-id>/login_pwchange.xhtml?faces-redirect=true&includeViewParams=true</to-view-id>
</navigation-case>
</navigation-rule>
RedirectLogin.java
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
boolean authorized = false;
boolean is_sysadmin = false;
String user_sys_id = null;
HttpSession session = null;
if (request instanceof HttpServletRequest) {
session = ((HttpServletRequest) request).getSession(false);
if (session != null) {
user_sys_id = (String) session.getAttribute("user_sys_id");
if (user_sys_id != null) {
authorized = true;
String _id = user_sys_id.substring(0, 8);
if (_id.equals("SYSADMIN")) {
is_sysadmin = true;
}
}
}
}
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
String _uri = ((HttpServletRequest) request).getRequestURI();
String _querystring = ((HttpServletRequest) request).getQueryString(); //can get for first time. when there is page submit, this becomes null
//Forget Password
//========================
if (!authorized && _uri.contains("login_pwchange.xhtml")) {
HashMap _m = isResetPasswordURL(_querystring);
request.setAttribute("userid", _m.get("USERID"));
request.setAttribute("request_datetime", _m.get("REQUEST_DATETIME"));
request.setAttribute("token", _m.get("TOKEN"));
//OK - continue
chain.doFilter(request, response);
return;
}
if (_uri.contains("login.xhtml")) {
//OK - continue
chain.doFilter(request, response);
return;
}
chain.doFilter(request, response);
return;
}
Login_pwchange.java
public String doLogin_pwchange_changeAction() {
W_login _w_l = getW_login();
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
request.setAttribute("token", _w_l.getToken());
Useraccount _ua = new Useraccount();
_ua = _ua.getUserAccount_ByUserid_NotClosed(_w_l.getUserid());
String _user_sys_id = _ua.getUsersysid();
_w_l.setUsersysid(_user_sys_id);
String _password = _w_l.getPassword();
if(isEmptyNull(_password)) {
_password = "";
}
String _password_retype = _w_l.getPassword_retype();
if(isEmptyNull(_password_retype)) {
_password_retype = "";
}
_ua = _w_l.getUserAccount_BackEnd_ByUsersysid(_user_sys_id);
Integer _min_length = _ua.getPwminlength();
Integer _max_length = _ua.getPwmaxlength();
Integer _password_length = new Integer(_password.length());
Integer _password_history = _ua.getPwhistory();
Integer _max_age = _ua.getPwmaxage();
String _userid = _ua.getUserid();
String _msg_key=null;
_w_l.setPassword(null);
_w_l.setPassword_retype(null);
// Password mismatch
if (!_password.equals(_password_retype)) {
showCommonMessage_ByKey("login_pwchange_message_password_mismatch");
return "xxxxxx";
}
Integer _status = _w_l.changePassword(_user_sys_id,_password);
if (_status!=null) {
return "success";
} else {
return "failure";
}
}

Related

rendered attribute not working with request parameter

I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}

How to implement a "task monitor" with JSF

I need to execute some tasks in the server and show status with JSF (primefaces).
Below I'm describing my last try:
default.xhtml
<p:commandButton
value="execute"
action="#{controller.init()}" /> <!-- initialize and validate data and call task1() -->
<p:fieldset id="messages" legend="Status:">
<ul>
<li>
<h:panelGrid columns="2" id="msg1" styleClass="#{controller.status1}">
<p:outputLabel value="#{controller.msg1}" />
<span class="#{controller.classToIconClass(controller.status1)}"></span>
</h:panelGrid>
</li>
<li>
<h:panelGrid columns="2" id="msg2" styleClass="#{controller.status2}">
<p:outputLabel value="#{controller.msg2}" />
<span class="#{controller.classToIconClass(controller.status2)}"></span>
</h:panelGrid>
</li>
...
<p:remoteCommand name="task1" action="#{controller.task1()}" update="messages" />
<p:remoteCommand name="task2" action="#{controller.task2()}" update="messages" />
Each step is like this: (Controller.java)
#SessionScoped
...
public void task1() {
if(stopExecution) return;
long returnCode = -1;
String errorMessage = "An error occurred in the task1 execution.";
try {
returnCode = execute(comandString);
} catch (Exception e) {
Logger.getLogger(getClass()).error(errorMessage, e);
returnCode = -1;
stopExecution = true;
}
if(returnCode != 0 && returnCode != 4) {
msg1 = errorMessage;
status1 = "error";
stopExecution = true;
return;
} else {
msg1 = "Task1 is finished.";
status1 = "successful";
}
msg2 = "Running task2...";
status2 = "running";
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("task2();"); // Calls next step
}
// Everything is like task1() and always call next task at the end:
public void task2() {...}
public void task3() {...}
public void task4() {...}
public void finish() {...}
This way everything runs fine, but the users sometimes refresh the page and the execution chain brokes.
Is there a way to do what a I want to do and surviving a page refresh?
PS:
I also tried to execute task by task with RequestContext.getCurrentInstance().update("form:messages"); between them, but the page only updates at the end of the last task.
EDIT:
As Michele and Xtreme Biker said, I do it in a separate thread:
Controller.java
#SessionScoped
...
RequestContext requestContext;
Callable<Long> task1 = new Callable<Long>() {
#Override
public Long call() throws Exception {
long returnCode = -1;
String errorMessage = "An error occurred in the task1 execution.";
returnCode = execute(comandString);
if(returnCode != 0 && returnCode != 4) {
msg1 = errorMessage;
status1 = "error";
return returnCode;
} else {
msg1 = "Task1 is finished.";
status1 = "successful";
msg2 = "Running task2...";
status2 = "running";
}
requestContext.update("form:messages");
return returnCode;
}
};
public void init() {
requestContext = RequestContext.getCurrentInstance();
List<Future<Long>> tasks = new ArrayList<Future<Long>>();
ExecutorService executor = Executors.newSingleThreadExecutor();
tasks.add(executor.submit(this.task1));
tasks.add(executor.submit(this.task2));
tasks.add(executor.submit(this.task3));
tasks.add(executor.submit(this.task4));
tasks.add(executor.submit(this.finish));
executor.shutdown();
}
All tasks run even if I do a page refresh, good.
But the view doesn't update.
I think that requestContext.update("form:messages"); is in the wrong place.
But if a get RequestContext.getCurrentInstance() from inside the Callable.call, I get a NullPointerException, because I'm not in the JSF life cycle.
What's wrong?
Thanks in advice.

How to grab POST data from external site

An external site redirect the user to my platform passing some POST data. How can grab this information from my Bean and display its in a JSF page?
I've try a lot of solution but no one works. The following is a JSF testing page.
<f:metadata>
<f:viewParam name="auth" value="#{getResponse2.auth}" required="true"/>
</f:metadata>
<ui:define name="content">
<center>
An error occurred during transaction
#{getResponse2.auth}<br />
#{getResponse2.responsecode}
</center>
Here some attempt to grab POST data:
#ManagedBean
#RequestScoped
public class getResponse extends HttpServlet {
private String paymentId;
private String result;
private String auth;
private String ref;
private String traind;
private String trackid;
private String udf1;
private String responsecode;
private String host;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
paymentId = request.getParameter("paymentid");
result = request.getParameter("result");
auth = request.getParameter("auth");
ref = request.getParameter("ref");
traind = request.getParameter("tranid");
trackid = request.getParameter("trackid");
udf1 = request.getParameter("udf1");
responsecode = request.getParameter("responsecode");
System.out.println("response code: " + responsecode);
}
Another one:
public void getResponse() {
paymentId = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("paymentId");
result = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("result");
auth = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("auth");
ref = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("ref");
traind = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("traind");
trackid = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("trakid");
udf1 = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("udf1");
responsecode = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("responsecode");
}

The JSF page ins't redirecting using by Filter interface

I am developing jsf login and logout smaller web app.I see some problems.My logout method don't removed session and not working redirecting to login page.I have asked from stackoverflow.com.The Matt user answered Filter class to me.Then I researching Filter and page cache according Matt.I used to Filter's doFilter() method, in web.xml file etc..
Here is my code:
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
UserController userController = (UserController) request.getSession().getAttribute("user");
if (userController == null || !userController.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.jsf");
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
}
}
And logout()
public String logout() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ec = context.getExternalContext();
final HttpServletRequest request = (HttpServletRequest) ec.getRequest();
request.getSession(false).invalidate();
return "logout";
}
And web.xml configuration:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>org.bis.logic.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
After logging I rendering home page.
<body>
<!--
#{ session.invalidate();
response.sendRedirect("login.jsf");
} -->
<h:panelGrid rendered="#{userController.isLoggedIn()}">
Hello Mr . #{userController.user.name}
<br />
<h:form>
<p align="right">
<h:commandLink action="#{userController.logout()}"value="Logout" />
</p>
</h:form>
</h:panelGrid>
</body>
My userController managedBean class:
#ManagedBean(name = "userController")
#SessionScoped
public class UserController {
private User user;
public UserController() {
user = new User();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public String authenticate() {
if (user.getName().equals("admin") && user.getPassword().equals("")) {
return "success";
} else
addErrorMessage(String
.format("Username and Password didn't match !!!"));
return "fail";
}
The page navigation xml:
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/home.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/home.xhtml</from-view-id>
<navigation-case>
<from-action>#{userController.logout()}</from-action>
<from-outcome>logout</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
Your filter is running in an infinite redirect loop. The request on login.jsf will also invoke the filter. If the user is still not logged in, then it will redirect back to login.jsf which will in turn invoke the filter again, etcetera.
There are basically 2 ways to fix this:
Make sure that login.jsf is not covered by the URL pattern of the filter. Collect all secured pages (expect of login.jsf!) in a separate folder like /app, /secured, /pages, etc and map the filter on that URL pattern instead, e.g. /app/*.
Add an extra check which determines if the request is already requesting the login page and if so, then don't redirect to it again.
String loginURL = request.getContextPath() + "/login.jsf";
boolean loggedIn = userController != null && userController.isLoggedIn();
boolean loginRequest = request.getRequestURI().equals(loginURL);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURL);
}

JSF HTTP Session Login

I try to create login form in web application.
in JSP page I can use
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
but now I am using JSF /Facelets for web application
I don't know how to create session in JSF Backing bean for client and check if user is logged in or not so it will redirect into login page.
who can help me give me link tutorial for these problem ?
thank you before
Now I have little problem with mapping into web.xml
code snipped of class Filter
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
LoginController controller = (LoginController) req.getSession()
.getAttribute("loginController");
if (controller == null || !controller.isLoggedIn()) {
res.sendRedirect("../admin/login.xhtml");
} else {
chain.doFilter(request, response);
}
}
and in web.xml I map with <fitler> tag
<filter>
<filter-name>userLoginFilter</filter-name>
<filter-class>com.mcgraw.controller.UserLoginFilter</filter-class>
<init-param>
<param-name>loginPage</param-name>
<param-value>/login.xhtml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>userLoginFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
I have one folder admin in web project and I check if the user is not logged in with admin permission to not access page (I can do the permission check) but when I use the filter the browser doesn't understand url ??
no StackTrace show when the browser doesn't understand url
Error shown on Firefox
The page isn't redirecting properly
on IE it loading ... loading . .. non-stop
now I change condition which check if req.getPathInfo.startsWith("/login.xhtml") it will do chain
I have 2 idea but it response 500 HTTP STATUS
if (controller == null || !controller.isLoggedIn()) {
res.sendRedirect("../admin/login.xhtml");
if(req.getPathInfo().startsWith("/login.xhtml")){
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
===============
if (controller == null || !controller.isLoggedIn()) {
if (!req.getPathInfo().startsWith("/login.xhtml")) {
res.sendRedirect("../admin/login.xhtml");
} else {
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
======================
update Class loginController
package com.mcgraw.controller;
import com.DAO.UserBean;
import com.entity.IUser;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
* #author Kency
*/
#ManagedBean
#SessionScoped
public class LoginController implements Serializable {
#EJB
private UserBean userBean;
private IUser user;
private boolean admin;
private boolean mod;
private PasswordService md5;
/** Creates a new instance of LoginController */
public LoginController() {
user = new IUser();
md5 = new PasswordService();
}
// getter / setter
public boolean isMod() {
return mod;
}
public void setMod(boolean mod) {
this.mod = mod;
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public String cplogin() {
String md5Password = md5.md5Password(user.getPassword());
if (userBean.userLogin(user.getUsername(), md5Password) != null) {
if (user.getUsername() != null || md5Password != null) {
user = userBean.userLogin(user.getUsername(), md5Password);
if (user.getGroups().getAdmin() != null) {
setAdmin(user.getGroups().getAdmin());
}
if (user.getGroups().getMods() != null) {
setMod(user.getGroups().getMods());
}
if (isAdmin() == true || isMod() == true) {
return "home";
} else {
return "login";
}
} else {
return "login";
}
} else {
return "login";
}
}
public String logout() {
user = null;
return "login";
}
public boolean isLoggedIn() {
return user != null;
}
}
I have new problem if render JSF taglib with method loggedIn, in index page (not in admin folder) user doesn't login can see what I render example, <== this like if user doesn't login user can't see but why can he see it?
You can in JSF get/set HTTP session attributes via ExternalContext#getSessionMap() which is basically a wrapper around HttpSession#get/setAttribute().
#Named
#RequestScoped
public class LoginController {
private String username;
private String password;
#EJB
private UserService userService;
public String login() {
User user = userService.find(username, password);
FacesContext context = FacesContext.getCurrentInstance();
if (user == null) {
context.addMessage(null, new FacesMessage("Unknown login, try again"));
username = null;
password = null;
return null;
} else {
context.getExternalContext().getSessionMap().put("user", user);
return "userhome?faces-redirect=true";
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "index?faces-redirect=true";
}
// ...
}
In the Facelets page, just bind the username and password input fields to this bean and invoke login() action accordingly.
<h:form>
<h:inputText value="#{loginController.username}" />
<h:inputSecret value="#{loginController.password}" />
<h:commandButton value="login" action="#{loginController.login}" />
</h:form>
Session attributes are directly accessible in EL. A session attribute with name user is in EL available as #{user}. When testing if the user is logged in some rendered attribute, just check if it's empty or not.
<h:panelGroup rendered="#{not empty user}">
<p>Welcome, #{user.fullName}</p>
<h:form>
<h:commandButton value="logout" action="#{loginController.logout}" />
</h:form>
</h:panelGroup>
The logout action basically just trashes the session.
As to checking an incoming request if a user is logged in or not, just create a Filter which does roughly the following in doFilter() method:
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + "/login.xhtml";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER);
if (loggedIn || loginRequest || resourceRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
Map it on an url-pattern covering the restricted pages, e.g. /secured/*, /app/*, etc.
See also:
How to handle authentication/authorization with users in a database?
Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same
Try this in your backing bean when a request is received (like in an action method):
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = request.getSession();
Then you can work with the request and session objects just like you used to with JSPs, setting attributes and so on.
You might also want to take a look at my related question about checking the client session in a servlet Filter. You could write a similar Filter to check for the user login in their HttpSession and then do a redirect (or RequestDispatch like I ended up doing) to your login page if needed.

Resources