HTTPPostServlet

11 respostas
R

Estou iniciando em Servlets e, ao tentar compilar o arquivo abaixo utilizando o servlet.jar do tomcat4, surgiram 29 erros. Alguém pode me ajudar?

// HTTPPostServlet.java

import javax.servlet.<em>;

import javax.servlet.http.</em>;

import java.text.<em>;

import <a href="http://java.io">java.io</a>.</em>;

import java.util.*;
public class HTTPPostServlet extends HttpServlet {

private String animalNames[] =

{ cachorro, gato, pássaro, cobra, nenhum };
public void doPost ( HttpServletRequest request,
					 HttpServletResponse response )
	throws ServletException, IOException
}
	int animals[] = null, total = 0;
	File f = new File ( "survey.txt" );

if ( f.exists() ) {
	//Determina nº de resposta da pesquisa até agora
	try {
		ObjectInputStream input = new ObjectInputStream(
			new FileInputStream ( f ) );

		animals = (int []) input.readObject();
		input.close();	// fecha o fluxo

		for ( int i = 0; i &lt; animals.length ; ++i )
			total += animals [ i ];
	}
	catch ( ClassNotFoundException cnfe )	{
		cnfe.printStackTrace();
	}
}
else
	animals = new int [ 5 ];

	//lê a resposta da pesquisa atual
	String value =
		request.getParameter( "animal" );
		++total;	//atualiza o total de todas as respostas

	//determina qual foi selecionado e atualiza seu total
	for ( int i = 0 ; i &lt; animalNames.length ; ++i )
		if ( value.equals( animalNames[ i ] ) )
			++animals[ i ];

	//grava os totais atualizados em disco
	ObjectOutputStream output = new ObjectOutputStream(
		new FileOutputStream( f ) );

	output.writeObject( animals );
	output.flush();
	output.close();

	//calcula as porcentagens
	double percentages[] = new double[ animals.length ];

	for ( int i = 0 ; i &lt; percentages.length ; ++i )
		percentages[ i ] = 100.0 * animals[ i ] / total;
	
	//envia uma mensagem de agradecimento para o cliente
	response.setContentType( "text/html" );	//tipo de conteúdo

	PrintWriter responseOutput = response.getWriter();
	StringBuffer buf = new StrinBuffer();
	buf.append( "&lt;html&gt;
" );

buf.append( "<title>Agradecimento!</title>

" );

buf.append( "Obrigado por sua participação.

" );

buf.append( <BR>Resultados:

<PRE> );
DecimalFormat twoDigits = new DecimalFormal( "#0.00" );
	for ( int i = 0; i &lt; percentages.length ; ++i ) {
		buf.append( "&lt;BR&gt;" );
		buf.append( animalNames[ i ] );
		buf.append( ": " );
		buf.append( twoDigits.format( percentages[ i ] ) );
		buf.append( "% respostas: " );
		buf.append( animals[ i ] );
		buf.append( "

" );
}

buf.append( "
<BR><BR>Total de respostas: " );

buf.append( total );

buf.append( </PRE>

</html> );
responseOutput.println( buf.toString() );
	responseOutput.close();
}

}

Obrigado!

11 Respostas

C

Quais foram os erros reportados colega?

R

Eis os erros reportados:

C: javac -classpath c: omcat4commonlibservlet.jar HTTPPostServlet.java

HTTPPostServlet.java:15: ; expected

throws ServletException, IOException

^

HTTPPostServlet.java:17: class or interface expected

int animals[] = null, total = 0;

^

HTTPPostServlet.java:18: class or interface expected

File f = new File ( survey.txt );

^

HTTPPostServlet.java:20: class or interface expected

if ( f.exists() ) {

^

HTTPPostServlet.java:40: class or interface expected

String value =

^

HTTPPostServlet.java:42: class or interface expected

++total;        //atualiza o total de todas as respostas
^

HTTPPostServlet.java:45: ‘class’ or ‘interface’ expected
++total; //atualiza o total de todas as respostas

^
HTTPPostServlet.java:50: class or interface expected

ObjectOutputStream output = new ObjectOutputStream(

^

HTTPPostServlet.java:53: class or interface expected

output.writeObject( animals );

^

HTTPPostServlet.java:54: class or interface expected

output.flush();

^

HTTPPostServlet.java:55: class or interface expected

output.close();

^

HTTPPostServlet.java:58: class or interface expected

double percentages[] = new double[ animals.length ];

^

HTTPPostServlet.java:60: class or interface expected

for ( int i = 0 ; i < percentages.length ; ++i )

^

HTTPPostServlet.java:64: class or interface expected

response.setContentType( text/html ); //tipo de conte·do

^

HTTPPostServlet.java:66: class or interface expected

PrintWriter responseOutput = response.getWriter();

^

HTTPPostServlet.java:67: class or interface expected

StringBuffer buf = new StrinBuffer();

^

HTTPPostServlet.java:68: class or interface expected

buf.append( "<html>

" );

^

HTTPPostServlet.java:69: class or interface expected

buf.append( "<title>Agradecimento!</title>

" );

^

HTTPPostServlet.java:70: class or interface expected

buf.append( "Obrigado por sua participaþÒo.

" );

^

HTTPPostServlet.java:71: class or interface expected

buf.append( <BR>Resultados:

<PRE> );

^

HTTPPostServlet.java:73: class or interface expected

DecimalFormat twoDigits = new DecimalFormal( #0.00 );

^

HTTPPostServlet.java:74: class or interface expected

for ( int i = 0; i < percentages.length ; ++i ) {

^

HTTPPostServlet.java:85: class or interface expected

buf.append( total );

^

HTTPPostServlet.java:86: class or interface expected

buf.append( “</PRE>

</html>” );

^

HTTPPostServlet.java:88: class or interface expected

responseOutput.println( buf.toString() );

^

HTTPPostServlet.java:89: class or interface expected

responseOutput.close();

^

HTTPPostServlet.java:90: class or interface expected

}

^

HTTPPostServlet.java:92: class or interface expected

^
HTTPPostServlet.java:13: missing method body, or declare abstract
public void doPost ( HttpServletRequest request,
^
29 errors

J2Alex

Bem, pelo que percebi no seu código, acho que no seguinte trecho:

public void doPost &#40; HttpServletRequest request, HttpServletResponse response &#41; throws ServletException, IOException &#125;

Na verdade a chave } deveria ser {

Acho que isso deve resolver o seu problema…

R

:oops: Realmente cara, vc tem toda razão!
Compilei com a alteração e está praticamente resolvido… somente este pequeno erro nos digitos decimais e pronto… tem idéia de como resolver?

HTTPPostServlet.java:67: cannot resolve symbol

symbol  : class StrinBuffer

location: class HTTPPostServlet

StringBuffer buf = new StrinBuffer();

^

HTTPPostServlet.java:73: cannot resolve symbol

symbol  : class DecimalFormal

location: class HTTPPostServlet

DecimalFormat twoDigits = new DecimalFormal( #0.00 );

^

2 errors

Obrigadão!!!

aconstantino

Mude

StringBuffer buf = new StrinBuffer&#40;&#41;;

para

StringBuffer buf = new StringBuffer&#40;&#41;;

e em

DecimalFormat twoDigits = new DecimalFormal&#40; &quot;#0.00&quot; &#41;;

coloque

DecimalFormat twoDigits = new DecimalFormat&#40; &quot;#0.00&quot; &#41;;

J2Alex

Tirou as palavras da minha boca dohko… :smiley:

Nada muito sério ramires, só toma cuidado com a digitação - em especial, atenção para maíusculas e mínusculas que podem geram erros um pouco difíceis de localizar.

aconstantino

Eu também quando estou meio distraído dou umas dessas, sorte que o eclipse não me deixa fazer isso :slight_smile:

R

Obrigadão pessoal!

Estou gostando muito deste GUJ, pois aqui dá pra ver que o pessoal realmente se importa e ajuda aqueles que estão começando.

Já abusando da boa vontade de vocês, vejam se podem me ajudar nesta outra questão:

Só estou conseguindo compilar meus arquivos .java dentro da pasta BIN do J2SDK, meu AUTOEXEC.BAT está configurado da seguinte maneira:

SET JAVA_HOME=C:j2sdk1.4.0_03
SET PATH=%PATH%;%JAVA_HOME%in;C:ARQUIV~1IBMCLIENT~1;C:ARQUIV~1IBMCLIENT~1SHARED;C:ARQUIV~1IBMCLIENT~1EMULATOR
SET CLASSPATH=.;%JAVA_HOME%

Já tentei algumas variações, mas sem êxito …

Obrigado pela força!

Ramires

cadu

tentei rodar um servlet parecido com este:
entro com dados da pesquisa… ok
mas não retorna o resultado
será q é alguma configuração no web.xml
por q testei com um servlet mas simples e rodou…
e o q parece com esse, só rodou com fiz o deploy dele no diretório “examples”.

C

Olá Cadu,

Mande uma cópia do código que recebe os parametros para que todos possam dar uma olhada… provavelmente é algum erro simples…

Abraços!

R

Cadú, eu usei o arquivo web.xml abaixo e funcionou:

<?xml version=“1.0” encoding=“ISO-8859-1”?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>

&lt;servlet&gt;
    &lt;servlet-name&gt;HTTPPostServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;HTTPPostServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;HTTPPostServlet&lt;/servlet-name&gt; 
    &lt;url-pattern&gt;*.html&lt;/url-pattern&gt; 
&lt;/servlet-mapping&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;HTTPPostServlet&lt;/servlet-name&gt; 
    &lt;url-pattern&gt;/HTTPPostServlet&lt;/url-pattern&gt; 
&lt;/servlet-mapping&gt;

&lt;session-config&gt;
    &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;!-- 30 minutes --&gt;
&lt;/session-config&gt;

</web-app>

Valeu?

Criado 31 de janeiro de 2003
Ultima resposta 4 de fev. de 2003
Respostas 11
Participantes 5