validaÇÃo personalizada

2 respostas
T

Pessoal, é o seguinte vou tentar passar ao máximo de informações.... basicamente quero determinar faixas salariais para pessoas do sexo masculino e feminino, jhá tenho funcionando na aplicação inclusive a validação f:validateDoubleRange minimum="380" maximum="50000" mas esta faixa é para ambos terei que determinar faixas diferentes... vai aí todo o meu código fonte:

é divido em tres camadas apresentação, negócio e persistência

[img]http://br.geocities.com/frangospelados/tela.JPG[/img]

Apresentação

Bean.java

package br.teste.manterpessoa.apresentacao;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.MaskFormatter;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.manterpessoa.negocio.ManterPessoaBO;
import br.teste.util.ControleExcecao;

public class ManterPessoaBean {
	private String pess_nome;
	private Long pess_seq;
	private String data_nasc;
	private Long salario;
	private String sexo;
	
	
	
// aqui fica seus respectivos Getters and Setters


	
	public String alterar() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_seq(pess_seq);
			dto.setPess_nome(pess_nome);
			dto.setData_nasc(data_nasc);
			dto.setSalario(salario);
			bo.alterar(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_ALTERAR_PESSOA);
			return "erro";
		}
	}

	public ListDataModel getConsultar() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		List lista;
		PessoaDTO dto = new PessoaDTO();
		dto.setPess_nome(pess_nome);
		dto.setPess_seq(pess_seq);

		lista = bo.consultar(dto);
		return new ListDataModel(lista);
	}

	public String excluir() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_seq(pess_seq);
			bo.excluir(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_EXCLUIR_PESSOA);
			return "erro";
		}
	}

	public String incluir() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_nome(pess_nome);
			dto.setData_nasc(data_nasc);
			dto.setSalario(salario);
			dto.setSexo(sexo);
			bo.incluir(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_INCLUIR_PESSOA);
			return "erro";
		}
	}

	public String loadAlterar() throws Throwable {
		HttpServletRequest request = null;
		PessoaDTO dto = new PessoaDTO();
		Long codigo;
		try {
			request = (HttpServletRequest) FacesContext.getCurrentInstance()
					.getExternalContext().getRequest();
			String parametro = (String) request.getParameter("pess_seq");
			codigo = Long.parseLong(parametro);
			ManterPessoaBO bo = new ManterPessoaBO();
			dto = bo.consultar(codigo);
			pess_nome = dto.getPess_nome();
			pess_seq = dto.getPess_seq();
			data_nasc = dto.getData_nasc();
			salario = dto.getSalario();
			sexo = dto.getSexo();
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_ALTERAR_PESSOA);
			return "erro";
		}
	}

	public String loadExcluir() throws Throwable {
		HttpServletRequest request = null;
		PessoaDTO dto = new PessoaDTO();
		Long codigo;
		try {
			request = (HttpServletRequest) FacesContext.getCurrentInstance()
					.getExternalContext().getRequest();
			String parametro = (String) request.getParameter("pess_seq");
			codigo = Long.parseLong(parametro);
			ManterPessoaBO bo = new ManterPessoaBO();
			dto = bo.consultar(codigo);
			pess_nome = dto.getPess_nome();
			pess_seq = dto.getPess_seq();
			data_nasc = dto.getData_nasc();
			salario = dto.getSalario();
			sexo = dto.getSexo();
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_EXCLUIR_PESSOA);
			return "erro";
		}
	}
	

	

	public ArrayList getPreencheCombo() throws Throwable {
		ArrayList listacombo = null;
		ManterPessoaBO bo = new ManterPessoaBO();
		listacombo = bo.consultar();
		return listacombo;
	}

	

}

Negócio

BO.java

package br.teste.manterpessoa.negocio;

import java.util.ArrayList;
import java.util.List;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.manterpessoa.persistencia.ManterPessoaDAO;

public class ManterPessoaBO{
	private ManterPessoaDAO dao = new ManterPessoaDAO();

