0

コードで primefaces メッセージを使用しようとすると問題が発生します。テストを実行すると、メッセージは正常に機能しますが、ストリーム ファイルを実行して xhtml でメッセージを送信しようとすると、プロセスは正常に機能しますが、メッセージが大きくなりません。

私のコード:

public void cadastrar () throws KeyStoreException, CADoesntExistsException,        NoSuchAlgorithmException, CertificateException, IOException      
{           
    FacesContext fc = FacesContext.getCurrentInstance();            
    if((controlador.checkUserIfExist(certificadoModel.getUsername()) == false) || (controlador.checkUserIfExist(certificadoModel.getUsername()) == true && authorization == true))
    {
        System.out.println("Revoke: " + authorization);
        System.out.println("Check: " + controlador.checkUserIfExist(certificadoModel.getUsername()));
        //KeyStore keyStore = controlador.cadastrar(certificadoModel);      
        System.out.println("Bean Class: " + certificadoModel.getMensagem());
        /*       
        ExternalContext ec = fc.getExternalContext();

        ec.responseReset(); 
        ec.setResponseContentType("application/x-pkcs12"); 
        //ec.setResponseContentLength(contentLength); 
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + certificadoModel.getUsername() + ".p12" + "\""); 

        OutputStream output = ec.getResponseOutputStream();
        keyStore.store(output, certificadoModel.getPassword().toCharArray());
          */
        fc.addMessage("mensagem", new FacesMessage(FacesMessage.SEVERITY_INFO, "Teste", "")); 
        //fc.responseComplete();            
        controlador.clean(certificadoModel);            
    }else           
        fc.addMessage("mensagem", new     FacesMessage(FacesMessage.SEVERITY_ERROR, "Um usuário com o mesmo username já está     cadastrado!", ""));  
        controlador.clean(certificadoModel);
}

マイページコード:

<!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"> 
    <ui:decorate template="/resources/template/default.xhtml">
        <ui:define name="centro"> 
            <h:form id="cadastro"> 
                <p:panel id="painelCadastro" header="Novo Cadastro" style="margin-bottom:10px;">         
                    <p:messages id="mensagem" autoUpdate="true" closable="true" />   

                    <p:commandButton action="#{certificadoBean.cadastrar}"  ajax="false" value="Cadastrar" update="mensagem" />                   
                    <p:commandButton outcome="homePage" ajax="false" value="Home Page"/>                                  
                </p:panel>       
            </h:form>  
        </ui:define>
    </ui:decorate>
</html>

@BalusC、これが私がやったことです。

xhtml

                <p:commandButton value="Cadastrar" action="#{downloadBean.prepareDownload}" update="mensagem" />
                <p:messages globalOnly="true" />
                <h:outputScript rendered="#{not empty downloadBean.downloadKey}">
                    window.location = '#{request.contextPath}/download?key=#{downloadBean.downloadKey}';
                </h:outputScript>   

                <p:commandButton outcome="homePage" ajax="false" value="Home Page"/>                                  
            </p:panel>       
        </h:form>  

DownloadBean クラス

public class DownloadBean {

private String downloadKey; 

public void prepareDownload() throws NamingException {
    FacesContext context = FacesContext.getCurrentInstance();

    CertificadoModel certificadoModel = new CertificadoModel();
    CertificadoControlador controlador = new CertificadoControlador();      

    if ((controlador.checkUserIfExist(certificadoModel.getUsername()) == false)) 
    {
        downloadKey = UUID.randomUUID().toString();     
        context.getExternalContext().getSessionMap().put(downloadKey, certificadoModel);
        context.addMessage("mensagem", new FacesMessage(FacesMessage.SEVERITY_INFO, "Usuário cadastrado com sucesso!", "")); 
    }else {
        context.addMessage("mensagem", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Um usuário com o mesmo username já está cadastrado!", ""));  
    }           
}

public String getDownloadKey() {
    return downloadKey;
}

DownloadServlet クラス

public class DownloadServlet extends HttpServlet {

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String downloadKey = request.getParameter("key");
    CertificadoModel certificadoModel = (CertificadoModel) request.getSession().getAttribute(downloadKey);

    System.out.println("Teste!");

    CertificadoControlador controlador = null;
    try {
        controlador = new CertificadoControlador();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    request.getSession().removeAttribute(downloadKey);

    KeyStore keyStore = null;
    try {
        keyStore = controlador.cadastrar(certificadoModel);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CADoesntExistsException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }  

    response.reset();
    response.setContentType("application/x-pkcs12"); 
    //response.setContentLength(contentLength); 
    response.setHeader("Content-Disposition", "attachment; filename=\"" + certificadoModel.getUsername() + ".p12" + "\""); 

    try {
        keyStore.store(response.getOutputStream(), certificadoModel.getPassword().toCharArray());
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {           
        e.printStackTrace();
    }
}

そしてweb.xmlで

<servlet>
    <servlet-name>DownloadServlet</servlet-name>
    <servlet-class>br.com.certificado.beans.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DownloadServlet</servlet-name>
    <url-pattern>/download</url-pattern>
</servlet-mapping>
4

1 に答える 1

2

基本的に、1 つの HTTP リクエストに対して 2 つの HTTP レスポンスを返そうとしています。これは明らかに不可能です。

最善の策はwindow.location、目的のファイルのダウンロードを返す新しい HTTP 要求を送信する URL で JavaScript 呼び出しを条件付きでレンダリングすることです。単純なサーブレットは、この作業に非常に適したツールです。この回答にリストされている方法のいずれかを使用して、サーブレット内のマネージド Bean にアクセスできます:任意のサーブレット関連クラスで JSF マネージド Bean を名前で取得するか、一意のセッション属性キーを生成してリクエスト パラメーターとして渡すことができます。

最後のアプローチを使用したキックオフの例を次に示します。

<h:form>
    ...
    <p:commandButton ... action="#{bean.prepareDownload}" update="@form" />
    <p:messages globalOnly="true" />
    <h:outputScript rendered="#{not empty bean.downloadKey}">
        window.location = '#{request.contextPath}/download?key=#{bean.downloadKey}';
    </h:outputScript>
</h:form>

(注:/downloadサーブレットの URL パターンと正確に一致する必要があります)

この豆で:

private String downloadKey; // +Getter.

public void prepareDownload() {
    FacesContext context = FacesContext.getCurrentInstance();

    if (canDownload) {
        downloadKey = UUID.randomUUID.toString();
        context.getExternalContext().getSessionMap().put(downloadKey, certificadoModel);
        context.addMessage(null, infoMessage);
    } else {
        context.addMessage(null, errorMessage);
    }
}

そしてこのサーブレット:

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String downloadKey = request.getParameter("key");
        CertificadoModel certificadoModel = (CertificadoModel) request.getSession().getAttribute(downloadKey);
        request.getSession().removeAttribute(downloadKey);

        // ...

        response.reset();
        response.setContentType("application/x-pkcs12"); 
        response.setContentLength(contentLength); 
        response.setHeader("Content-Disposition", "attachment; filename=\"" + certificadoModel.getUsername() + ".p12" + "\""); 
        keyStore.store(response.getOutputStream(), certificadoModel.getPassword().toCharArray());
    }

}
于 2013-04-08T18:21:54.550 に答える