JSF 2.0 Diferença ViewScoped para session

13 respostas
E

JSF 2.0 Diferença @ViewScoped para @SessionScoped

13 Respostas

D

Com @ViewScoped o bean é mantido até a aplicação navegar p/ outra página.
Com @SessionScoped o bean é mantido até a sessão do usuário encerrar, ou seja, até essa sessão ser explicitamente invalidada (HttpSession.invalidate()) ou até a ela expirar.

E

No caso de segurança é desvantagem usar o view escoped então, porque, um usuário pode sair e deixar á pagina aberta que depois de horas, alguem vai poder usar está pagina certo?

D

@ViewScoped é um escopo menor q @SessionScoped. Se a sessão do cara expirar todos os beans em @ViewScoped tb serão destruídos.

Não há problema nenhum de segurança em usar o @ViewScoped. É na verdade muito util p/ páginas q usam enviar muitas informações através de submissões parciais com AJAX.

E

Então posso considerar que a vantagem do @ViewScoped é
que ele deixa mais leve a aplicação?

D

Basicamente!!

Ele vai fazer a mesma coisa q o @SessionScoped mais com uma duração menor.

E

então mais como ele vair diminuir o “tempo” com os objetos do bean carregado, teoricamente isso não gera uma melhor performace?
se não, porque usar ele?

D

Sim, ele gera uma carga menor de memória.

E

Valeu Obrigado

S

Boas eu tambem fiquei com esta duvida…

S

e o custom scope??
se eu tiver um formulario que sera preenchido por etapas em varias paginas fase 1 fase 2 fase 3…
sera o momento ideal para criar um custom scope???

D

Eu não cheguei a mexer com o @CustomScoped mas, pelo q andei lendo, ele é mais prático p/ criar extensões do q p/ aplicar diretamente em um projeto de aplicação. Codificar um @CustomScoped envolve codificar infraestrutura o q, na minha opinião, é trabalho de um desenvolvedor de framework e não de um desenvolvedor de aplicativos. O desenvolvedor de aplicativos deveria, em um mundo perfeito, codificar apenas a lógica de negócios da aplicação sem se preocupar com a arquitetura da mesma.

S

Distorncendo um pouco o tema deste topico alguem sabe como fazer upload em jsf2 + primefaces ou apenas em jsf2??
para uma base de dados oracle via jdbc??

V

Eu utilizei este para fazer um teste a um tempo. Deu certo, vê se entende e qualquer coisa posta aí.

