1
I’m having a really hard time with the PrimeFaces 5 + JSF
.
I have two applications in the company where I work and the same ones running on intranet, but when someone executes something, queries or navigates between both application and another user accesses it, this new user and all others enter the system with this same view of the old user.
Ex: User A -> Accessed the C tab and searched the animals registered on system and the same returned a list; User B and C -> Access or Log in the same system, and already enter Tab C, viewing the list of animals searched by User A;
Summary: Users who are being logged in or accessing the system, enter the application viewing the last state of the same.
PS My MB is annotated as @Requestscoped
<?xml version='1.0' encoding='UTF-8' ?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<f:view>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Escala de Plantão</title>
<script>
PrimeFaces.locales['pt'] = {
closeText: 'Fechar',
prevText: 'Anterior',
nextText: 'Próximo',
currentText: 'Começo',
monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
dayNamesMin: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
weekHeader: 'Semana',
firstDay: 0,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: '',
timeOnlyTitle: 'Só Horas',
timeText: 'Tempo',
hourText: 'Hora',
minuteText: 'Minuto',
secondText: 'Segundo',
ampm: false,
month: 'Mês',
week: 'Semana',
day: 'Dia',
allDayText: 'Todo o Dia'
};
</script>
</h:head>
<h:body>
<h:form id="form" style="height:100%;">
<p:growl id="msg" life="5000" />
<p:layout fullPage="true">
<p:layoutUnit position="west" size="400">
<h:panelGrid columns="2" style="width:100%;" border="1" >
<p:panel id="panelInclusao" header="Inclusão" style="height:95%;border: 0px;">
<h:panelGrid columns="2" style="width:100%;" cellpadding="5" >
<p:outputLabel for="disciplina" value="Disciplina: " />
<p:selectOneMenu id="disciplina" value="#{plantaoControllerMB.idDisciplina}" valueChangeListener="#{plantaoControllerMB.onChangeDisciplina}" style="width:100%;">
<f:selectItem itemLabel="Selecione uma disciplina" itemValue="" />
<f:selectItems value="#{plantaoControllerMB.listaDisciplina}" />
<p:ajax event="change" update="colaborador" />
</p:selectOneMenu>
<p:outputLabel for="colaborador" value="Colaborador: " />
<p:selectOneMenu id="colaborador" value="#{plantaoControllerMB.idColaborador}" style="width:100%;">
<f:selectItem itemLabel="Selecione um colaborador" itemValue="" />
<f:selectItems value="#{plantaoControllerMB.listaColaborador}" />
</p:selectOneMenu>
<p:outputLabel for="intervalo" value="Intervalo: " />
<p:selectOneMenu id="intervalo" value="#{plantaoControllerMB.idIntervaloPlantao}" style="width:100%;">
<f:selectItem itemLabel="Selecione um intervalo" itemValue="" />
<f:selectItems value="#{plantaoControllerMB.listaIntervaloPlantao}" />
</p:selectOneMenu>
<p:outputLabel for="data" value="Dia do Plantão:" />
<p:calendar id="data" value="#{plantaoControllerMB.dataPlantao}" pattern="dd/MM/yyyy" effect="fold" style="width:100%;" locale="pt" />
<br/>
<h:panelGrid columns="2" style="width:100%;">
<p:commandButton value="Salvar" id="btnSalvar" type="submit" ajax="true" process="@form" actionListener="#{plantaoControllerMB.salvarPlantao}" update="msg, tabelaRegistros" style="width:100%" />
</h:panelGrid>
</h:panelGrid>
</p:panel>
</h:panelGrid>
<h:panelGrid columns="2" border="1" style="width:100%;">
<p:panel id="panelConsulta" header="Consulta" style="height:95%;border: 0px;">
<h:panelGrid columns="2" style="width:100%;" cellpadding="5" >
<p:outputLabel for="disciplinaPesquisa" value="Disciplina: " />
<p:selectOneMenu id="disciplinaPesquisa" value="#{plantaoControllerMB.idDisciplinaPesquisa}" valueChangeListener="#{plantaoControllerMB.onChangeDisciplinaPesquisa}" style="width:100%;">
<f:selectItem itemLabel="Filtro de Pesquisa" itemValue="" />
<f:selectItems value="#{plantaoControllerMB.listaDisciplinaPesquisa}" />
<p:ajax event="change" update="colaboradorPesquisa" />
</p:selectOneMenu>
<p:outputLabel for="colaboradorPesquisa" value="Colaborador: " />
<p:selectOneMenu id="colaboradorPesquisa" value="#{plantaoControllerMB.idColaboradorPesquisa}" style="width:100%;">
<f:selectItem itemLabel="Filtro de Pesquisa" itemValue="" />
<f:selectItems value="#{plantaoControllerMB.listaColaboradorPesquisa}" />
</p:selectOneMenu>
<p:outputLabel for="dataInicioMes" value="Data Início: " />
<p:calendar id="dataInicioMes" value="#{plantaoControllerMB.dataInicioMes}" pattern="dd/MM/yyyy" effect="fold" style="width:100%;" locale="pt" />
<p:outputLabel for="dataFimMes" value="Data Fim: " />
<p:calendar id="dataFimMes" value="#{plantaoControllerMB.dataFimMes}" pattern="dd/MM/yyyy" effect="fold" style="width:100%;" locale="pt" />
<br/>
<h:panelGrid columns="2" style="width:100%;" >
<p:commandButton value="Pesquisar" id="btnPesquisar" type="submit" ajax="true" process="@form" actionListener="#{plantaoControllerMB.pesquisarPlantao}" update="msg, tabelaRegistros" style="width:100%" />
</h:panelGrid>
</h:panelGrid>
</p:panel>
</h:panelGrid>
<h:panelGrid columns="2" cellpadding="10" border="1" style="width:100%;" >
<p:panel id="panelRelatorio" header="Relatório" style="height:95%;border: 0px;">
<h:panelGrid columns="2" style="width:100%;" cellpadding="4" >
<p:outputLabel for="dataInicio" value="Data Início da Semana: (Segunda)" />
<p:calendar id="dataInicio" value="#{plantaoControllerMB.dataInicioSemana}" pattern="dd/MM/yyyy" effect="fold" style="width:100%;" locale="pt" />
<p:outputLabel for="tiporelatorio" value="Tipo de Relatório: " />
<p:selectOneRadio id="tiporelatorio" value="#{plantaoControllerMB.tipoRelatorio}" >
<f:selectItem itemLabel="PDF" itemValue="PDF" />
<f:selectItem itemLabel="EXCEL" itemValue="EXCEL" />
</p:selectOneRadio>
<br/>
<h:panelGrid columns="2" style="width:100%;">
<p:commandButton value="Gerar Plantão Consolidado" id="btnGerarPlantao" ajax="false" actionListener="#{plantaoControllerMB.getSampleReportPDF}" update="msg" >
<p:fileDownload value="#{plantaoControllerMB.streamedContent}" />
</p:commandButton>
</h:panelGrid>
</h:panelGrid>
</p:panel>
</h:panelGrid>
</p:layoutUnit>
<p:layoutUnit id="layoutUnit2" position="center">
<h:panelGrid columns="1" cellpadding="10">
<p:dataTable id="tabelaRegistros" var="registro" value="#{plantaoControllerMB.listaRegistroVO}" selection="#{plantaoControllerMB.listSelectedExcluirVO}" rowKey="#{registro.idRegistro}"
editable="false" style="margin-bottom:20px" emptyMessage="Sem Registros." paginator="true" rowsPerPageTemplate="5,10,15">
<f:facet name="header">
Lista dos Plantonistas
</f:facet>
<p:column selectionMode="multiple" style="width:16px;text-align:center"/>
<p:column headerText="Dia">
<h:outputText value="#{registro.dataPlantao}" style="text-align:center;width:100%" />
</p:column>
<p:column headerText="Intervalo">
<h:outputText value="#{registro.intervaloPlantao}" style="text-align:center; width:100%" />
</p:column>
<p:column headerText="Disciplina">
<h:outputText value="#{registro.nomeDisciplina}" style="text-align:center; width:100%" />
</p:column>
<p:column headerText="Colaborador">
<h:outputText value="#{registro.nomeColaborador}" style="text-align:center; width:100%" />
</p:column>
<f:facet name="footer" >
<p:column style="width:16px">
<p:commandButton value="Excluir" id="btnExcluir" type="submit" ajax="true" process="@form" actionListener="#{plantaoControllerMB.excluirRegistroEscalaPlantao}" update=":form:msg, tabelaRegistros"/>
</p:column>
</f:facet>
</p:dataTable>
</h:panelGrid>
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
</f:view>
</html>
package com.iedacr.plantao.controller;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewExpiredException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import net.sf.jasperreports.engine.JRException;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.iedacr.plantao.spring.model.Colaborador;
import com.iedacr.plantao.spring.model.ColaboradorIntervaloPlantao;
import com.iedacr.plantao.spring.model.Disciplina;
import com.iedacr.plantao.spring.model.IntervaloPlantao;
import com.iedacr.plantao.spring.model.RegistroVO;
import com.iedacr.plantao.spring.service.PlantaoService;
import com.iedacr.plantao.util.ConnectionFactoryJDBC;
import com.iedacr.plantao.util.ReportUtils;
import com.iedacr.plantao.util.TiposRelatorio;
@Controller
@RequestScoped
@ManagedBean(name = "plantaoControllerMB")
public class PlantaoControllerMB implements Serializable {
private static final long serialVersionUID = 8257510266299290234L;
@Autowired
private PlantaoService plantaoService;
private ColaboradorIntervaloPlantao colaboradorIntervaloPlantaoVO;
private List<SelectItem> listaIntervaloPlantao;
private List<SelectItem> listaColaborador;
private List<SelectItem> listaDisciplina;
private List<SelectItem> listaDisciplinaPesquisa;
private List<SelectItem> listaColaboradorPesquisa;
private String idIntervaloPlantao;
private String idDisciplina;
private String idColaborador;
private Date dataPlantao;
private List<RegistroVO> listaRegistroVO;
private List<RegistroVO> listSelectedExcluirVO;
private Date dataInicioSemana;
private StreamedContent streamedContent;
private String tipoRelatorio;
private String idDisciplinaPesquisa;
private String idColaboradorPesquisa;
private Date dataInicioMes;
private Date dataFimMes;
public void addMessageInfo(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void addMessageError(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
@PostConstruct
public void init() {
listaDisciplina = new ArrayList<SelectItem>();
listaDisciplinaPesquisa = new ArrayList<SelectItem>();
for (Disciplina disciplina : plantaoService.getListDisciplina()) {
listaDisciplina.add(new SelectItem(disciplina.getId(), disciplina.getNome()));
listaDisciplinaPesquisa.add(new SelectItem(disciplina.getId(), disciplina.getNome()));
}
listaIntervaloPlantao = new ArrayList<SelectItem>();
for (IntervaloPlantao intervaloPlantao : plantaoService.getListIntervalo()) {
listaIntervaloPlantao.add(new SelectItem(intervaloPlantao.getId(), intervaloPlantao.getIntervalo()));
}
listaColaborador = new ArrayList<SelectItem>();
listaColaboradorPesquisa = new ArrayList<SelectItem>();
listaRegistroVO = new ArrayList<RegistroVO>();
listSelectedExcluirVO = new ArrayList<RegistroVO>();
}
public String validarCamposInclusao() {
if (idDisciplina == null || idDisciplina.isEmpty()) {
return "Erro: Favor informar o Disciplina";
}
if (idColaborador == null || idColaborador.isEmpty()) {
return "Erro: Favor informar o Colaborador";
}
if (idIntervaloPlantao == null || idIntervaloPlantao.isEmpty()) {
return "Erro: Favor informar o Intervalo do Plantão";
}
if (dataPlantao == null) {
return "Erro: Favor informar o Dia do Plantão";
}
return null;
}
public void salvarPlantao() {
String result = validarCamposInclusao();
if (result != null) {
addMessageError(result);
return;
}
SimpleDateFormat dataf = new SimpleDateFormat("dd/MM/yyyy");
String strDataPlantaoFormatada = dataf.format(dataPlantao).toString();
/*if(plantaoService.isExistePlantonistaByDay(new BigDecimal(idColaborador), strDataPlantaoFormatada)){
addMessageError("Já existe um plantão cadastrado para este colaborador no dia informado ");
} else{*/
colaboradorIntervaloPlantaoVO = new ColaboradorIntervaloPlantao();
colaboradorIntervaloPlantaoVO.setDataPlantao(new java.sql.Date(dataPlantao.getTime()));
colaboradorIntervaloPlantaoVO.setColaborador(plantaoService.getColaboradorById(new BigDecimal(idColaborador)));
colaboradorIntervaloPlantaoVO.setIntervaloPlantao(plantaoService.getIntervaloPlantaoById(new BigDecimal(idIntervaloPlantao)));
ColaboradorIntervaloPlantao entidadePersistida = plantaoService.save(colaboradorIntervaloPlantaoVO);
RegistroVO regVO = new RegistroVO();
regVO.setDataPlantao(dataf.format(colaboradorIntervaloPlantaoVO.getDataPlantao()));
regVO.setIdRegistro(entidadePersistida.getId().toString());
regVO.setIntervaloPlantao(colaboradorIntervaloPlantaoVO.getIntervaloPlantao().getIntervalo());
regVO.setNomeColaborador(colaboradorIntervaloPlantaoVO.getColaborador().getNome());
regVO.setNomeDisciplina(colaboradorIntervaloPlantaoVO.getColaborador().getDisciplina().getNome());
listaRegistroVO.add(regVO);
addMessageInfo("Plantão de " + colaboradorIntervaloPlantaoVO.getColaborador().getNome() + " foi salvo com sucesso! ");
//}
}
public void gerarPlantaoConsolidado() throws ViewExpiredException {
if (dataInicioSemana == null) {
addMessageError("Erro: Informe a data de início da uma semana para gerar o plantão consolidado");
return;
}
InputStream inputStream = getClass().getResourceAsStream("/Plantao.jasper");
Map<String, Object> parametros = new HashMap<String, Object>();
GregorianCalendar gregorian = new GregorianCalendar();
gregorian.setTime(dataInicioSemana);
if (gregorian.get(GregorianCalendar.DAY_OF_WEEK) != 2) {
addMessageError("Erro: A data início da semana não corresponde a segunda-feira.");
return;
}
SimpleDateFormat dataf = new SimpleDateFormat("dd/MM/yyyy");
parametros.put("DATA_INICIO", dataf.format(dataInicioSemana).toString());
gregorian.add(gregorian.DATE, 6);
parametros.put("DATA_FIM", dataf.format(gregorian.getTime()).toString());
{
parametros.put("SEGUNDA", dataf.format(dataInicioSemana).toString());
gregorian.setTime(dataInicioSemana);
gregorian.add(gregorian.DATE, 1);
parametros.put("TERCA", dataf.format(gregorian.getTime()).toString());
gregorian.add(gregorian.DATE, 1);
parametros.put("QUARTA", dataf.format(gregorian.getTime()).toString());
gregorian.add(gregorian.DATE, 1);
parametros.put("QUINTA", dataf.format(gregorian.getTime()).toString());
gregorian.add(gregorian.DATE, 1);
parametros.put("SEXTA", dataf.format(gregorian.getTime()).toString());
gregorian.add(gregorian.DATE, 1);
parametros.put("SABADO", dataf.format(gregorian.getTime()).toString());
gregorian.add(gregorian.DATE, 1);
parametros.put("DOMINGO", dataf.format(gregorian.getTime()).toString());
}
try {
// abre o relatório
ReportUtils.openReport("Plantonistas da Fiscalização", inputStream, parametros,
ConnectionFactoryJDBC.getPlantaoConnection());
addMessageInfo(" Plantão consolidado gerado com sucesso! ");
} catch (SQLException exc) {
addMessageError("Erro na consulta do relatório.");
} catch (JRException exc) {
exc.printStackTrace();
}
}
public void excluirRegistroEscalaPlantao() {
if (listSelectedExcluirVO == null || listSelectedExcluirVO.isEmpty()) {
addMessageError("É necessário selecionar ao menos um colaborador para efetuar o processo de exclusão!");
} else {
List<RegistroVO> listVO = new ArrayList<RegistroVO>();
listVO.addAll(listaRegistroVO);
for (int i = 0; i < listVO.size(); i++) {
for (RegistroVO tempExcluir : listSelectedExcluirVO) {
if (tempExcluir.getIdRegistro().equals(listVO.get(i).getIdRegistro())) {
listVO.remove(i);
plantaoService.delete(plantaoService.getById(new BigDecimal(tempExcluir.getIdRegistro())));
}
}
}
listaRegistroVO.clear();
listaRegistroVO.addAll(listVO);
addMessageInfo("A exclusão dos registros selecionados foi realizada com sucesso!");
}
}
public List<SelectItem> getColaboradoresByDiciplina(String idDisciplina) {
listaColaborador.clear();
for (Colaborador colaborador : plantaoService.getColaboradoresByDiciplina(new BigDecimal(idDisciplina))) {
listaColaborador.add(new SelectItem(colaborador.getId(), colaborador.getNome()));
}
return listaColaborador;
}
public List<SelectItem> getColaboradoresByDiciplinaPesquisa(String idDisciplina) {
listaColaboradorPesquisa.clear();
for (Colaborador colaborador : plantaoService.getColaboradoresByDiciplina(new BigDecimal(idDisciplina))) {
listaColaboradorPesquisa.add(new SelectItem(colaborador.getId(), colaborador.getNome()));
}
return listaColaboradorPesquisa;
}
public void onChangeDisciplina(ValueChangeEvent e) {
if (e.getNewValue() != null) {
this.listaColaborador = getColaboradoresByDiciplina(e.getNewValue().toString());
}
}
public void onChangeDisciplinaPesquisa(ValueChangeEvent e) {
if (e.getNewValue() != null) {
this.listaColaboradorPesquisa = getColaboradoresByDiciplinaPesquisa(e.getNewValue().toString());
}
}
public void pesquisarPlantao() {
RegistroVO regVO = new RegistroVO();
regVO.setIdDisciplina(idDisciplinaPesquisa);
regVO.setIdColaborador(idColaboradorPesquisa);
//regVO.setIdIntervaloPlantao(idIntervaloPlantao);
if (dataInicioMes != null) {
SimpleDateFormat dataf = new SimpleDateFormat("dd/MM/yyyy");
String strDataPlantaoFormatada = dataf.format(dataInicioMes).toString();
regVO.setDataInicioMes(strDataPlantaoFormatada);
} else {
regVO.setDataInicioMes(null);
}
if (dataFimMes != null) {
SimpleDateFormat dataf = new SimpleDateFormat("dd/MM/yyyy");
String strDataPlantaoFormatada = dataf.format(dataFimMes).toString();
regVO.setDataFimMes(strDataPlantaoFormatada);
} else {
regVO.setDataFimMes(null);
}
listaRegistroVO.clear();
listaRegistroVO.addAll(plantaoService.pesquisarPlantao(regVO));
}
public StreamedContent exportFileToPDF() {
return streamedContent;
}
public StreamedContent getSampleReportPDF() {
streamedContent = null;
return streamedContent;
}
}
Show the code of your Managed bean - at least the party that delivers this list whose status is maintained between sessions. If the MB is Requestscoped, then the state is being kept in another object.
– Caffé
There’s plenty of code there and you haven’t pointed out what exactly keeps it in between sessions. The injected bean Plantaoservice seems to have a larger scope than it should have (should be with application scope) or uiliza the state of another bean with application scope - ie, have to analyze the code of Plantaoservice. But you’ve got the point: from the list you’re maintaining status follow all the objects used and find out which one is in application scope and then narrow the scope or clear the state with each request (the second option is difficult because it would need to be thread safe).
– Caffé