Работа с get-запросами в JSF

JAVA*
Как известно JSF умеет работать только с post-запросами, однако существет метод, который позволяет разбирать и get.


Делается это примерно так:

1. Создаем реквестный бин чтобы извлечь параметры запроса.
package ru.beans;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class EntryBean {

  // название параметра в строке get-запроса
  private static final String PARAM_ID = "id";

  private Integer id = null;

  // в конструкторе получаем необходимые параметры запроса
  public EntryBean() {
    HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();

    String id = req.getParameter(PARAM_ID);
    if(id != null) {
      setId(Integer.parseInt(id));
    }
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public int getId() {
    return id;
  }

  // здесь определяем на какую страницу надо перейти
  public String getEntryLocation() {
    String result = "/userList.jsf";

    if (getId() != null) {
      result = "/userDetail.jsf";
    }

    return result;
  }
}


* This source code was highlighted with Source Code Highlighter.

2. Реализуем интерфейс PhaseListener:
pacakage ru.lifecycle;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

import ru.beans.EntryBean;

public class RedirectPhaseListener implements PhaseListener {

    // на какой фазе будем выполнять
    public PhaseId getPhaseId() {
    return PhaseId.RESTORE_VIEW;
    }

    // выполненение до фазы
    public void beforePhase(PhaseEvent event) {
        FacesContext ctx = event.getFacesContext();
        HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest();
        
        String path = request.getServletPath();
        EntryBean entry = null;
    if ((path != null) && path.endsWith("/entry.jsf")) {
      // находим бин в контексте
      entry = (EntryBean)ctx.getApplication().evaluateExpressionGet(ctx, "#{EntryBean}", EntryBean.class);
      try {
        String location = entry.getEntryLocation();
        
        // создаем ViewRoot для новой страницы
        UIViewRoot newPage = ctx.getApplication().getViewHandler().createView(ctx, location);
        ctx.setViewRoot(newPage);
        
        // сюда пишем код, который устанавливает необходимые значения, например:
        if(entry.getId() != null) {
          customersBean.setCustomerId(entry.getId());
        }

      // если что-то пошло не так...
      } catch (Throwable e) {
            log.error("Failed to redirect", e);
         }
      // отображаем то, что накреативили
      ctx.renderResponse();
    }
  }

  // оставляем пустым
  public void afterPhase(PhaseEvent event) {
  }
}


* This source code was highlighted with Source Code Highlighter.

3. В faces-config.xml создаем категорию
<lifecycle>
  <phase-listener>ru.lifecycle.RedirectPhaseListener</phase-listener>
</lifecycle>


* This source code was highlighted with Source Code Highlighter.
+5
26 ноября 2008, 15:35
5
FlashXL 8,3

комментарии (3)

0
DbLogs #
Посмотрите в сторону Jboss Seam и будет Вам счастье:)
0
krolser #
А может подойдет такой способ:
В faces-config.xml дописать что-нибудь подобное.

<managed-bean>
<managed-bean-name>customer</managed-bean-name>
<managed-bean-class>.....</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>customerId</property-name>
#{param.customerId}
</managed-property>
</managed-bean>
0
vanyatka #
Если сделали поддержку только GET, значит это кому-нибудь нужно?

Только зарегистрированные пользователи могут оставлять комментарии. Войдите, пожалуйста.