Midlet + servlets + conexão com banco

2 respostas
hayase

pessoal
estou tendo o seguinte problema...
tenho uma midlet q acessa um banco através de uma servlet
bom.... é retornado na tela um erro de "removido temporariamente"

ai vão os códigos
este é do SERVLET
GetNpostServlet.java

import java.util.*; 
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.sql.*; 

public class GetNpostServlet extends HttpServlet 
{ 
   protected void doGET(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
   { 
      String acct = req.getParameter("account"), pwd = req.getParameter("password"); 
      String balance = accountLookup(acct, pwd); 
      if(balance == null) 
      { 
         res.sendError(res.SC_BAD_REQUEST, "Não foi possível localizar a conta..."); 
         return; 
      } 
      res.setContentType("text/plain"); 
      PrintWriter out = res.getWriter(); 
      out.print(balance); 
      out.close(); 
   } 
    
   protected void doPOST(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
   { 
      String acct = req.getParameter("account"), pwd = req.getParameter("password"); 
      String balance = accountLookup(acct, pwd); 
      if(balance == null) 
      { 
         res.sendError(res.SC_BAD_REQUEST, "Não foi possível localizar a conta..."); 
         return; 
      } 
      res.setContentType("text/plain"); 
      PrintWriter out = res.getWriter(); 
      out.print(balance); 
      out.close(); 
   } 
    
   private String accountLookup(String acct, String pwd) 
   { 
      Connection con = null; 
      Statement st = null; 
      StringBuffer msgb = new StringBuffer(""); 
      try 
      { 
         Class.forName("com.mysql.jdbc.Driver"); 
         con = DriverManager.getConnection("jdbc:mysql://localhost/banco?charSet=ISO8859-1", "sap", "cissa" ); 
         Statement stmt = con.createStatement(); 
         ResultSet rs = stmt.executeQuery("select balance from acctInfo where account = " + acct + " and password = '" + pwd + " ' "); 
         if(rs.next()) 
            return rs.getString(1); 
         else 
            return null; 
      } 
      catch(Exception e) 
      { 
         return e.toString(); 
      } 
   } 

   public String getServletInfo() 
   { 
      return "GetNpostServlet 1.0 - www.corej2me.com"; 
   } 
}

este é da midlet

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import javax.microedition.io.*; 
import java.io.*; 

public class GetNpost extends MIDlet implements CommandListener 
{ 
   private Display display; 
   private Form fmMain; 
   private Alert alError; 
   private Command cmGET; 
   private Command cmPOST; 
   private Command cmExit; 
   private TextField tfAcct; 
   private TextField tfPwd; 
   private StringItem siBalance; 
   private String errorMsg = null; 
    
   public GetNpost() 
   { 
      display = Display.getDisplay(this); 
      cmGET = new Command("GET", Command.SCREEN, 2); 
      cmPOST = new Command("POST", Command.SCREEN, 2); 
      cmExit = new Command("Sair", Command.EXIT, 1); 
      tfAcct = new TextField("Conta: ", "", 5, TextField.NUMERIC); 
      tfPwd = new TextField("Password: ", "", 10, TextField.ANY|TextField.PASSWORD); 
      siBalance = new StringItem("Saldo: $", ""); 
      fmMain = new Form("Informação da Conta"); 
      fmMain.addCommand(cmExit); 
      fmMain.addCommand(cmGET); 
      fmMain.addCommand(cmPOST); 
      fmMain.append(tfAcct); 
      fmMain.append(tfPwd); 
      fmMain.append(siBalance); 
      fmMain.setCommandListener(this); 
   } 

   public void startApp() 
   { 
      display.setCurrent(fmMain); 
   } 
    
   public void pauseApp( ) { } 
    
   public void destroyApp(boolean unconditional) { } 

   public void commandAction(Command c, Displayable s) 
   { 
      if (c == cmGET || c == cmPOST) 
      { 
         try 
         { 
            if(c == cmGET) 
               lookupBalance_withGET(); 
            else 
               lookupBalance_withPOST(); 
         } 
         catch (Exception e) 
         { 
            System.out.println("Msg: " + e.toString()); 
         } 
      } 
      else if(c == cmExit) 
      { 
         destroyApp(false); 
         notifyDestroyed(); 
      } 
   } 

   private void lookupBalance_withGET() throws IOException 
   { 
      Thread t = new Thread(new Runnable() 
      { 
         public void run() 
         { 
            HttpConnection http = null; 
            InputStream iStrm = null; 
            boolean ret = false; 
            String url = "endereço" + "?" + "account=" + tfAcct.getString() + "&" + "password=" + tfPwd.getString(); 
            try 
            { 
               http = (HttpConnection) Connector.open(url); 
               http.setRequestMethod(HttpConnection.GET); 
               iStrm = http.openInputStream(); 
               ret = processServerResponse(http, iStrm); 
            } 
            catch (IOException e){ e.printStackTrace(); } 
            finally 
            { 
               if(iStrm != null) 
                  try 
                  { 
                     iStrm.close(); 
                  } 
                  catch (IOException e) 
                  { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
                  } 
               if(http != null) 
                  try 
                  { 
                     http.close(); 
                  } 
                  catch (IOException e) 
                  { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
                  } 
            } 
            if(ret == false) 
               showAlert(errorMsg); 
         } 
      }); 
      t.start(); 
   } 

   private void lookupBalance_withPOST() throws IOException 
   { 
      Thread t = new Thread(new Runnable() 
      { 
         public void run() 
         { 
            HttpConnection http = null; 
            OutputStream oStrm = null; 
            InputStream iStrm = null; 
            boolean ret = false; 
            String url = "endereço"; 
            try 
            { 
               http = (HttpConnection) Connector.open(url); 
               oStrm = http.openOutputStream(); 
               http.setRequestMethod(HttpConnection.POST); 
               http.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); 
               http.setRequestProperty("Conexão", "close"); 
               byte data[] = ("account= " + tfAcct.getString()).getBytes(); 
               oStrm.write(data); 
               data = ("&password= " + tfPwd.getString()).getBytes(); 
               oStrm.write(data); 
               oStrm.flush(); 
               iStrm = http.openInputStream(); 
               ret = processServerResponse(http, iStrm); 
            } 
            catch (IOException e){ e.printStackTrace(); } 
            finally 
            { 
               if(iStrm != null) 
                  try 
                  { 
                     iStrm.close(); 
                  } 
                  catch (IOException e) 
                  { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
                  } 
               if(http != null) 
                  try 
                  { 
                     http.close(); 
                  } 
                  catch (IOException e) 
                  { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
                  } 
            } 
            if(ret == false) 
                  showAlert(errorMsg); 
         } 
      }); 
      t.start(); 
   } 

   private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException 
   { 
      errorMsg = null; 
      if(http.getResponseCode() == HttpConnection.HTTP_OK) 
      { 
         int length = (int) http.getLength(); 
         String str; 
         if(length != -1) 
         { 
            byte servletData[] = new byte[length]; 
            iStrm.read(servletData); 
            str = new String(servletData); 
         } 
         else 
         { 
            ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); 
            int ch; 
            while((ch = iStrm.read()) != -1) 
               bStrm.write(ch); 
            str = new String(bStrm.toByteArray()); 
            bStrm.close(); 
         } 
         siBalance.setText(str); 
         return true; 
      } 
      else 
         errorMsg = new String(http.getResponseMessage()); 
         return false; 
   } 

