`

jee6 学习笔记 2 - @ManagedBean

    博客分类:
  • JEE
阅读更多
看看BackingBean(or ActionBean if you like),先上图。

the login screen

login validation 1: missing required fields

login validation 2: wrong password

home screen: after successful login


login.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"> 
    
<h:head>
</h:head>

<h:body>
    <p:panel header="Login Panel" style="width:50%">
     <h:messages/>
     <h:form>
      <h:panelGrid columns="2">
      <h:outputLabel value="username: "/> 
      <h:inputText id="nameId" value="#{loginBean.user.username}"/>
      <h:outputLabel value="password: "/> 
      <h:inputSecret id="passId" value="#{loginBean.user.password}"/>
      <!-- call action bean method login() -->
      <h:commandButton type="submit" value="Login" action="#{loginBean.login}"/>
      </h:panelGrid>
     </h:form>
    </p:panel>
</h:body>
</html>


Backing bean "LoginBean.java"
package com.jxee.action;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.jxee.ejb.UserDAO;
import com.jxee.model.User;

/**
 * Backing bean for login.xhtml
 * @ManagedBean used to replace the declaration of the bean in faces-config.xml
 * <br/>you can give it a name, like @ManagedBean("myBean"), otherwise, it defaults
 * to the class name with the first character lower cased, eg, "loginBean". So in this
 * example, it can be accessed in JSF pages like this: #{loginBean.login}
 */
@ManagedBean
@SuppressWarnings("all")
public class LoginBean implements Serializable {
  
  private static final Logger log = Logger.getLogger(LoginBean.class);
  
  // inject EJB UserDAO for accessing database
  // it's recommended to use CDI annotations @javax.inject.Inject, instead of @EJB.
  // but in my current environment, it's just not working. Also not working is the
  // annotation @javax.inject.Named. don't why, probably CDI is not available in JBoss6.1?
  @EJB UserDAO userDao;
  
  private User user = new User();
  
  public User getUser() { return this.user; }
  public void setUser(User user) { this.user = user; }

  // called by "login.xhtml" to login user
  public String login() {
    
    log.debug("login user: " + user.getUsername());
    log.debug("userDao is null ? " + (userDao == null ? "true" : "false"));
    
    try {
      User registeredUser = this.userDao.findUserByName(user.getUsername());
      
      if(registeredUser != null) {
        if(registeredUser.getUsername().equals(user.getUsername())) {
          if(registeredUser.getPassword().equals(user.getPassword())) {
            log.debug("user logged in: " + registeredUser.getUsername());

          // 直接定义,爽!!!no fking navigation rules!
            return "home";  // send user to "home.jsf", 
          }
          else {
            FacesMessage errormsg = new FacesMessage("Hey! forget your password?");
            FacesContext.getCurrentInstance().addMessage(null, errormsg);
            return "login";
          }
        }
      }
    }
    catch(Exception e) {
      log.debug(e);
    }
      
    FacesMessage regmsg = new FacesMessage("Hey! please register...");
    FacesContext.getCurrentInstance().addMessage(null, regmsg);
    
    return "login"; // should redirect to "register.xhtml"
  }
  
  // called by "home.xhmtl" logout
  public String logout() {
    log.debug("invalidate session for user: " + user.getUsername());
    HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    if(session != null) {
      String sessionId = session.getId();
      session.invalidate();
      log.debug("session invalidated: " + sessionId);
    }
    return "login"; // return to login page "log.xhtml"
  }
  
  // called by "home.xhtml" to render some data only
  public String getSessionId() {
    ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession)cntxt.getSession(false);
    
    // it seems that JSF creates the session automatically, is it good or necessary?
    if(session == null) {
      log.debug("creating http session for user: " + user.getUsername());
      session = (HttpSession)cntxt.getSession(true);
    }
    
    log.debug(String.format("jsf2 created session already, id=%s, created time: %s", 
                            session.getId(), new java.util.Date(session.getCreationTime())));
    
    return session != null ? session.getId() : "no session found";
  }
}


package com.jxee.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * entity bean to table "jwtest.appuser"
 * validation done here as well -- this is excellent!
 */
@Entity
@Table(name="APPUSER")
public class User implements Serializable {
  
  @Id
  @GeneratedValue
  @Column(name="userid")
  private Integer userid;
  
  @Column(name="username")
  @NotNull(message="username cannot be null")
  @Size(min=4,max=20,message="username must be 4-20 characters")
  private String username;
  
  @Column(name="password")
  @NotNull(message="password cannot be null")
  @Size(min=4,max=10, message="password must be 4-10 characters")
  private String password;
  
  @Column(name="email")
  @Pattern(regexp="^(.)+@(.)+$", message="email must match something@somedomain")
  private String email;
  
  
  public Integer getUserid() {
    return userid;
  }

  public void setUserid(Integer userid) {
    this.userid = userid;
  }
  
  public String getUsername() {
    return username;
  }
  
  public void setUsername(String username) {
    this.username = username;
  }
  
  public String getPassword() {
    return password;
  }
  
  public void setPassword(String password) {
    this.password = password;
  }
  
  public String getEmail() {
    return email;
  }
  
  public void setEmail(String email) {
    this.email = email;
  }
}


小姐以下:

1。 @ManagedBean替代了faces-config.xml,这是好事啊,xml配置文件是最讨厌了。从J2EE开始,一堆爱克斯爱慕爱澳(xml)文件,他们说这样灵活,你说有多操蛋!现在人们终于回过味来了。就像EJB2被(死脑筋(sbrain-spring) )打得晕头转向才搞了EJB3是一样。

2。 jsf搞了一堆标签,这太讨厌了,看看开头的name spaces就知道了。希望primefaces能做好,以后就主流化了。richfaces死气沉沉的,文档也是草蛋的。

3。 CDI @java.inject.Inject and @javax.inject.Named 在这个例子里不行,不知道为什么。可能我的环境有问题,JBoss6.1不支持吗?还来还得看看CDI,完全没概念。

4。 Validation放在entity上很爽,希望其“message"属性能支持EL表达式,这样能国际化。

5。 Navigation rules 可以直接定义在Backing Bean里面,这太好了!太爽了!

6。 Web MVC框架最主要的任务,其实就是自动绑定ActionBean/Backing Bean,并提供较好的Form Validation支持。通过这个例子,目前可以说明JSF2/EJB3.1/JPA的搭配已经很简洁了。如果能很好地运用Primefaces,相信利用JEE6来开发,根本不需要什么第三方的框架,而完全是标准技术。

没架子多好!不但容易提高,工作轻松了,而且好找工作了。你想到木有?!

下一片看看EJB/JPA: jee6 学习笔记 3 - an ejb3.1 DAO
  • 大小: 24.4 KB
  • 大小: 20.4 KB
  • 大小: 27.1 KB
  • 大小: 19.4 KB
分享到:
评论

相关推荐

    jee6 学习笔记 6.3 - @Asynchronous

    `@Asynchronous`是Java EE 6引入的EJB 3.1规范的一部分,它可以应用在无状态会话bean(Stateless Session Bean)的方法上。当一个带有`@Asynchronous`的方法被调用时,调用者会立即返回,而实际的方法执行将在另一...

    开发工具 eclipse-jee-mars-2-win32

    开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32...

    eclipse-jee-mars-2-win32

    eclipse-jee-mars-2-win32 javaee开发工具 eclipse-jee-mars-2-win32 javaee开发工具

    eclipse-jee-ganymede-SR2-win32.zip2

    eclipse-jee-ganymede-SR2-win32.zip

    eclipse-jee-juno-SR2-linux-gtk-x86_64.tar.gz

    标题 "eclipse-jee-juno-SR2-linux-gtk-x86_64.tar.gz" 指示的是一个特定版本的Eclipse集成开发环境(IDE)针对Java企业版(Java Enterprise Edition,简称JEE)的发行包,适用于Linux操作系统,并且是64位(x86_64...

    eclipse-jee-luna-SR2-win32-x86_64网盘下载地址(官网厂货)

    eclipse-jee-luna-SR2-win32-x86_64网盘下载地址(官网厂货); 绿色纯净版,解压缩方可运行(亲测可行)

    eclipse-jee-indigo-SR2-win32百度云下载:

    标题中的“eclipse-jee-indigo-SR2-win32”指的是Eclipse IDE的一个特定版本,它是专为Java EE(企业级Java)开发者设计的。Eclipse是一个开源的集成开发环境(IDE),广泛用于Java编程,它提供了丰富的工具集来支持...

    eclipse-jee-kepler-SR2-win32 svn插件

    大家下载eclipse-jee-kepler-SR2-win32.zip解压后运行,发现不能直接从SVN中导入项目,下面是我自己想到的方法: 方法:找到自己使用过的带有svn的,低版本的eclipse,找到features和plugins目录,将其中的带有“org...

    eclipse-jee-juno-SR2-win32-x86_64

    eclipse-jee-juno-SR2-win32-x86_64, 百度云盘下载!

    jee6 学习笔记 5 - Struggling with JSF2 binding GET params

    这篇"jee6 学习笔记 5 - Struggling with JSF2 binding GET params"主要探讨了开发者在使用JSF2绑定GET参数时可能遇到的挑战和解决方案。 JSF2是一个基于MVC(模型-视图-控制器)设计模式的Java框架,用于创建交互...

    Eclipse64位3.6.2太阳神版eclipse-jee-helios-SR2-win32-x86_64.zip支持jdk1.5

    Eclipse64位3.6.2太阳神版eclipse-jee-helios-SR2-win32-x86_64.zip支持jdk1.5 Eclipse 支持jdk1.5 64位 helios 太阳神版 eclipse-jee-helios-SR2-win32-x86_64.zip 更多eclipse版本可看查看我的系列,欢迎下载~

    eclipse-jee-mars-1-win32-x86_64.7z

    eclipse-jee-mars-1-win32-x86_64.7z eclipse-jee-mars-1-win32-x86_64.zip 我打的 7z 压缩包 关于有 Alt + / 不起作用解决办法: window -&gt; General -&gt; Keys -&gt; Content Assist -&gt; Binding: 改为 Alt + / When:...

    Eclipse-jee-indigo-SR2-win32

    标题"Eclipse-jee-indigo-SR2-win32"指的是Eclipse IDE的特定版本,用于Java企业级(Java EE)开发。Eclipse是一款开源的集成开发环境(IDE),深受Java开发者喜爱,它提供了丰富的功能来支持代码编写、调试、测试和...

    eclipse-jee-2023-12-R-win32-x86-64.zip

    eclipse-jee-2023-12-R-win32-x86_64.zip 适用于Windows系统

    eclipse-jee-2021-12-R-win32-x86_64

    eclipse-jee-2021-12-R-win32-x86_64 eclipse-jee-2021-12-R-win32-x86_64 eclipse-jee-2021-12-R-win32-x86_64

    eclipse-jee-neon-1a-win_64

    eclipse-jee-neon-1a-win_64

    eclipse-jee-2023-09-R-linux-gtk-x86-64.tar.gz

    "eclipse-jee-2023-09-R-linux-gtk-x86_64.tar.gz" 文件是Eclipse专为Java企业版(Java EE)开发者设计的2023年9月版本,适用于64位的Linux操作系统。这个版本包含了对Java EE开发所需的全部工具和功能,如Web服务器...

    eclipse-jee-2023-12-R-linux-gtk-x86-64.tar.gz

    eclipse-jee-2023-12-R-linux-gtk-x86_64.tar.gz 适用于Linux x86_64位系统

    eclipse-jee-2022-06-R-win32-x86_64.zip

    在解压eclipse-jee-2022-06-R-win32-x86_64.zip后,我们会得到一个名为“eclipse”的文件夹,这个文件夹包含了整个IDE的所有组件和配置。启动Eclipse IDE,用户会看到熟悉的界面,包括工作区(Workspace)、透视图...

Global site tag (gtag.js) - Google Analytics