<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sylverio &#187; PHP</title>
	<atom:link href="http://sylverio.com.br/blog/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://sylverio.com.br/blog</link>
	<description>Análise, Arquitetura, Orientação a Objetos, UML, Tecnologias e Programação</description>
	<lastBuildDate>Fri, 11 May 2012 02:35:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Introdução ao Ajax</title>
		<link>http://sylverio.com.br/blog/2009/10/introducao-ao-ajax/</link>
		<comments>http://sylverio.com.br/blog/2009/10/introducao-ao-ajax/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 01:13:58 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Tecnologia]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=254</guid>
		<description><![CDATA[O problema que o Ajax tenta resolver está enraizado no protocolo de comunicação HTTP. Isso porque esse protocolo é sem estado (stateless), assim o controle das ações executadas na aplicação cliente é controlado pelo código no servidor web. Ou seja, &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2009/10/introducao-ao-ajax/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>O problema que o Ajax tenta resolver está enraizado no protocolo de comunicação HTTP. Isso porque esse protocolo é sem estado (stateless), assim o controle das ações executadas na aplicação cliente é controlado pelo código no servidor web. Ou seja, as alterações (ou entrada de dados) executadas na página web pelo usuário são enviadas para o servidor para que este atualize seu estado, e o servidor responde a alteração reenviado todo o HTML para o browser.</p>
<p><img style="float:right" src="image/Ajax_TriplaAcao.png" alt="Ajax"><br />
<strong>Mas o que é o Ajax?</strong></p>
<p>Ajax é o acrônimo (da língua inglesa) de <em>Asynchronous Javascript and XML</em>, ele não é uma linguagem de programação e sim a combinação de tecnologias existentes (<em>Javascript</em>, <em>XML</em> e <em>XmlHttpRequest</em>) que nos permite realizar solicitações assíncronas ao servidor para busca de informações e/ou atualizar seu estado.<br />
Em outras palavras o Ajax, é um objeto presente nos browser atuais que combinado com JavaScript pode se comunicar com o servidor Web sem recarregar e redesenhar a página inteira.</p>
<p><strong>Utilizando do Ajax</strong></p>
<p>O exemplo abaixo apresenta uma página chamada calcProduto.html, onde o usuário escolhe o tipo de produto e informa a quantidade de  produto que gostaria de adquir. Ao clicar no botão calcular, é realizado via ajax uma requisição ao servidor web (arquivo calcProduto.php) que realiza o calculo necessário e sua reposta é renderizada sem recarregar a página html.</p>
<p>Abaixo o código do arquivo calcProduto.html:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>html<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>head<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>title<span style="color: #339933;">&gt;</span>Produto<span style="color: #339933;">&lt;/</span>title<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>script language<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;javascript&quot;</span> type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span><span style="color: #339933;">&gt;</span>
&nbsp;
            <span style="color: #003366; font-weight: bold;">var</span> request <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #006600; font-style: italic;">// função que cria objeto de requisição</span>
            <span style="color: #003366; font-weight: bold;">function</span> createRequest <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #006600; font-style: italic;">// cria objeto XmlHttpRequest para os browser Firefox, Safari, Opera</span>
                    request <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> XMLHttpRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span> trymicrosoft <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #000066; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #006600; font-style: italic;">// cria objeto XmlHttpRequest para o browser IE</span>
                        request <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> ActiveXObject<span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;Msxm12.XMLHTTP&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span> othermicrosoft <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">try</span><span style="color: #009900;">&#123;</span>
                            <span style="color: #006600; font-style: italic;">// cria objeto XmlHttpRequest para o browser IE</span>
                            request <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> ActiveXObject<span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;Microsoft.XMLHTTP&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span> failed <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                            request <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
                        <span style="color: #009900;">&#125;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> request <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;Erro ao criar objeto Request!&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            <span style="color: #006600; font-style: italic;">// função que executa chamada ao servidor para realizar o calculo</span>
            <span style="color: #003366; font-weight: bold;">function</span> getPrice <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
                createRequest <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
                <span style="color: #003366; font-weight: bold;">var</span> prod <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;produto&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
                <span style="color: #003366; font-weight: bold;">var</span> qtd <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;quantidade&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
                <span style="color: #003366; font-weight: bold;">var</span> url <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;calcProduto.php?produto=&quot;</span> <span style="color: #339933;">+</span> prod <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;&amp;quantidade=&quot;</span> <span style="color: #339933;">+</span> qtd<span style="color: #339933;">;</span>
&nbsp;
                request.<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;GET&quot;</span><span style="color: #339933;">,</span> url<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                request.<span style="color: #660066;">onreadystatechange</span> <span style="color: #339933;">=</span> updatePage<span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// define função a ser chamada a obter resposta do servidor web</span>
                request.<span style="color: #660066;">send</span><span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// null informa que não está sendo enviado nenhum dado na requisição</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            <span style="color: #006600; font-style: italic;">// função chamada ao obter retorno da requisição e atualiza interface</span>
            <span style="color: #003366; font-weight: bold;">function</span> updatePage <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
                <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> request.<span style="color: #660066;">readyState</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">4</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> request.<span style="color: #000066;">status</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">200</span> <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
                        <span style="color: #003366; font-weight: bold;">var</span> resultado <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;resultado&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        resultado.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> request.<span style="color: #660066;">responseText</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                    <span style="color: #000066; font-weight: bold;">else</span><span style="color: #009900;">&#123;</span>
                        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">&quot;Erro: não foi possível obter resposta do servidor.&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>head<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;</span>body<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>h1<span style="color: #339933;">&gt;</span>Calculo de produto<span style="color: #339933;">&lt;/</span>h1<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>p<span style="color: #339933;">&gt;</span> Escolha um produto e informe a quantidade.<span style="color: #339933;">&lt;/</span>p<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>form method<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;GET&quot;</span> action<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;calcProduto.php&quot;</span><span style="color: #339933;">&gt;</span>
            <span style="color: #339933;">&lt;</span>p<span style="color: #339933;">&gt;</span> Produto<span style="color: #339933;">:</span> 
                <span style="color: #339933;">&lt;</span>select <span style="color: #000066;">name</span><span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;produto&quot;</span> id<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;produto&quot;</span><span style="color: #339933;">&gt;</span>
                    <span style="color: #339933;">&lt;</span>option value<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;0&quot;</span><span style="color: #339933;">&gt;</span>Caneta<span style="color: #339933;">&lt;/</span>option<span style="color: #339933;">&gt;</span>
                    <span style="color: #339933;">&lt;</span>option value<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;1&quot;</span><span style="color: #339933;">&gt;</span>Borracha<span style="color: #339933;">&lt;/</span>option<span style="color: #339933;">&gt;</span>
                    <span style="color: #339933;">&lt;</span>option value<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;2&quot;</span><span style="color: #339933;">&gt;</span>Giz<span style="color: #339933;">&lt;/</span>option<span style="color: #339933;">&gt;</span>
                    <span style="color: #339933;">&lt;</span>option value<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;3&quot;</span><span style="color: #339933;">&gt;</span>Apagador<span style="color: #339933;">&lt;/</span>option<span style="color: #339933;">&gt;</span>
                <span style="color: #339933;">&lt;/</span>select<span style="color: #339933;">&gt;</span>
            <span style="color: #339933;">&lt;/</span>p<span style="color: #339933;">&gt;</span>htm
            <span style="color: #339933;">&lt;</span>p<span style="color: #339933;">&gt;</span> Quantidade <span style="color: #339933;">&lt;</span>input type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text&quot;</span> <span style="color: #000066;">name</span><span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;quantidade&quot;</span> id<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;quantidade&quot;</span><span style="color: #339933;">&gt;&lt;/</span>p<span style="color: #339933;">&gt;</span>
            <span style="color: #339933;">&lt;</span>p<span style="color: #339933;">&gt;&lt;</span>input type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;button&quot;</span> value<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;Calcular&quot;</span> onClick<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;getPrice();&quot;</span><span style="color: #339933;">&gt;&lt;/</span>p<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;/</span>form<span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;</span>div id<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;resultado&quot;</span><span style="color: #339933;">&gt;</span>
        <span style="color: #339933;">&lt;/</span>div<span style="color: #339933;">&gt;</span>
    <span style="color: #339933;">&lt;/</span>body<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>html<span style="color: #339933;">&gt;</span></pre></div></div>

<p>O código utilizado no servidor web:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
    <span style="color: #000088;">$produto</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_REQUEST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'produto'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$qtd</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_REQUEST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'quantidade'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$prodName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$vlr</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$produto</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;0&quot;</span><span style="color: #339933;">:</span>
            <span style="color: #000088;">$prodName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Caneta'</span><span style="color: #339933;">;</span>
            <span style="color: #000088;">$vlr</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'1'</span><span style="color: #339933;">:</span>
            <span style="color: #000088;">$prodName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Borracha'</span><span style="color: #339933;">;</span>
            <span style="color: #000088;">$vlr</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'2'</span><span style="color: #339933;">:</span>
            <span style="color: #000088;">$prodName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Giz'</span><span style="color: #339933;">;</span>
            <span style="color: #000088;">$vlr</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'3'</span><span style="color: #339933;">:</span>
            <span style="color: #000088;">$prodName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Apagador'</span><span style="color: #339933;">;</span>
            <span style="color: #000088;">$vlr</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">4</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000088;">$total</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$qtd</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$vlr</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;h3&gt;Calculo:&lt;/h3&gt;
&lt;table  border=1 &gt;
    &lt;tr&gt;
        &lt;td&gt;Produto&lt;/td&gt;
        &lt;td&gt;Quantida&lt;/td&gt;
        &lt;td&gt;Valor unidade&lt;/td&gt;
        &lt;td&gt;Total&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">print</span> <span style="color: #000088;">$prodName</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/td&gt;
        &lt;td&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">print</span> <span style="color: #000088;">$qtd</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/td&gt;
        &lt;td&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;R$ &quot;</span> <span style="color: #339933;">.</span><span style="color: #990000;">number_format</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$vlr</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">','</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/td&gt;
        &lt;td&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;R$ &quot;</span> <span style="color: #339933;">.</span><span style="color: #990000;">number_format</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$total</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">','</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;</pre></div></div>

<p>Futuramente falarei um pouco mais sobre o componente XmlHttpRequest e seus recursos.<br />
Enjoy <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/10/introducao-ao-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Requisição HTTP com Java Application Parte 2</title>
		<link>http://sylverio.com.br/blog/2009/09/requisicao-http-com-java-application-parte-2/</link>
		<comments>http://sylverio.com.br/blog/2009/09/requisicao-http-com-java-application-parte-2/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 03:17:27 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=231</guid>
		<description><![CDATA[Olá pessoal, No post anterior Requisição HTTP com Java Application Parte 1 , falei um pouco sobre como obter o conteúdo de uma página web. Mas nem sempre somente o conteúdo de uma página nos interessa. Na maioria das vezes &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2009/09/requisicao-http-com-java-application-parte-2/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Olá pessoal,</p>
<p>No post anterior <a href="http://sylverio.com.br/blog/?p=197">Requisição HTTP com Java Application Parte 1</a> , falei um pouco sobre como obter o conteúdo de uma página web. Mas nem sempre somente o conteúdo de uma página nos interessa.<br />
Na maioria das vezes necessitamos que de uma interação com a página (ou páginas) por meio de troca de informação, ou seja, enviamos dados, a página processa os dados e nos retorna a informação.</p>
<p>Para isso iremos trabalhar com o objeto <em>URLConnection</em>, objeto existente no pacote <strong>java.net</strong>.<br />
Veja o exemplo abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">teste.communication</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.BufferedReader</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.IOException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.InputStreamReader</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.OutputStreamWriter</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.MalformedURLException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.URL</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.URLConnection</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.URLEncoder</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TesteComunicacao <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> 
			<span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">MalformedURLException</span>, <span style="color: #003399;">IOException</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">try</span><span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">// monta estrutura de parametros a serem eviados</span>
			<span style="color: #003399;">String</span> data <span style="color: #339933;">=</span> <span style="color: #003399;">URLEncoder</span>.<span style="color: #006633;">encode</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;nome&quot;</span>, <span style="color: #0000ff;">&quot;UTF-8&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;=&quot;</span> <span style="color: #339933;">+</span> <span style="color: #003399;">URLEncoder</span>.<span style="color: #006633;">encode</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;Fernando&quot;</span>, <span style="color: #0000ff;">&quot;UTF-8&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		         <span style="color: #003399;">URL</span> url <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">URL</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;http://localhost/get_name.php&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	                 <span style="color: #003399;">URLConnection</span> urlConnection <span style="color: #339933;">=</span> url.<span style="color: #006633;">openConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	                 <span style="color: #666666; font-style: italic;">// envia dados</span>
	                 urlConnection.<span style="color: #006633;">setDoOutput</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	                 <span style="color: #003399;">OutputStreamWriter</span> outputWriter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">OutputStreamWriter</span><span style="color: #009900;">&#40;</span>urlConnection.<span style="color: #006633;">getOutputStream</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	                 outputWriter.<span style="color: #006633;">write</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	                 outputWriter.<span style="color: #006633;">flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	                 <span style="color: #666666; font-style: italic;">// Obtem as respostas</span>
	                 <span style="color: #003399;">InputStreamReader</span> inputReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InputStreamReader</span><span style="color: #009900;">&#40;</span>urlConnection.<span style="color: #006633;">getInputStream</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	                 <span style="color: #003399;">BufferedReader</span> bufferedReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BufferedReader</span><span style="color: #009900;">&#40;</span> inputReader <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>** retorno da página web **&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #003399;">String</span> linha <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span>linha <span style="color: #339933;">=</span> bufferedReader.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>linha<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span> e.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Após instânciar o objeto <em>URL</em>, podemos obter o objeto <em>URLConnection</em> através do seu método <em>openConnection</em>.<br />
O método <em>urlConnection.setDoOutput(true); </em> é executado para informar que será enviado parâmetros.<br />
Depois obtemos o stream de saída e enviamos os dados (obs: esses dados são enviados via método POST).<br />
O retorno é obtido através do método <em>urlConnection.getInputStream</em> que é tratado por meio do objeto <em>InputStreamReader</em>.</p>
<p>Para simular o processamento dos dados enviados gerei um arquivo PHP com o seguinte código:</p>
<p><code><br />
&lt;?php<br />
    $response = $_POST['nome'];</p>
<p>    echo "Conteúdo recebido: ";<br />
    echo $response;<br />
?&gt;<br />
</code></p>
<p>Ele simplesmente lê o dado recebido e gera uma resposta apartir das informações obtidas.</p>
<p>Enjoy<br />
 <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_cool.gif' alt='8-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/09/requisicao-http-com-java-application-parte-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introdução ao CakePHP</title>
		<link>http://sylverio.com.br/blog/2009/08/introducao-ao-cakephp/</link>
		<comments>http://sylverio.com.br/blog/2009/08/introducao-ao-cakephp/#comments</comments>
		<pubDate>Sun, 23 Aug 2009 20:58:48 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=213</guid>
		<description><![CDATA[Uma breve introdução ao CakePHP<p class="read-more"><a href="http://sylverio.com.br/blog/2009/08/introducao-ao-cakephp/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>CakePHP é um framework escrito em PHP, que possibilita o desenvolvimento de aplicações (PHP) web robustas rapidamente sem perder flexibilidade.<br />
O CakePHP é Open Source e fornece uma arquitetura extensível para desenvolvimento, manutenção, e distribuição de aplicações por meio de patterns conhecidos como ActiveRecord, Association Data Mapping, Front Controller, MVC (Model-View-Controller) e ORM.</p>
<h3>Entendendo o MVC</h3>
<p>O CakePHP segue o design pattern MVC, que separa sua aplicação em três camadas principais?<br />
1. <strong>Model</strong> representa os dados da aplicação.<br />
2. <strong>View</strong> representa o modelo de apresentação dos dados.<br />
3. <strong>Controller</strong> recebe e encaminha requisições feitas pelo cliente.</p>
<p><img src="http://sylverio.com.br/blog/image/mvc-cake.png" alt="Cake MVC" /></p>
<p>1.Cliente (browser) faz requisição para o servidor web;<br />
2.O expedidor (dispacher) verifica a URL e encaminha a requisição para o controller correto.<br />
3.O controller realiza a específica lógica da aplicação.<br />
4.O controller utiliza o model para se ter acesso aos dados da aplicação.<br />
5.Depois os dados o controller os encaminha para view. A view pega os dados e os prepara no formato de apresentação específico para o cliente.<br />
6.Uma vez criado a apresentação, este é retornado para o browser.</p>
<h3>Observação: </h3>
<ul>
<li>A camada de Model representa os dados da aplicação, não é representação de um banco de dados ou entidades da aplicação, ela poderia estar acessando um WebService, por exemplo, para obter os dados da aplicação, isolando assim a camada de apresentação com a camada de negócio.</li>
<li>Usualmente as views no CakePHP são no formato HTML, mas podem ser PDF, XML, JSON, isso depende mais qual será o propósito de sua utilização.</li>
</ul>
<h3>Estrutura do CakePHP</h3>
<p>Alem das classes de Model, View e Controller o CakePHP também possui algumas características como classes de Components, Behaviors e Helpers que auxiliam o desenvolvimento.</p>
<p><strong>Controller</strong> – são equipados com callbacks, que possibilita inserir operações no núcleo do CakePHP;<br />
<strong>Component</strong> 	– compartilha a lógica entre controllers;<br />
<strong>Helper</strong> 	– compartilha a lógica entre as views;<br />
<strong>Behaviors</strong> 	– adiciona funcionalidade entre models;<br />
<strong>DataSources</strong> 	– abstrações que permitem os models manipularem diferentes tipos de dados consistente; </p>
<h3>Convenções</h3>
<p>O CakePHP possui já um <a href="http://sylverio.com.br/blog/?p=159">estilo de programação</a> que pode ser acompanhado em <a href="http://book.cakephp.org/view/22/CakePHP-Conventions Conveções" target="_blanck">book.cakephp.org</a></p>
<p>Segue uma lista básica de estilo:</p>
<table>
<tr>
<td style="width: 140px;"><strong>nomes de arquivo</strong></td>
<td>devem ser sublinhados;</td>
</tr>
<tr>
<td style="width: 140px;"><strong>nome de classes</strong></td>
<td>devem ser CamelCase;</td>
</tr>
<tr>
<td style="width: 140px;"><strong>nome de controller</strong></td>
<td>devem estar no plural  e ser CamelCase;</td>
</tr>
<tr>
     </tr>
<tr>
<td style="width: 140px;"></td>
<td>deve ter uma função chamada índex();</td>
</tr>
<tr>
     </tr>
<tr>
<td style="width: 140px;"></td>
<td>colocando um sublinhado na frente da função ela será disponível somente para uso interno, não ficando disponível para web por meio do dispatcher.</td>
</tr>
<tr>
      </tr>
<tr>
<td style="width: 140px;"><strong>nome de models</strong></td>
<td>devem ser no singular e ser CamelCase;</td>
</tr>
<tr>
      </tr>
<tr>
<td style="width: 140px;"><strong>nome de URL</strong></td>
<td>o nome dos controller devem ser no plural e lowerCamelCase, porem curtos. Exemplo: RedCarsController ficaria redCars;</td>
</tr>
<tr>
</tr>
</table>
<h3>Referências</h3>
<p><a href="http://www.cakephp.org" target="_blanck">The Official CakePHP website</a><br />
<a href="http://book.cakephp.org" target="_blanck">The Cookbook</a><br />
<a href="http://pt.wikipedia.org/wiki/CakePHP" target="_blanck">Wikipedia</a></p>
<p>Até mais <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/08/introducao-ao-cakephp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introdução ao PHP</title>
		<link>http://sylverio.com.br/blog/2009/08/introducao-ao-php/</link>
		<comments>http://sylverio.com.br/blog/2009/08/introducao-ao-php/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 01:56:01 +0000</pubDate>
		<dc:creator>Carlos Fernando Sylverio</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://sylverio.com.br/blog/?p=190</guid>
		<description><![CDATA[PHP é uma linguagem de script Open Source de uso geral, muito utilizada para aplicações Web. Suas principais características são: Criação de aplicações dinâmicas; Código PHP é executado do lado servidor; Interação com banco de dados sem exposição de código &#8230;<p class="read-more"><a href="http://sylverio.com.br/blog/2009/08/introducao-ao-php/">Saiba mais &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>PHP é uma linguagem de script Open Source de uso geral, muito utilizada para aplicações Web.</p>
<p><img style="float:right" src="http://sylverio.com.br/blog/image/php-logo.jpg" alt="Logo PHP" /></p>
<p>Suas principais características são:</p>
<ul>
<li>Criação de aplicações dinâmicas;</li>
<li>Código PHP é executado do lado servidor;</li>
<li>Interação com banco de dados sem exposição de código para o cliente;</li>
<li>Possibilidade de embutir código dentro do HTML;</li>
<li>Arquivos PHP são tipos texto (ASCII) e podem ser escritos em qualquer editor de texto;</li>
<li>Compatibilidade com diversos Sistemas Operacionais (Windows, Linux, Unix, Mac OS, e outros);</li>
<li>Suportado por diversos servidores Web (Apache, IIS, e outros), podendo ser configurado como módulo ou como um CGI comum.</li>
</ul>
<h3>O que pode ser feito?</h3>
<p>Basicamente, qualquer coisa como criar e coletar dados de um formulário, gerar páginas dinâmicas ou enviar e receber cookies.<br />
Segue um link para o <a href="http://www.php.net/manual/pt_BR/index.php" target="_blanck">manual web do PHP</a>. Nele há um suporte desde a sintaxe básica do PHP até a instalação e configuração de um servidor PHP.</p>
<h3>Referência</h3>
<p><a href="http://www.php.net/manual/pt_BR/index.php" target="_blanck">Manual PHP</a><br />
Beginning PHP5 and MySQL5, W Jason Gilmore</p>
<p>Até mais <img src='http://sylverio.com.br/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sylverio.com.br/blog/2009/08/introducao-ao-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

