2

i'm currently working with JSF, but since i'm a old and grouchy php-dev i always mess up with the GET-Parameters of an request. (In PHP you can access the request Paramerts whenever you want, using the $_GET["paramname"] Array.

Now, i'm working on an User Managment System. (CRUD) Usually i go with a list of all available users, having options like edit / delete. The edit link is then pointing to http:\\localhost\editUser.xhtml?userId=5 for example.

I have also an Controller called UserEditController which basically holds the user entity and invokes the update.

So, inside this Controller I'm using the @PostConstruct Annotation to load the user with the id 5 from the DataService and store it inside a property.

Problem here is: Wenn entering PostConstruct-Method in the APPLY_REQUEST_VALUES-Phase im not able to access the request Parameter Map of Faces Context (Will return null for userId)

Controller (simplified):

@Named
@RequestScoped
UserEditController{


@Inject
private UserDataService userDataService;

private User currentUser;

@PostConstruct
public void initValues(){
    String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userId");

    this.currentUser = userDataService.getUserById(id);
}

public String saveCurrentUser(){
    userDataService.updateUser(this.currentUser);
    return "userManagement"; //return to overview after saving
}

//getter and setter
}

This works as intened. All the Form-Fields now are bound to user's properties like #{userEditController.currentUser.forename} etc.

I now added a save button with action attribute {userEditController.saveCurrentUser()}

However the script then enters the APPLY_REQUEST_VALUES-Phase And the UserEditController's initValues is called again.

  • this results in a nullpointer Exception, when trying to access the RequestParameterMap
  • and obviously i dont want to reload the user BEFORE saving it :-)

This sounds like a stupid question but i think i'm messing up between the PHP-Style and the JSF-Style to handle things.

Any Help would be appreciated.

4

2 回答 2

2

将用户(或用户 ID)传递给 BackingBean 的常用方法是使用以下选项之一:

http://www.mkyong.com/jsf2/4-ways-to-pass-parameter-from-jsf-page-to-backing-bean/

我认为主要问题是您的 bean 是@RequestScoped. 如果您在编辑页面上按下保存按钮,您将发送一个新请求,因此将创建一个请求范围 bean 的新实例。只需将您的 bean 更改为@ViewScoped.

更多信息:

于 2012-11-13T15:46:26.973 回答
0

我试图将其更改为 ViewScoped 但每次访问属性时它都会以“调用构造函数”为 bean 结束......

同时我尝试了很多东西,没有按预期工作:

我可以让它工作的唯一情况是将控制器设置为“SessionScoped”。但我认为这不是一个好方法,因为我需要处理“清理”值并导致大量未定义(初始化)的 bean ......

我创建了一个简单的项目来玩 arround。这是有效的会话范围版本。但是如果我改变范围,我需要在点击保存按钮时“重新加载”当前用户。如果无法访问请求参数,我不知道如何实现。

(我尝试使用“表单”再次传递用户 ID,但后来我在“第一次”传递 id 时遇到问题)

这是我的样本。(Getter 和 Setter 可用,为了简短起见,没有提及)

用户等级:

public class User {

   private String firstname;
   private String lastname;

   public User (String f, String l){
       this.firstname = f;
       this.lastname = l;
   }
}

数据库模拟器:

@Named("dbSimulator")
@SessionScoped
public class DBSimulator implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 659826879566280911L;

private Map<String, User> data;

public DBSimulator() {
    //Load data
    User u1 = new User("Mickey", "Maus");
    User u2 = new User("Peter", "Pan");

    this.data = new HashMap<String, User>();
    this.data.put("Mickey", u2);
    this.data.put("Max", u1);
}

public List<User> getUserList(){
    List<User> l = new LinkedList<User>();

    for (Map.Entry<String, User> user : data.entrySet()) {
        l.add(user.getValue());
    }

    return l;

}

public void saveUser(User user){
    this.data.put(user.getFirstname(), user);
}
}

用户管理控制器:

@Named
@SessionScoped
public class UserManagementController implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -4300851229329827994L;

@Inject
private DBSimulator dbSimulator;

private List<User> users;

public UserManagementController() {
    System.out.println("UserManagementController:construct()");
}

@PostConstruct
public void LoadUsers(){
    this.setUsers(this.dbSimulator.getUserList());
}
}

用户编辑控制器

@Named
@SessionScoped
public class UserEditController implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1867483972880755108L;

@Inject
private DBSimulator dbSimulator;

private User user;

public UserEditController() {
    System.out.println("UserEditController:construct()");
}

public String activateUser(User user){
    this.setUser(user);
    System.out.println("setting User");
    return "userEdit";
}

public String save(){
    //Save user
    this.dbSimulator.saveUser(user);
    return "userManagement";
}

}

最后两个 XHTML 文件:UserManagement.xhtml

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

<h:head>
<title>Test</title>
</h:head>
<h:body>
    <h:outputText value="Select user to edit." />

    <h:dataTable value="#{userManagementController.users}" var="user">
        <h:column>
            <f:facet name="header">Firstname</f:facet>
            <h:outputText value="#{user.firstname}" />
        </h:column>

        <h:column>
            <f:facet name="header">Lastname</f:facet>
            <h:outputText value="#{user.lastname}" />
        </h:column>

        <h:column>
            <f:facet name="header">Options</f:facet>
            <h:form>
                <h:commandLink action="userEdit" actionListener="#{userEditController.activateUser(user)}" value="edit user" />
            </h:form>
        </h:column>
    </h:dataTable>
</h:body>
</html>

用户编辑.xhtml

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


<h:head>
<title>Test</title>
</h:head>
<h:body>
    <h:form>
        <h:inputText value="#{userEditController.user.firstname}"></h:inputText>
        <br /><br />
        <h:inputText value="#{userEditController.user.lastname}"></h:inputText>
        <br /><br />
        <h:commandButton value="save" action="#{userEditController.save}"></h:commandButton>
    </h:form>

</h:body>
</html>

ps.:我不希望任何人“更正”我的代码 - 但也许有人能够看到完整的例子,我的 headeck 来自哪里:)

使用 ViewScoped Bean 会生成以下控制台输出:

[pageload]
12:07:49,126 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:07:49,334 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:07:49,341 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
[edit click]
12:08:35,410 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,411 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,412 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,413 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,414 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,414 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,415 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,416 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,416 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,417 INFO  [stdout] (http--0.0.0.0-8090-3) UserManagementController:construct()
12:08:35,476 INFO  [stdout] (http--0.0.0.0-8090-3) UserEditController:construct()
12:08:35,478 INFO  [stdout] (http--0.0.0.0-8090-3) setting User
12:08:35,494 INFO  [stdout] (http--0.0.0.0-8090-3) UserEditController:construct()
12:08:35,497 INFO  [stdout] (http--0.0.0.0-8090-3) UserEditController:construct()

显然用户不再设置,因为(ViewScoped)UserEditController在设置用户后已经重建了两次......

于 2012-11-14T11:11:08.133 回答