Duvida

0 respostas
helviojr

Olá boa tarde...Estou com um problema serio no desenvolvimento da minha aplicação.
Tenho uma classe Curso e a classe Professor
com o seguinte codigo:

package br.iff.campos.frameworkhorarioescolar.model.persistence;

import java.io.Serializable;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Professor implements Serializable {
	@Id
	private String matricula;

	private String nome;

	private String email;

	private String titulo;

	private String regimetrabalho;

	private String telresidencial;

	private String telcelular;

	private String situação;

	@ManyToOne
	@JoinColumn(name="codcurso")
	private Curso codcurso;

	@OneToMany(mappedBy="matricula")
	private Set<Competencia> competenciaCollection;

	@OneToMany(mappedBy="matricula")
	private Set<Horario> horarioCollection;

	@OneToMany(mappedBy="matricula")
	private Set<Disponibilidade> disponibilidadeCollection;

	private static final long serialVersionUID = 1L;

	public Professor() {
		super();
	}

	public String getMatricula() {
		return this.matricula;
	}

	public void setMatricula(String matricula) {
		this.matricula = matricula;
	}

	public String getNome() {
		return this.nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getTitulo() {
		return this.titulo;
	}

	public void setTitulo(String titulo) {
		this.titulo = titulo;
	}

	public String getRegimetrabalho() {
		return this.regimetrabalho;
	}

	public void setRegimetrabalho(String regimetrabalho) {
		this.regimetrabalho = regimetrabalho;
	}

	public String getTelresidencial() {
		return this.telresidencial;
	}

	public void setTelresidencial(String telresidencial) {
		this.telresidencial = telresidencial;
	}

	public String getTelcelular() {
		return this.telcelular;
	}

	public void setTelcelular(String telcelular) {
		this.telcelular = telcelular;
	}

	public String getSituação() {
		return this.situação;
	}

	public void setSituação(String situação) {
		this.situação = situação;
	}

	public Curso getCodcurso() {
		return this.codcurso;
	}

	public void setCodcurso(Curso codcurso) {
		this.codcurso = codcurso;
	}

	public Set<Competencia> getCompetenciaCollection() {
		return this.competenciaCollection;
	}

	public void setCompetenciaCollection(Set<Competencia> competenciaCollection) {
		this.competenciaCollection = competenciaCollection;
	}

	public Set<Horario> getHorarioCollection() {
		return this.horarioCollection;
	}

	public void setHorarioCollection(Set<Horario> horarioCollection) {
		this.horarioCollection = horarioCollection;
	}

	public Set<Disponibilidade> getDisponibilidadeCollection() {
		return this.disponibilidadeCollection;
	}

	public void setDisponibilidadeCollection(Set<Disponibilidade> disponibilidadeCollection) {
		this.disponibilidadeCollection = disponibilidadeCollection;
	}

}




package br.iff.campos.frameworkhorarioescolar.model.persistence;

import java.io.Serializable;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Curso implements Serializable {
	@Id
	private String codcurso;

	private String nomecurso;

	private String datainicio;

	private String tempominimointegracao;

	private String tempomaximointegracao;

	private String cargahtotal;

	@OneToMany(mappedBy="codcurso")
	private Set<Professor> professorCollection;

	@OneToMany(mappedBy="codcurso")
	private Set<Componentecurriculartecnico> componentecurriculartecnicoCollection;

	@OneToMany(mappedBy="codcurso")
	private Set<Turma> turmaCollection;

	@OneToMany(mappedBy="codcurso")
	private Set<Matrizcurricular> matrizcurricularCollection;

	private static final long serialVersionUID = 1L;

	//construtor dúvida
	public Curso(String codcurso2, String cargahtotal2, String nomecurso2,
			String datainicio2, String tempominimointegracao2,
			String tempomaximointegracao2) 
	   {// TODO Auto-generated constructor stub
		codcurso= codcurso2;
		cargahtotal=cargahtotal2;
		nomecurso=nomecurso2;
		datainicio=datainicio2;
		tempomaximointegracao=tempomaximointegracao2;
		tempominimointegracao=tempomaximointegracao2;
	}


	public String getCodcurso() {
		return this.codcurso;
	}

	public void setCodcurso(String codcurso) {
		this.codcurso = codcurso;
	}

	public String getNomecurso() {
		return this.nomecurso;
	}

	public void setNomecurso(String nomecurso) {
		this.nomecurso = nomecurso;
	}

	public String getDatainicio() {
		return this.datainicio;
	}

	public void setDatainicio(String datainicio) {
		this.datainicio = datainicio;
	}

	public String getTempominimointegracao() {
		return this.tempominimointegracao;
	}

	public void setTempominimointegracao(String tempominimointegracao) {
		this.tempominimointegracao = tempominimointegracao;
	}

	public String getTempomaximointegracao() {
		return this.tempomaximointegracao;
	}

	public void setTempomaximointegracao(String tempomaximointegracao) {
		this.tempomaximointegracao = tempomaximointegracao;
	}

	public String getCargahtotal() {
		return this.cargahtotal;
	}

	public void setCargahtotal(String cargahtotal) {
		this.cargahtotal = cargahtotal;
	}

	public Set<Professor> getProfessorCollection() {
		return this.professorCollection;
	}

	public void setProfessorCollection(Set<Professor> professorCollection) {
		this.professorCollection = professorCollection;
	}

	public Set<Componentecurriculartecnico> getComponentecurriculartecnicoCollection() {
		return this.componentecurriculartecnicoCollection;
	}

	public void setComponentecurriculartecnicoCollection(Set<Componentecurriculartecnico> componentecurriculartecnicoCollection) {
		this.componentecurriculartecnicoCollection = componentecurriculartecnicoCollection;
	}

	public Set<Turma> getTurmaCollection() {
		return this.turmaCollection;
	}

	public void setTurmaCollection(Set<Turma> turmaCollection) {
		this.turmaCollection = turmaCollection;
	}

	public Set<Matrizcurricular> getMatrizcurricularCollection() {
		return this.matrizcurricularCollection;
	}

	public void setMatrizcurricularCollection(Set<Matrizcurricular> matrizcurricularCollection) {
		this.matrizcurricularCollection = matrizcurricularCollection;
	}

}
Agora tenho uma um servlet principal onde a função dele é pegar o nome do formulario da minha pagina jsp e pegar classeHelper deste formulario. Para mandar salvar os dados. O codigo dele é:
package br.iff.campos.frameworkhorarioescolar.web.control;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.iff.campos.frameworkhorarioescolar.web.control.helper.GenericHelper;

/**
 * Servlet implementation class PrincipalServlet
 */
public class PrincipalServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PrincipalServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String nomeForm = request.getParameter("nomeForm");

		String helper = nomeForm.substring(0, nomeForm.indexOf(".")).concat(
				"Helper");
		String metodo = nomeForm.substring(nomeForm.indexOf(".") + 1, nomeForm
				.length());

		System.out.println(helper + " "+metodo);
		
		
		GenericHelper gHelper = null;

		Object obj = null;
		try {
			obj = Class.forName(
					"br.iff.campos.frameworkhorarioescolar.web.control.helper."
							.concat(helper)).newInstance();
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		gHelper = (GenericHelper) obj;

		try {
			@SuppressWarnings("unused")
			Object i = gHelper.getClass().getMethod(metodo,
					HttpServletRequest.class).invoke(gHelper, request);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		

		response.setContentType("text/html");
		ServletOutputStream out = response.getOutputStream();
		  out.println("<BODY></HTML>");
          out.println("<BODY></HTML>");

	}

}
Agora tenho a classe Helper que quero salvar no caso Professor
package br.iff.campos.frameworkhorarioescolar.web.control.helper;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;

import br.iff.campos.frameworkhorarioescolar.model.persistence.Professor;

public class ProfessorHelper extends GenericHelper{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	EntityManagerFactory emf= Persistence.createEntityManagerFactory("SAGHEEJB");
	EntityManager em=emf.createEntityManager();
	
	public void Excluir (HttpServletRequest request){
		
	}
	public void Salvar (HttpServletRequest request)
	{
		Professor prof=new Professor();
		prof.setMatricula(request.getParameter("matricula"));
		prof.setNome(request.getParameter("nome"));
		prof.setEmail(request.getParameter("email"));
		prof.setTitulo(request.getParameter("titulo"));
		prof.setRegimetrabalho(request.getParameter("regimetrabalho"));
		prof.setTelcelular(request.getParameter("telcelular"));
		prof.setTelresidencial(request.getParameter("telresidencial"));
		prof.setSituação(request.getParameter("situacao"));
		prof.setCodcurso(request.getParameter("codcurso"));//esse campo é uma chave estrangeira em curso pois professor pertence a um curso
	
		EntityTransaction trans= em.getTransaction();
		trans.begin();
		em.persist(prof);
		trans.commit();
		
	}
	public void Pesquisar (HttpServletRequest request)
	{
		
	}
	
}
Agora o que eu quero fazer é o seguinte tenho a minha pagina jsp e quero entrar com os dados onde este vai ser encaminhado ao principal servlet que vai direcionar para a Classe ProfessorHelper. Porém tenho uma chave estrangeira em professor, queria que o usuario selecionasse o nome de todos os cursos em um listbox que viria carregado com todos os dados cadastrados. Porém na hora de salvar na tabela ele não salvaria o nome do curso e sim o codigo do curso que uma chave estrangeira em professor. Eu não estou sabendo como carregar este listbox com os valores de cursos cadastrados. Minha pagina jsp é a seguinte.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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">
<%@page import="java.util.*" %>
<%@page import="br.iff.campos.frameworkhorarioescolar.model.persistence.*"%> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<%@page import="br.iff.campos.frameworkhorarioescolar.model.persistence.Professor"%>
<%@page import="br.iff.campos.frameworkhorarioescolar.model.persistence.Curso"%>

</head>
<% 
 Curso curso=(Curso).session.getAtribute("cursos");
 String nomecurso="&nbsp";
 Professor professor=(Professor)session.getAttribute("professores");
 String matricula="&nbsp";
 String nome="&nbsp";
 String email="&nbsp";
 String titulo="&nbsp";
 String regimetrabalho="&nbsp";
 String telcelular="&nbsp";
 String telresidencial="&nbsp";
 String situacao="&nbsp";
 string curso="&nbsp"; //essa e uma chave estrangeira para selecionar um curso a qual o professor pertence
 
  if(professor!=null)// eu verifico aqui se os campos são vazios? Pois testando ele, mesmo com campos vazios ele esta salvando
  {
	matricula=professor.getMatricula();
	nome=professor.getNome();
	email=professor.getEmail();
	titulo= professor.getTitulo();
	regimetrabalho=professor.getRegimetrabalho();
	telcelular=professor.getTelcelular();
	telresidencial=professor.getTelresidencial();
	situacao=professor.getSituação();
	//curso=professor.getCodcurso();
  }
  
    
 
 %>

<body background="imagemfundo.jpg">
<jsp:useBean id="" scope="aplicattion" class="br.iff.campos.frameworkhorarioescolar.model.persistence.Curso"/>
<table align="center" bgcolor="white" bordercolor="Green" border="3" height="800%" width="600">
<tr>
<td>
<h2>SAGHE-Sistema de Apoio ao Gerenciamento de Horário Escolar</h2>
</td>
</tr>
<tr>
<td>
<br><br>
<form method="post" action="http://localhost:8080/SAGHEWEB/PrincipalServlet">
<table align="center">	
<tr>
<td>
<center><h5 style="width: 145px">MATRICULA <font color="blue"><br><center>(Ex: 123443.112)</center></br></font> </h5><center>
</td>
<td>
 <h5> <input type= "text" style="width: 200px" name="matricula" value = <%=matricula%>></h5>
</td>  
</tr>  
<tr>
<td>
<center><h5 style="width: 145px">NOME PROFESSOR:</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="nome" value = <%=nome%>></h5>
</td>  
</tr>  

<tr>
<td>
<center><h5 style="width: 145px">E-MAIL</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="email" value = <%=email%>></h5>
</td>  
</tr> 
<tr>
<td>
<center><h5 style="width: 145px">TITULO</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="titulo" value = <%=titulo%>></h5>
</td>  
</tr> 
<tr>
<td>
<center><h5 style="width: 145px">REGIME DE TRABALHO</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="regimetrabalho" value = <%=regimetrabalho%>></h5>
</td>  
</tr> 
<tr>
<td>
<center><h5 style="width: 145px">TEL.CELULAR</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="telcelular" value = <%=telcelular%>></h5>
</td>  
</tr> 
<tr>
<td>
<center><h5 style="width: 145px">TEL.RESIDENCIAL</h5></center>
</td>
<td>
  <h5><input type= "text" style="width: 300px" name="telresidencial" value = <%=telresidencial%>></h5>
</td>  
</tr>
<tr>
<td>
  <center><h5 style="width: 145"> SITUAÇÃO:<br><font color="blue">Uma situação dele no momento.<br> Ex: Cursando Mestrado</br></font></br></h5></center>
</td>
<td>
 <h5><input type= "text" style="width: 300px" name="situacao" value = <%=situacao%>></h5>  
</td>
</tr> 
<tr>
<td>
<center><h5 style="width: 200px">SELECIONE O CURSO</h5><center>
</td>
<td>
<h5><select name="tipo" id="tipo" style="width: 200px">//Eu queria que aqui fosse carregados com os valores do bd para que o usuario possa selecionar e salvar
     <option </option>
     
    </select>
</h5>  
</td>

 </tr> 
<tr>
<td>
<center><input type="reset" value="LIMPAR" style='font-size: 12px; font-family: "Times New Roman", Serif; font-weight: bold; width: 140px'></center>
</td>
<td>
<center><input type="submit" value="SALVAR" style='color: Black; font-style: normal; font-size: 12px; font-family: "Times New Roman", Serif; font-weight: bold; width: 140px'><center>
</td>  
</tr>
</table>
    <input type="hidden" name="nomeForm" value = "Professor.Salvar">	
	  
</form>
<br><br>
</td>
</tr>

<tr>
<td>
<center><img src="ropape.jpg"></center>
</td>
</tr>
</table>
</body>
</html>
Por favor alguem me ajuda!
Criado 16 de junho de 2009
Respostas 0
Participantes 1