	public void alterar(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.alterar(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public List consultar(PessoaDTO dto) throws Exception{
		try {
			List res = null;
			if (dto != null) {
				if (dto.getPess_nome() != null && dto.getPess_nome().trim().equals("")) {
					dto.setPess_nome(null);
				}
				if (dto.getPess_seq() != null) {
					dto.setPess_seq(null);
				}
				res = dao.consultar(dto);
			}
			return res;
		} catch (Exception e){
			throw new Exception (e);
		}
	}

	public ArrayList consultar() throws Exception {
		try {
			return dao.consultar();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public PessoaDTO consultar(Long codigo) throws Exception {
		try {
			PessoaDTO dto = new PessoaDTO();
			if (codigo != null) {
				dto = dao.consultar(codigo);
			}
			return dto;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public void excluir(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.excluir(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public void incluir(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.incluir(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
}

Persistência

DAO.java

package br.teste.manterpessoa.persistencia;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.faces.model.SelectItem;

import org.hibernate.Criteria;
import org.hibernate.criterion.Example;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.util.HibernateUtility;

public class ManterPessoaDAO{

	public void alterar (PessoaDTO dto) {
		HibernateUtility.getSession().update(dto);
	}

	public List consultar (PessoaDTO dto) {
		Criteria criteria = HibernateUtility.getSession().createCriteria(PessoaDTO.class);
		criteria.add(Example.create(dto));
		List lista = criteria.list();
		return lista;
	}

	public ArrayList consultar() {
		Criteria criteria = HibernateUtility.getSession().createCriteria(PessoaDTO.class);
		ArrayList<SelectItem> listaItem  = new ArrayList<SelectItem>();
		List result = criteria.list();
		Collection colecao = result;
		Iterator iteracao = colecao.iterator();
		while (iteracao.hasNext()) {
			PessoaDTO obj = (PessoaDTO)iteracao.next();
			listaItem.add(new SelectItem(obj.getPess_seq(),obj.getPess_nome()));
		}
		return listaItem;
	}

	public PessoaDTO consultar(Long codigo) {
		PessoaDTO dto = new PessoaDTO();
		dto = (PessoaDTO) HibernateUtility.getSession().get(PessoaDTO.class,codigo);
		return dto;
	}

	public void excluir (PessoaDTO dto) {
		HibernateUtility.getSession().delete(dto);
	}

	public void incluir (PessoaDTO dto) {
		HibernateUtility.getSession().save(dto);
	}

}

Essa é minha página Incluir.jsp certemente devo registrar a função nela certo... como faço isso é o meu problema, e aonde devo e como escrever a função também é o outro problema, com certeza terei que fazer um if ???????.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@taglib
	uri="/oscache" prefix="oscache"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<f:view>
	<head>
	<title>RPS - Reestruturação Organizacional, Definição de
	Processos e Desenvolvimento de Sistema</title>
	<link href="style.css" rel="stylesheet" rev="stylesheet"></link>
	<f:loadBundle basename="br.teste.util.messages" var="msgs" />
	</head>

	<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0"
		marginwidth="0" marginheight="0">
	<h:form id="form">
		<br>
		<br>
		<div class="titulo1">Incluir Pessoa</div>
		<hr color="#c0c0c0" size="1">
		<table>

			<tr>
				<td><h:outputLabel styleClass="labe1">Sexo:</h:outputLabel> <br>
				<h:selectOneMenu id="sexo" value="#{pessoa.sexo}" required="true">
					<f:selectItem id="vazio" itemLabel="" />
					<f:selectItem id="masc" itemLabel="M" itemValue="M" />
					<f:selectItem id="fem" itemLabel="F" itemValue="F" />
				</h:selectOneMenu><h:message for="sexo"></h:message></td>
			</tr>
			<tr>

				<td><h:outputLabel styleClass="labe2">Nome:</h:outputLabel> <br>
				<h:inputText id="nome" value="#{pessoa.pess_nome}" required="true"
					styleClass="input" style="width: 350px" /> <h:message for="nome"></h:message>
				</td>
			</tr>
			<tr>

				<td><h:outputLabel styleClass="labe3">Data Nasc.: </h:outputLabel>
				<br>
				<h:inputText id="data_nasc" value="#{pessoa.data_nasc}"
					required="true" styleClass="input" style="width: 132px" /> <h:message
					for="data_nasc"></h:message></td>

			</tr>
			<tr>
				<td><h:outputLabel styleClass="labe4">Salario:</h:outputLabel>
				<br>

				<h:inputText id="salario" value="#{pessoa.salario}" required="true"
					styleClass="input" style="width: 132px">
					<f:convertNumber minFractionDigits="2" />
					<f:validateDoubleRange minimum="380" maximum="50000"></f:validateDoubleRange>
				</h:inputText> <h:message for="salario" style="color:red">
				</h:message></td>
			</tr>
			<tr>
				<td><h:commandButton type="submit" action="#{pessoa.incluir}"
					value="Salvar" styleClass="btnok" /> <h:commandButton
					type="submit" action="loadManter" value="Cancelar"
					styleClass="btncancelar" immediate="true" /></td>
			</tr>
		</table>
	</h:form>
	</body>
</f:view>
</html>

2 Respostas

T
tiagotmr:
Pessoal, é o seguinte vou tentar passar ao máximo de informações.... basicamente quero determinar faixas salariais para pessoas do sexo masculino e feminino, jhá tenho funcionando na aplicação inclusive a validação f:validateDoubleRange minimum="380" maximum="50000" mas esta faixa é para ambos terei que determinar faixas diferentes... vai aí todo o meu código fonte:

é divido em tres camadas apresentação, negócio e persistência

[img]http://br.geocities.com/frangospelados/tela.JPG[/img]

Apresentação

Bean.java

package br.teste.manterpessoa.apresentacao;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.MaskFormatter;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.manterpessoa.negocio.ManterPessoaBO;
import br.teste.util.ControleExcecao;

public class ManterPessoaBean {
	private String pess_nome;
	private Long pess_seq;
	private String data_nasc;
	private Long salario;
	private String sexo;
	
	
	
// aqui fica seus respectivos Getters and Setters


	
	public String alterar() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_seq(pess_seq);
			dto.setPess_nome(pess_nome);
			dto.setData_nasc(data_nasc);
			dto.setSalario(salario);
			bo.alterar(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_ALTERAR_PESSOA);
			return "erro";
		}
	}

	public ListDataModel getConsultar() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		List lista;
		PessoaDTO dto = new PessoaDTO();
		dto.setPess_nome(pess_nome);
		dto.setPess_seq(pess_seq);

		lista = bo.consultar(dto);
		return new ListDataModel(lista);
	}

	public String excluir() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_seq(pess_seq);
			bo.excluir(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_EXCLUIR_PESSOA);
			return "erro";
		}
	}

	public String incluir() throws Throwable {
		ManterPessoaBO bo = new ManterPessoaBO();
		PessoaDTO dto = new PessoaDTO();
		try {
			dto.setPess_nome(pess_nome);
			dto.setData_nasc(data_nasc);
			dto.setSalario(salario);
			dto.setSexo(sexo);
			bo.incluir(dto);
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_INCLUIR_PESSOA);
			return "erro";
		}
	}

	public String loadAlterar() throws Throwable {
		HttpServletRequest request = null;
		PessoaDTO dto = new PessoaDTO();
		Long codigo;
		try {
			request = (HttpServletRequest) FacesContext.getCurrentInstance()
					.getExternalContext().getRequest();
			String parametro = (String) request.getParameter("pess_seq");
			codigo = Long.parseLong(parametro);
			ManterPessoaBO bo = new ManterPessoaBO();
			dto = bo.consultar(codigo);
			pess_nome = dto.getPess_nome();
			pess_seq = dto.getPess_seq();
			data_nasc = dto.getData_nasc();
			salario = dto.getSalario();
			sexo = dto.getSexo();
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_ALTERAR_PESSOA);
			return "erro";
		}
	}

	public String loadExcluir() throws Throwable {
		HttpServletRequest request = null;
		PessoaDTO dto = new PessoaDTO();
		Long codigo;
		try {
			request = (HttpServletRequest) FacesContext.getCurrentInstance()
					.getExternalContext().getRequest();
			String parametro = (String) request.getParameter("pess_seq");
			codigo = Long.parseLong(parametro);
			ManterPessoaBO bo = new ManterPessoaBO();
			dto = bo.consultar(codigo);
			pess_nome = dto.getPess_nome();
			pess_seq = dto.getPess_seq();
			data_nasc = dto.getData_nasc();
			salario = dto.getSalario();
			sexo = dto.getSexo();
			return "sucesso";
		} catch (Throwable e) {
			ControleExcecao
					.trataExcecao(e, ControleExcecao.ERRO_EXCLUIR_PESSOA);
			return "erro";
		}
	}
	

	

	public ArrayList getPreencheCombo() throws Throwable {
		ArrayList listacombo = null;
		ManterPessoaBO bo = new ManterPessoaBO();
		listacombo = bo.consultar();
		return listacombo;
	}

	

}

Negócio

BO.java

package br.teste.manterpessoa.negocio;

import java.util.ArrayList;
import java.util.List;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.manterpessoa.persistencia.ManterPessoaDAO;

public class ManterPessoaBO{
	private ManterPessoaDAO dao = new ManterPessoaDAO();

	public void alterar(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.alterar(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public List consultar(PessoaDTO dto) throws Exception{
		try {
			List res = null;
			if (dto != null) {
				if (dto.getPess_nome() != null && dto.getPess_nome().trim().equals("")) {
					dto.setPess_nome(null);
				}
				if (dto.getPess_seq() != null) {
					dto.setPess_seq(null);
				}
				res = dao.consultar(dto);
			}
			return res;
		} catch (Exception e){
			throw new Exception (e);
		}
	}

	public ArrayList consultar() throws Exception {
		try {
			return dao.consultar();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public PessoaDTO consultar(Long codigo) throws Exception {
		try {
			PessoaDTO dto = new PessoaDTO();
			if (codigo != null) {
				dto = dao.consultar(codigo);
			}
			return dto;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public void excluir(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.excluir(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	public void incluir(PessoaDTO dto) throws Exception {
		try {
			if (dto != null) { //acrescentar regras de negócio
				dao.incluir(dto);
			}else{
				throw new Exception(); // tratar exceção
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
}

Persistência

DAO.java

package br.teste.manterpessoa.persistencia;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.faces.model.SelectItem;

import org.hibernate.Criteria;
import org.hibernate.criterion.Example;

import br.teste.manterpessoa.PessoaDTO;
import br.teste.util.HibernateUtility;

public class ManterPessoaDAO{

	public void alterar (PessoaDTO dto) {
		HibernateUtility.getSession().update(dto);
	}

	public List consultar (PessoaDTO dto) {
		Criteria criteria = HibernateUtility.getSession().createCriteria(PessoaDTO.class);
		criteria.add(Example.create(dto));
		List lista = criteria.list();
		return lista;
	}

	public ArrayList consultar() {
		Criteria criteria = HibernateUtility.getSession().createCriteria(PessoaDTO.class);
		ArrayList<SelectItem> listaItem  = new ArrayList<SelectItem>();
		List result = criteria.list();
		Collection colecao = result;
		Iterator iteracao = colecao.iterator();
		while (iteracao.hasNext()) {
			PessoaDTO obj = (PessoaDTO)iteracao.next();
			listaItem.add(new SelectItem(obj.getPess_seq(),obj.getPess_nome()));
		}
		return listaItem;
	}

	public PessoaDTO consultar(Long codigo) {
		PessoaDTO dto = new PessoaDTO();
		dto = (PessoaDTO) HibernateUtility.getSession().get(PessoaDTO.class,codigo);
		return dto;
	}

	public void excluir (PessoaDTO dto) {
		HibernateUtility.getSession().delete(dto);
	}

	public void incluir (PessoaDTO dto) {
		HibernateUtility.getSession().save(dto);
	}

}

Essa é minha página Incluir.jsp certemente devo registrar a função nela certo... como faço isso é o meu problema, e aonde devo e como escrever a função também é o outro problema, com certeza terei que fazer um if ???????.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@taglib
	uri="/oscache" prefix="oscache"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<f:view>
	<head>
	<title>RPS - Reestruturação Organizacional, Definição de
	Processos e Desenvolvimento de Sistema</title>
	<link href="style.css" rel="stylesheet" rev="stylesheet"></link>
	<f:loadBundle basename="br.teste.util.messages" var="msgs" />
	</head>

	<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0"
		marginwidth="0" marginheight="0">
	<h:form id="form">
		<br>
		<br>
		<div class="titulo1">Incluir Pessoa</div>
		<hr color="#c0c0c0" size="1">
		<table>

			<tr>
				<td><h:outputLabel styleClass="labe1">Sexo:</h:outputLabel> <br>
				<h:selectOneMenu id="sexo" value="#{pessoa.sexo}" required="true">
					<f:selectItem id="vazio" itemLabel="" />
					<f:selectItem id="masc" itemLabel="M" itemValue="M" />
					<f:selectItem id="fem" itemLabel="F" itemValue="F" />
				</h:selectOneMenu><h:message for="sexo"></h:message></td>
			</tr>
			<tr>

				<td><h:outputLabel styleClass="labe2">Nome:</h:outputLabel> <br>
				<h:inputText id="nome" value="#{pessoa.pess_nome}" required="true"
					styleClass="input" style="width: 350px" /> <h:message for="nome"></h:message>
				</td>
			</tr>
			<tr>

				<td><h:outputLabel styleClass="labe3">Data Nasc.: </h:outputLabel>
				<br>
				<h:inputText id="data_nasc" value="#{pessoa.data_nasc}"
					required="true" styleClass="input" style="width: 132px" /> <h:message
					for="data_nasc"></h:message></td>

			</tr>
			<tr>
				<td><h:outputLabel styleClass="labe4">Salario:</h:outputLabel>
				<br>

				<h:inputText id="salario" value="#{pessoa.salario}" required="true"
					styleClass="input" style="width: 132px">
					<f:convertNumber minFractionDigits="2" />
					<f:validateDoubleRange minimum="380" maximum="50000"></f:validateDoubleRange>
				</h:inputText> <h:message for="salario" style="color:red">
				</h:message></td>
			</tr>
			<tr>
				<td><h:commandButton type="submit" action="#{pessoa.incluir}"
					value="Salvar" styleClass="btnok" /> <h:commandButton
					type="submit" action="loadManter" value="Cancelar"
					styleClass="btncancelar" immediate="true" /></td>
			</tr>
		</table>
	</h:form>
	</body>
</f:view>
</html>

maurenginaldo

Oi Tiago,

Existem várias formas de fazer isso, vou dar uma sugestão:

Faça as alterações:

Dentro do seu bean crie dois atributos: salarioMinimo e salarioMaximo.

Altere o metodo setSexo():

public setSexo(String sexo) { this.sexo = sexo: if (sexo.equals('M')) { salarioMinimo = 100; salarioMaximo = 200; } else { salarioMinimo = 50; salarioMaximo = 100; } }

Altere o Jsf:

<h:inputText id="salario" value="#{pessoa.salario}" required="true" styleClass="input" style="width: 132px"> <f:convertNumber minFractionDigits="2" /> <f:validateDoubleRange minimum="#{pessoa.salarioMinimo}" maximum="#{pessoa.salarioMaximo}"></f:validateDoubleRange> </h:inputText> <h:message for="salario" style="color:red"> </h:message>

Faça aí que deve dar certo!

Criado 13 de fevereiro de 2008
Ultima resposta 14 de fev. de 2008
Respostas 2
Participantes 2