apache deltaspike0.5的入门小例子

seam3已经宣布不再发布新的版本。据seam论坛说,seam的开发成员去了apache deltaspike,所以,开始apache deltaspike的体验。

这个例子是一个简单的登录,与权限无关。


1.环境:

jboss7.1.1.final

jdk1.7

jsf2.1

deltaspike0.5(cdi的扩展)

picketlink2.5.2(安全框架)


2.首先给出一个简单的登录页面。

-----


      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">

   



   


       
       
   


   

       
       
   


   


   


   

       
   

    

demo about jpa and picketlink.






  
 Welcome #{identity.account.loginName}!
      
      



  


-----

3.单击登录按钮{Login}时,将会触发action="#{identity.login}"事件,此事件自动调用BaseAuthenticator类的authenticate方法。


4.重写authenticate方法,用来从用户表中检查登录用户是否是存在于数据库中。

---


package security;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.picketlink.annotations.PicketLink;
import org.picketlink.authentication.BaseAuthenticator;
import org.picketlink.credential.DefaultLoginCredentials;
import org.picketlink.idm.model.basic.User;

@PicketLink
public class SimpleAuthenticator extends BaseAuthenticator {
    @Inject DefaultLoginCredentials credentials;
    @Inject EntityManager em;
    @Override
    public void authenticate() {
        String username,password;
        Query query = null;
        List result=new ArrayList();
        
        username=credentials.getUserId();
        password=credentials.getPassword();
        //EntityManager em=BeanProvider.getContextualReference(EntityManager.class,false);
        String sql="select * from webuser where username=:u and password=:p";

        //我用的是jpa原生Sql,可以用其他的方式。
        query=em.createNativeQuery(sql);
        query.setParameter("u", username);
        query.setParameter("p", password);
        result=query.getResultList();
        if(result.size()>0){

            User u = new User(credentials.getUserId());
            System.out.println(credentials.getUserId() +" logined.");
            // if employee credentials.getUserId() login
            u.setEmail(credentials.getUserId()+"@deltaspike.com");
            u.setFirstName(credentials.getUserId());
            u.setLastName(credentials.getUserId());
            setAccount(u);
            setStatus(AuthenticationStatus.SUCCESS);

        }else{
            setStatus(AuthenticationStatus.FAILURE);
           // FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Authentication Failure - The username or password you provided were invalid."));

        }
    }
}

---




需要说明的:

1.用了maven,所以第一次运行要能够联网,才能下载需要的依赖包。

2.源码在这里http://download.csdn.net/detail/mihaisheng/6530503


你可能感兴趣的:(apache deltaspike0.5的入门小例子)