public String imagemCorrente(Item item) {

        boolean uplded = false;
        boolean salved = false;
        String salvo = null;
        String upload = null;

        try {

            upload = webPatchTemporario;

            uplded = false;

            uplded = !upload.isEmpty();

        } catch (Exception e) {

            uplded = false;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO RETORNAR SE A IMAGEM ARMAZENANDA E A MESMA CARREGADA, ERRO: "
                    + e.toString().toUpperCase());
        }

        try {

            salvo = item.getFoto();

            salved = !salvo.isEmpty();

        } catch (Exception e) {

            salved = false;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO RETORNAR SE O ITEM TEM IMAGEM ARMAZENANDA, ERRO: "
                    + e.toString().toUpperCase());

        }

        if (uplded && salved) {

            imagemCorrente = upload;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "IMAGEM CARREGADA E SALVA");

        } else if (!uplded && !salved) {

            imagemCorrente = "/FIGURAS/wpic.png";

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "IMAGEM NAO CARREGADA, SERA UTILIZADA A PADRAO DO SISTEMA");

        } else if (!uplded && salved) {

            imagemCorrente = salvo;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "SEM MODIFICACOES NA IMAGEM DO ITEM, SERA UTILIZADA A JA EXISTENTE");

        } else if (uplded && !salved) {

            imagemCorrente = upload;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "IMAGEM CARREGADA");
        }

        //Avisa no prompt
        System.out.println(super.getClass().getName().toUpperCase()
                + "."
                + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                + " || "
                + "IMAGEM UTILIZADA: "
                + imagemCorrente.toUpperCase());

        return imagemCorrente;
    }

    public void upload(FileUploadEvent event) {

        try {

            if (event.getFile().getFileName().isEmpty()) {

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "ERRO, SEM ARQUIVO CARREGADO");

            } else {

                salvaTemporariamente(event.getFile().getFileName(), event.getFile().getInputstream());

                growl.addMessage("Sucesso! ", "Carregado com sucesso.");

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "ARQUIVO "
                        + nomeTemporario.toUpperCase()
                        + " CARREGADO COM SUCESSO");
            }

        } catch (IOException e) {

            growl.addMessage("Erro!", "Verificação: " + e);

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO CARREGAR ARQUIVO, ERRO: "
                    + e.toString().toUpperCase());
        }
    }

    public String realPath() {

        try {

            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

            FacesContext aFacesContext = FacesContext.getCurrentInstance();
            ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();

            caminhoReal = context.getRealPath("/");

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "SUCESSO AO OBETR O CAMINHO REAL "
                    + caminhoReal.toUpperCase());

        } catch (Exception e) {

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO OBETR O CAMINHO REAL, ERRO: "
                    + caminhoReal.toUpperCase());
        }

        //Avisa no prompt
        System.out.println(super.getClass().getName().toUpperCase()
                + "."
                + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                + " || "
                + "SERA UTILIZADO O CAMINHO"
                + caminhoReal.toUpperCase()
                + "/FIGURAS");

        return caminhoReal + "/FIGURAS";
    }

    public Item editaItemFoto(Item item) {

        try {

            boolean hasImage = item.getFoto().isEmpty();
            temImagem = !hasImage;

        } catch (Exception e) {

            temImagem = false;

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO VERIFICAR SE EXITE IMAGEM, ERRO: "
                    + e.toString().toUpperCase());
        }

        try {

            if (uploaded && temImagem) {
                //Tem Upload pronto e tem Imagem anterior = É uma substituição

                String apagar = caminhoReal + item.getFoto();

                apaga(apagar);

                item = salvaDefinitivamente(item);

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "IMAGEM SUBSTITUIDA COM SUCESSO");

            } else if (!uploaded && temImagem) {
                //Não tem upload e tem imagem = Alterou o item mas não mecheu na imagem

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "ALTEROU ITEM MAS NAO ALTEROU A IMAGEM");

            } else if (uploaded && !temImagem) {
                //Não tinha imagem e está pondo agora

                item = salvaDefinitivamente(item);

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "IMAGEM INSERIDA NO ITEM COM SUCESSO");

            } else if (!uploaded && !temImagem) {
                //Não tem imagem e não upou também

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + " ITEM CONTINUA SE IMAGEM");
            }

        } catch (Exception e) {

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO INSERIR IMAGEM, ERRO: "
                    + e.toString().toUpperCase());
        }

        uploaded = false;
        return item;
    }

    public Item salvaDefinitivamente(Item item) {

        try {

            if (uploaded) {

                String marca = trataNomeArquivo(item.getMarca());
                //Recebe o modelo do Item pelo parâmetro
                String modelo = trataNomeArquivo(item.getModelo());
                //Recebe a descrição do Item pelo parâmetro
                String descricao = trataNomeArquivo(item.getDescricao());

                if (marca.isEmpty() || modelo.isEmpty() || descricao.isEmpty()) {

                    realPath();

                    //########################################################
                    caminhoDefinitivo = caminhoDefinitivo.replace("//", "/");
                    caminhoDefinitivo = caminhoDefinitivo.replace("\\\\", "/");
                    caminhoDefinitivo = caminhoDefinitivo.replace("\\", "/");

                    nomeDefinitivo = nomeDefinitivo.replace("//", "/");
                    nomeDefinitivo = nomeDefinitivo.replace("\\\\", "/");
                    nomeDefinitivo = nomeDefinitivo.replace("\\", "/");

                    webPatchDefinitivo = webPatchDefinitivo.replace("//", "/");
                    webPatchDefinitivo = webPatchDefinitivo.replace("\\\\", "/");
                    webPatchDefinitivo = webPatchDefinitivo.replace("\\", "/");

                    caminhoDefinitivo = caminhoReal + "/";
                    nomeDefinitivo = nomeTemporario;
                    webPatchDefinitivo = "/" + nomeDefinitivo;

                    item.setFoto(webPatchDefinitivo);

                } else {

                    String sufixo = nomeTemporario;

                    caminhoDefinitivo = realPath() + "/" + marca + "/" + modelo + "/" + descricao + "/";
                    nomeDefinitivo = descricao + " - " + marca + " - " + modelo + sufixo.substring(sufixo.length() - 4, sufixo.length());
                    webPatchDefinitivo = "/FIGURAS/" + marca + "/" + modelo + "/" + descricao + "/" + nomeDefinitivo;

                    caminhoDefinitivo = caminhoDefinitivo.replace("\\\\", "/");
                    caminhoDefinitivo = caminhoDefinitivo.replace("\\", "/");
                    caminhoDefinitivo = caminhoDefinitivo.replace("//", "/");

                    nomeDefinitivo = nomeDefinitivo.replace("\\\\", "/");
                    nomeDefinitivo = nomeDefinitivo.replace("\\", "/");
                    nomeDefinitivo = nomeDefinitivo.replace("//", "/");

                    webPatchDefinitivo = webPatchDefinitivo.replace("\\\\", "/");
                    webPatchDefinitivo = webPatchDefinitivo.replace("\\", "/");
                    webPatchDefinitivo = webPatchDefinitivo.replace("//", "/");

                    item.setFoto(webPatchDefinitivo);

                }

                //Cria variável de acesso File
                File file = new File(caminhoDefinitivo);
                //Cria o diretório
                file.mkdirs();

                //Adiciona o arquivo uploaded ao InputStream
                InputStream in = new FileInputStream(new File(realFileTemporario));

                OutputStream out = new FileOutputStream(new File(caminhoDefinitivo + nomeDefinitivo));

                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = in.read(bytes)) != -1) {

                    out.write(bytes, 0, read);

                    //Avisa no prompt
//                    System.out.println(super.getClass().getName().toUpperCase()
//                            + "."
//                            + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
//                            + " || "
//                            + "ARQUIVO "
//                            + nomeDefinitivo.toUpperCase()
//                            + " SENDO SALVO EM "
//                            + caminhoDefinitivo.toUpperCase());
                }

                //Fecha o arquivo do InputStream
                in.close();

                //Apaga o arquivo temporário
                apaga(realFileTemporario);

                //Fecha e finaliza o OutPutStream
                out.flush();
                out.close();

                //Avisa no prompt
                System.out.println(super.getClass().getName().toUpperCase()
                        + "."
                        + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                        + " || "
                        + "ARQUIVO "
                        + nomeDefinitivo.toUpperCase()
                        + " SALVO EM "
                        + caminhoDefinitivo.toUpperCase());

                caminhoTemporario = "";
                caminhoDefinitivo = "";
                caminhoReal = "";
                nomeTemporario = "";
                nomeDefinitivo = "";
                webPatchTemporario = "";
                webPatchDefinitivo = "";
                realFileTemporario = "";
                realFileDefinitivo = "";
                uploaded = true;

            } else {

                item.setFoto("/FIGURAS/wpic.png");
            }

            //Recebe a marca do Item pelo parâmetro
        } catch (Exception e) {

            //Avisa no prompt
            System.out.println(super.getClass().getName().toUpperCase()
                    + "."
                    + Thread.currentThread().getStackTrace()[1].getMethodName().toUpperCase()
                    + " || "
                    + "ERRO AO SALVAR IMAGEM DEFINITIVAMENTE, ERRO: "
                    + e.toString().toUpperCase());
        }

        uploaded = false;
        return item;
    }
Criado 23 de setembro de 2010
Ultima resposta 26 de set. de 2015
Respostas 13
Participantes 4