Witam,
Jestem w trakcie pisania programu, który ma za zadanie z telefonu komórkowego(midlet) komunikować się z servletem, który jest na serverze Tomcat 7.0, a zaś ten servlet ma komunikować się z bazą danych MySQL i wykonywać jakieś tam zapytania. Wzorowałem się na tym: http://j2mesamples.blogspot.com/2009/02/database-connection-using-j2me.html poradniku.
Ogólnie to ten midlet pobiera z formularza dane(nazwa bazy, login i hasło) i wysyła do servletu, który testuje połączenie z bazą danych i odpowiada na midlet. Kłopot pojawia się w momencie, kiedy chcę z formularza 'index' pobrać kolejne dane i też przesłać je do servletu(w którym docelowo miałby być składowymi zapytania sql). Próbowałem robić to w tym samym DataOutputStream, ale kiedy to robię dostaje na ekranie tylko informację '0'. Jeżeli tworze nowy DataOutputStream i próbuje wysłać, to wtedy dostaję info 'no more output streams available'.
Mógłby ktoś mi powiedzieć co robię źle, lub jak to poprawić?
Midlet:
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class MySQLConn extends MIDlet implements CommandListener {
private String username;
private String url = "http://localhost:8080/Servlet_1/getConnection";
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);;
private Command connect = new Command("Connect", Command.SCREEN, 1);
private Command send = new Command("Wyslij", Command.SCREEN, 1);
private Form menu;
private TextField tb;
private TextField tb1;
private TextField tb2;
private Form index;
private TextField idx1;
private TextField idx2;
DBConn db;
public MySQLConn() throws Exception {
display = Display.getDisplay(this);
}
public void startApp() {
displayMenu();
}
public void displayMenu() {
menu = new Form("Polaczenie");
tb = new TextField("Baza danych: ","javatest",30,TextField.ANY );
tb1 = new TextField("Uzytkownik: ","root",30,TextField.ANY);
tb2 = new TextField("Haslo: ","",30,TextField.PASSWORD);
menu.append(tb);
menu.append(tb1);
menu.append(tb2);
menu.addCommand(exit);
menu.addCommand(connect);
menu.setCommandListener(this);
display.setCurrent(menu);
}
public void displayIndex(){
index = new Form ("Index");
idx1 = new TextField("Nr. Indexu: ","",5,TextField.ANY);
idx2 = new TextField("Ocena: ","",1,TextField.ANY);
index.append(idx1);
index.append(idx2);
index.addCommand(send);
index.setCommandListener(this);
display.setCurrent(index);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable screen) {
if (command == exit) {
destroyApp(false);
notifyDestroyed();
} else if (command == connect) {
db = new DBConn(this);
db.start();
db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
displayIndex();
} else if (command == send) {
db.sendIndex(idx1.getString(), idx2.getString());
}
}
public class DBConn implements Runnable {
MySQLConn midlet;
private Display display;
String db;
String user;
String pwd;
String temp1;
String temp2;
public DBConn(MySQLConn midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.writeUTF(db.trim());
os.writeUTF(user.trim());
os.writeUTF(pwd.trim());
os.flush();
DataOutputStream os2 = (DataOutputStream)c.openDataOutputStream();
os2.writeUTF(temp1.trim());
os2.flush();
os2.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like db,user and pwd and pass to servlet */
public void connectDb(String db,String user,String pwd) {
this.db = db;
this.user = user;
this.pwd = pwd;
}
public void sendIndex(String temp1, String temp2){
this.temp1 = temp1;
this.temp2 = temp2;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("Alert");
a.setString("Alert: "+err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
Servlet:
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.sql.*;
@WebServlet("/getConnection")
public class getConnection extends HttpServlet {
public void init() { }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DataInputStream in = new DataInputStream((InputStream)request.getInputStream());
String db = in.readUTF();
String user = in.readUTF();
String pwd = in.readUTF();
String message ="polaczenie ";
try {
connect(db.toLowerCase().trim(),user.toLowerCase().trim(), pwd.toLowerCase().trim());
message += "ok";
} catch (Throwable t) {
message += "blad: " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
DataInputStream in2 = new DataInputStream((InputStream)request.getInputStream());
String temp1 = in2.readUTF().trim();
//String temp2 = in2.readUTF().trim();
System.out.print(temp1);
in2.close();
System.out.print(temp1);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
private void connect(String db, String user,String pwd) throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,user,pwd);
}
}