jee6 学习笔记 2 - @ManagedBean

看看BackingBean(or ActionBean if you like),先上图。

the login screen
[img]http://dl.iteye.com/upload/attachment/0070/3005/e6a38740-00fc-3995-b89b-3795a637621b.jpg[/img]
login validation 1: missing required fields
[img]http://dl.iteye.com/upload/attachment/0070/2999/32f2aaf4-ef01-36f5-b50e-385b844773ff.jpg[/img]
login validation 2: wrong password
[img]http://dl.iteye.com/upload/attachment/0070/3001/15455618-7015-3f2e-8d1b-b3ebe74ad18a.jpg[/img]
home screen: after successful login
[img]http://dl.iteye.com/upload/attachment/0070/3003/95882abd-3192-314e-96f9-2e6beccc25d0.jpg[/img]

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;
}
}


小姐以下: :evil:

1。 @ManagedBean替代了faces-config.xml,这是好事啊,xml配置文件是最讨厌了。从J2EE开始,一堆爱克斯爱慕爱澳(xml)文件,他们说这样灵活,你说有多操蛋!现在人们终于回过味来了。就像EJB2被(死脑筋(sbrain-spring) :D )打得晕头转向才搞了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来开发,根本不需要什么第三方的框架,而完全是标准技术。

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

下一片看看EJB/JPA: jee6 学习笔记 3 - an ejb3.1 DAO
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值