Projeto com JSF, PrimeFaces 5, WebService Client e Server e Json

Projeto em JSF onde será feito cadastro de cursos utilizando WebService com JDBC.

As libs usadas no do Projeto foram:

asm-3.1.jar commons-codec-1.6.jar
commons-logging-1.1.1.jar fluent-hc-4.2.5.jar
gson-2.2.4.jar httpclient-4.2.5.jar
httpclient-cache-4.2.5.jar httpcore-4.2.4.jar
httpmime-4.2.5.jar jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar jaxen-1.1.6.jar
jdom-2.0.5.jar jersey-client-1.12.jar
jersey-core-1.12.jar jersey-json-1.12.jar
jersey-server-1.12.jar jersey-servlet-1.12.jar
jettison-1.1.jar jsr311-api-1.1.1.jar
mysql-connector-java-5.0.3-bin.jar servlet3-api.jar
xercesImpl.jar xml-apis.jar

Classe Curso:

package entity;

public class Curso {

	private Integer  idCurso;
	private String   nomeCurso;
	private Double   preco;
	private Boolean  promocao;

	public Curso() {

	}

	public Curso(Integer idCurso, String nomeCurso, Double preco, Boolean promocao) {
		super();
		this.idCurso = idCurso;
		this.nomeCurso = nomeCurso;
		this.preco = preco;
		this.promocao = promocao;
	}

	public Integer getIdCurso() {
		return idCurso;
	}
	public void setIdCurso(Integer idCurso) {
		this.idCurso = idCurso;
	}
	public String getNomeCurso() {
		return nomeCurso;
	}
	public void setNomeCurso(String nomeCurso) {
		this.nomeCurso = nomeCurso;
	}
	public Double getPreco() {
		return preco;
	}

	public void setPreco(Double preco) {
		this.preco = preco;
	}
	public Boolean getPromocao() {
		return promocao;
	}
	public void setPromocao(Boolean promocao) {
		this.promocao = promocao;
	}
}    

Script:

drop database if exists ws;
create database ws;

use ws;

 create table curso    (idCurso int primary key auto_increment,
        nomeCurso varchar (35),
        preco double,
        promocao int);
                     
 
    insert into curso  values (null,'webdeveloper',2900,     1);
    insert into curso  values (null,'mini-curso Maven',100,  1);
    insert into curso  values (null,'curso plsql 32',500,  1);
    insert into curso  values (null,'mini curso JBOSS',100,  1);
    
    commit;
    
    select * from curso;    

Resultado no banco...

DAO:

package persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Dao {

	Connection con;
	PreparedStatement stmt;
	ResultSet rs;
	
	public void open() throws Exception{
	   Class.forName("com.mysql.jdbc.Driver");
	   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webservice","root","coti");
	}
	
	public void close() throws Exception{
		con.close();
	}
}    

Classe CursoDao:

package persistence;

import java.util.ArrayList;
import java.util.List;
import entity.Curso;

public class CursoDao  extends Dao{
	
	public void create(Curso c)throws Exception{
	  open();
	    stmt = con.prepareStatement("insert into curso values (null,?,?,?) ");
	      stmt.setString(1, c.getNomeCurso());
	      stmt.setDouble(2, c.getPreco());
	      stmt.setInt(3 , (c.getPromocao()==true)? 1 : 0 );
 	         stmt.execute();
	         stmt.close();
	  close();
	}
		

	public List findAll() throws Exception{
		open();
		 stmt = con.prepareStatement("select * from curso");
		 List lst = new ArrayList();
		   rs = stmt.executeQuery();
		   while(rs.next()){
	       Curso c= new Curso(rs.getInt(1),
	    		              rs.getString(2), rs.getDouble(3), 
          new Boolean ( (rs.getInt(4)==1)?  "true" : "false") );
	        lst.add(c);
		   }
		close();
		return lst;
	}
}    

Classe WSCurso:

package webserviceserver;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import persistence.CursoDao;
import com.google.gson.Gson;
import entity.Curso;

@Path("/curso")
public class WSCurso {
	
	@Path("/listarTodosCursos")
	@GET
	@Produces
	 public String listarTodosCursos(){
		 try{
		 return new Gson().toJson(new CursoDao().findAll());
		 }catch(Exception ex){
			 return ex.getMessage();
		 }
	 }
	
	
	@GET
	@Path("/gravar/{nomecurso}/{preco}/{promocao}")
	@Produces("text/plain")
	public String gravar(
			  @PathParam ("nomecurso") String nomecurso,
			  @PathParam ("preco")     String preco,
			  @PathParam ("promocao")  String promocao
			   ){
	 try{
   Curso c = new Curso(null, nomecurso, new Double(preco), new Boolean(promocao));
       new CursoDao().create(c);
       return "Dados Gravados";
		}catch(Exception ex){
       return ex.getMessage();    
		}
	}
}    

Rodando pelo projeto...

Passando a url...

Gravado...

