tags:

views:

101

answers:

2

Hello All ! 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 using JSF /Facelets for web application i dont know how to create session in JSF Backing bean for client and check if user login or not login 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 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 user not login with permission admin not to access page ( i can do check permission) but when i user filter browser dont unserstand url ?? not StackTrace show when browser dont understand url

Error show 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 methog 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?

A: 

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.

Jim Tough
HttpSession have method setAttribute() the same session in jSP but how can i maintain and check session in client ?
Kency
@Kency I'm not understanding what it was you were doing before. Can you edit your question and provide some of your old code? When you say "check session in client", do you actually mean that you are checking something on the client-side using JavaScript?
Jim Tough
@Jimtough i was find phaselistenter to check user login for JSF. My question is when user access web page via web browser jsf will check user login or not it means in jsp i write 1 page session.getAttribute("thename") and include it in header page where i want to check user login or not login. But use phaselistener will check it but now i not yet understand phaselistener work. you have tutorial link for JSF login session,if any? if you have give me link to tutorial thank you
Kency
+1  A: 

Create a session scoped managed bean which roughly look like this:

@ManagedBean
@SessionScoped
public class UserManager {
    private String username;
    private String password;
    private User user;

    public String login() {
        user = userDAO.find(username, password);
        if (user != null) {
            username = password = null;
            return "home";
        } else {
            setMessage("Unknown login, please retry.");
            return "login";
        }
    }

    public String logout() {
        user = null;
        return "login";
    }

    public boolean isLoggedIn() {
        return user != null;
    }

    // ...
}

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="#{userManager.username}" />
    <h:inputSecret value="#{userManager.password}" />
    <h:commandButton value="login" action="#{userManager.login}" />
</h:form>

When testing if the user is logged in, make use of the UserManager#isLoggedIn() in some rendered attribute, e.g.

<h:panelGroup rendered="#{userManager.loggedIn}">
    <p>Welcome, #{userManager.user.fullName}</p>
</h:panelGroup>

No need to fiddle with raw servlet API like that. Session scoped beans are stored as session attribtues anyway.


As to checking if an user is logged in or not, just create a Filter which does roughly the following in doFilter() method:

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
UserManager userManager = (UserManager) req.getSession().getAttribute("userManager");
if (userManager == null || !userManager.isLoggedIn()) {
    res.sendRedirect("login.xhtml");
} else {
    chain.doFilter(request, response);
}

Map it on an url-pattern covering the restricted pages, e.g. /secured/*. Note that the managed bean name is exactly the session attribute name.

BalusC
hi BalusC all it ok but i have little problem with map to web.xml page you can see above question i was edit, i have folder admin in web project and redirect to ../admin/login.xhtml it not work browser dont understand it
Kency
If the login page is placed in `/admin`, then the same filter will be invoked again and it will go in an infinite redirect loop because the user isn't logged in. Either place the login page outside the `/admin` or add a condition which checks if `req.getPathInfo().startsWith("/login.xhtml")` and then just continue the chain and don't redirect.
BalusC
once again i was edited my question with solution you suggest but i retrieve error 500 HTTP Status in glassfish server it throws Null Pointer Exception
Kency
OK, the pathinfo is apparently `null` in your filter. Use `req.getRequestURI().endsWith("/login.xhtml")` instead.
BalusC
You're welcome.
BalusC
thank you for your support ! but when it redirect to login.xhtml i true but i want chang extension to login.jsf
Kency
Just change it accordingly in the URL's in the filter.
BalusC
oh i missing mapped `<url-pattern>*.jsf</url-pattern>` and edit in filter class, once again thank you very much
Kency
Hi Balusc I have new Problem with it, userlogin above i use for admincp but when i access to main page( it out of admincp folder) example content/register.xhtml it redirect me to http://localhost/content/admin/login.jsf. how can i avoid redirect in page out of admincp folder, i was map in web.xml url-partern is `<url-partern>/admin/*</url-partern>` Thank you!
Kency
Redirect to `/content/login.jsf` or `../login.jsf` instead.
BalusC
Hi Balusc i do it but i repeat loading to login.jsf http://localhost/myproject/admin/login.jsf, in firefox i get message `The page isn't redirecting properly` , true url redirect in filter is `res.sendRedirect("../admin/login.jsf");`
Kency
and i have problem with logout, when i logout user is null and re-login it throws Exception target null user.username. why error? Thank you
Kency
The first error is caused because you're redirecting to the login page in an infinite loop. You have to either move the login page outside the url-pattern of the filer or check inside the filter if the currently requested page is not the login page. As to the logout, just add a `if (user != null)` check before accessing the user.
BalusC
Thank you , i move login in other folder of admin folder and other page inside content folder. it work well Thank you
Kency
Where do i add `if(user !=null)` ? login method or logout method? i try with logout and login but it not work
Kency
Just there where `NullPointerException` was caused because `user` is `null`.
BalusC
Hi BalusC i get exception `WARNING: /admin/login.xhtml @43,73 value="#{loginController.user.username}": Target Unreachable, 'null' returned null` i dont know where i can add user != null, i was updated question with code. GoodNight BalusC Thank You!
Kency
That's not a `NullPointerException`. The `#{loginController.user}` just returned `null` and therefore it's impossible to set `#{loginController.user.username}`. You need to ensure that `#{loginController.user}` never returns null. Usually, you'd like to preinitialize nested beans during declaration or bean's construction or postconstruct like `user = new User()`. And.. in the future, please ask a new question for each independent problem :)
BalusC
Thank you ! but i was preinitialize it in constructor and when end-user call method login, user set to null in this method user=null and user is global varialbe when user logout it set to null therefore loginController.user is null,i know it, but i dont know how to re-initial it to user = new User(); After this problem i will post each question for independent problem :) Thank You
Kency
You'd like to approach this problem a bit differently. Instead of relying on the presence of the `User` to check if someone is logged in or not, use for example `if (user.getId() != null)`. On logout, just do `user = new User()` to prepare the login fields.
BalusC