   private void showAlert(String msg) 
   { 
      alError = new Alert("Erro", msg, null, AlertType.ERROR); 
      alError.setTimeout(Alert.FOREVER); 
      display.setCurrent(alError, fmMain); 
   } 
}

por favor... apenas um detalhe... onde está escrito endereço, eu mesma escrevi isso... eu sei oq tem q por lá... hehehehe

agora o q acontece... qdo a midlet acessa a servlet um erro é retornado na tela do dispositivo móvel, um erro de que a página está removida temporariamente...

o q é isto?

tipo... estou usando jdk5, tomcat4....

em relação ao context do server.xml do tomcat.... estou tendo problemas tb... se adiciono um bloco lá o tomcat não roda.... se nao coloco nada o tomcat roda mas não encontra a minha pagina....não sei o q fazer....
alguém pode me dar uma idéia
até....

2 Respostas

DEAD

Amiga hayase se eu tiver um tempo postarei um código sobre isso. Não é difícil. Aconcelho vc utilizar um pouco o IDE NetBeans se vc quer focar mais na parte de programação e pouco na parte de configuração de servidores e esse tipo de coisas, o Tomcat vem embuido nele, e se vc tiver o Mobility Pack e uma conexão com um banco de dados já era vc conseguirá fazer isso sem problemas.
Não tive tempo de analizar seu código mas se der certo postarei algo lhe ajudando! até mais e se cuide!

hayase

[color=violet]obrigada
eu vou acaba fazendo isso mesmo
eu normalmente uso o eclipse
mas parece q o netbeans será mais produtivo pra mim neste momento…
obrigada mesmo assim ok :)[/color] :idea:

Criado 23 de agosto de 2007
Ultima resposta 27 de ago. de 2007
Respostas 2
Participantes 2