Para listar passar a URL...

CRIAR UM NOVO PROJETO - CLIENT...

As libs usadas no do Projeto foram:

asm-3.1.jar commons-beanutils-1.8.0.jar commons-codec-1.6.jar
commons-collections-3.2.1.jar commons-digester-2.0.jar commons-logging-1.1.1.jar
fluent-hc-4.2.5.jar gson-2.2.4.jar httpclient-4.2.5.jar
httpclient-cache-4.2.5.jar httpcore-4.2.4.jar httpmime-4.2.5.jar
jackson-core-asl-1.9.2.jar jackson-jaxrs-1.9.2.jar jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar javax.faces-2.0.11.jar jaxen-1.1.6.jar
jdom-2.0.5.jar jersey-client-1.12.jar jersey-core-1.12.jar
jersey-json-1.12.jar jersey-server-1.12.jar jersey-servlet-1.12.jar
jettison-1.1.jar jsr311-api-1.1.1.jar jstl.jar
mysql-connector-java-5.0.3-bin.jar primefaces-5.0-sources.jar primefaces-5.0.jar
servlet3-api.jar standard.jar xercesImpl.jar
xml-apis.jar

Classe Curso:

package entity;

public class Curso {

	private Integer  idCurso;
	private String   nomeCurso;
	private Double   preco;
	private Boolean  promocao;

	public Curso() {
	}

	public Curso(Integer idCurso, String nomeCurso, Double preco, Boolean promocao) {
		super();
		this.idCurso = idCurso;
		this.nomeCurso = nomeCurso;
		this.preco = preco;
		this.promocao = promocao;
	}

	public Integer getIdCurso() {
		return idCurso;
	}
	public void setIdCurso(Integer idCurso) {
		this.idCurso = idCurso;
	}
	public String getNomeCurso() {
		return nomeCurso;
	}
	public void setNomeCurso(String nomeCurso) {
		this.nomeCurso = nomeCurso;
	}
	public Double getPreco() {
		return preco;
	}
	public void setPreco(Double preco) {
		this.preco = preco;
	}
	public Boolean getPromocao() {
		return promocao;
	}
	public void setPromocao(Boolean promocao) {
		this.promocao = promocao;
	}

	@Override
	public String toString() {
		return "Curso [idCurso=" + idCurso + ", nomeCurso=" + nomeCurso + ", preco=" + preco + ", promocao=" + promocao + "]";
	}
}    

Classe ManagerBean:

package manager;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import com.sun.jersey.api.client.Client; //webService
import com.sun.jersey.api.client.WebResource;
import entity.Curso;

@ManagedBean(name="mb")
@RequestScoped
public class ManagerBean {

	private Curso curso;
	
	public ManagerBean() {

	}

	@PostConstruct
	public void init(){
	    curso = new Curso();		
	}
	

	public Curso getCurso() {
		return curso;
	}

	public void setCurso(Curso curso) {
		this.curso = curso;
	}

PASSAR A SUA URL
	
    public void gravar(){
    	String msg="";
    	FacesContext fc = FacesContext.getCurrentInstance();
    	try{
    	   Client c = Client.create();
    	    WebResource resource=
c.resource("http://localhost:8082/projetoServiceServer2/webservice/curso/gravar/" 
 + curso.getNomeCurso() + "/" + curso.getPreco() + "/" + curso.getPromocao()	   );
    	    String resposta = resource.get(String.class); //ele captura o retorno do m�todo
    	    curso = new Curso();
    	    msg = resposta;
    	}catch(Exception ex){
    		msg = "Error :" + ex.getMessage();
    	}
    	 fc.addMessage("form1", new FacesMessage(msg));
    }
}    

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Aula23_clientWebServer</display-name>
  
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  
</web-app>    

index.jsp

<%   
 response.sendRedirect("sistema.jsf");
%>    

sistema.xhtml

<!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:p="http://primefaces.org/ui"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">

 <h:head>
 </h:head>

 <h:body>
 <p:panel header="Gravar os Dados no Sistema WebService">
  <h:form id="form1">
    <p:panelGrid columns="2">
         <h:outputText value="Nome do Curso" />
         <p:inputText value="#{mb.curso.nomeCurso}" />
      
         <h:outputText value="Preco" />
         <p:inputText value="#{mb.curso.preco}" />
         
         <h:outputText value="Promocao" />
         <p:selectOneMenu value="#{mb.curso.promocao}">
           <f:selectItem itemLabel="true"   itemValue="1"></f:selectItem>
           <f:selectItem itemLabel="false"  itemValue="0"></f:selectItem>
       </p:selectOneMenu>
         
         <p:commandButton   value="Gravar"
                            action="#{mb.gravar}"
                            update=":form1"
                            ajax="true"
                            >
                            </p:commandButton>

    </p:panelGrid>
    <p:messages></p:messages>
   </h:form>
  </p:panel>
 </h:body>
</html>    

Rodando o sistema...