Conexão com Banco Midlet Servlet

23/08/2007

0

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.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); 

               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 

                  } 
            } 
            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é....
Cissagatto

Cissagatto

Responder

Que tal ter acesso a um e-book gratuito que vai te ajudar muito nesse momento decisivo?

Ver ebook

Recomendado pra quem ainda não iniciou o estudos.

Eu quero
Ver ebook

Recomendado para quem está passando por dificuldades nessa etapa inicial

Eu quero

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar