|
查看: 1523|回复: 9
|
J2ME连接MySQL问题 (Servlet)!!!
[复制链接]
|
|
|
J2ME连接MySQL问题
(Servlet)!!!
如题。我是个Java新手,请各位高手帮帮忙,急。万分谢意。
1. 我利用LoginServlet.java尝试连接MySQL Database : Working!!!
2. 参考书籍,利用HTTPCommunication.java 连接 Servlets.java (JBoss) ; 修改Servlet.java尝试连接MySQL Database: Failed!!!
以下是我的Code:
HTTPCommunication.java
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
import com.shared.*;
public class HTTPCommunication {
private String serviceURL;
private boolean offline = true;
private ProgressObserverUI progressObserverUI = null;
public HTTPCommunication(String serviceURL, ProgressObserverUI progressObserverUI) {
this.serviceURL = serviceURL;
this.progressObserverUI = progressObserverUI;
return;
}
public boolean isOffline() {
return offline;
}
public void setOffline(boolean offline) {
this.offline = offline;
return;
}
public boolean login(String userName, String password) {
int passed = 0;
HttpConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
try {
connection = openConnection();
updateProgress();
outputStream = openConnectionOutputStream(connection);
outputStream.writeByte(MessageConstants.OPERATION_LOGIN_USER);
outputStream.writeUTF(userName);
outputStream.writeUTF(password);
outputStream.close();
updateProgress();
inputStream = openConnectionInputStream(connection);
passed = inputStream.readInt();
System.out.println(passed);
updateProgress();
} catch (IOException ioe) {
} finally {
closeConnection(connection, outputStream, inputStream);
}
if (passed == 1)
return true;
else
return false;
}
private HttpConnection openConnection() throws IOException {
try {
HttpConnection connection = (HttpConnection) Connector.open(serviceURL);
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.1");
connection.setRequestProperty("Content-Type","application/octet-stream");
connection.setRequestMethod(HttpConnection.POST);
offline = false;
return connection;
} catch (IOException ioe) {
offline = true;
throw ioe;
}
}
private DataOutputStream openConnectionOutputStream(HttpConnection connection) throws IOException {
try {
return connection.openDataOutputStream();
} catch (IOException ioe) {
offline = true;
throw ioe;
}
}
private DataInputStream openConnectionInputStream(HttpConnection connection) throws IOException {
try {
int responseCode = connection.getResponseCode();
if (responseCode == HttpConnection.HTTP_OK) {
DataInputStream inputStream = connection.openDataInputStream();
return inputStream;
}
} catch (IOException ioe) {
offline = true;
}
return null;
}
void closeConnection(HttpConnection connection, DataOutputStream outputStream, DataInputStream inputStream) {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ioe) {
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
}
}
if (connection != null) {
try {
connection.close();
} catch (IOException ioe) {
}
}
return;
}
protected void updateProgress() {
if (progressObserverUI != null) {
if (!progressObserverUI.isStopped()) {
progressObserverUI.updateProgress();
return;
}
}
}
}
Servlet.java
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
import com.luckysms.shared.*;
public class LCKServlet extends HttpServlet {
protected static final String DBName = "java:/DefaultDS";
private DataSource dataSource;
public void init(ServletConfig config) throws ServletException {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup(DBName);
} catch (Exception e) {
e.printStackTrace();
throw new ServletException("init error");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/octet-stream");
InputStream is = request.getInputStream();
OutputStream os = response.getOutputStream();
DataInputStream call = new DataInputStream(is);
DataOutputStream result = new DataOutputStream(os);
byte method = call.readByte();
switch (method) {
case MessageConstants.OPERATION_LOGIN_USER:
login(call,result);
break;
/** case MessageConstants.XXX:
......**/
}
response.setContentLength(result.size());
}
private void login(DataInputStream call, DataOutputStream result) throws IOException{
String username = call.readUTF();
String password = call.readUTF();
System.out.println(username);
System.out.println(password);
/**Database Query Here**/
result.writeInt(1);
return;
}
}
|
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 02:14 PM
|
显示全部楼层
LoginServlet.java
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
Connection conn = null;
String nextJSP = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e){
throw new ServletException("Unable to load JDBC driver");
}
String userid = (String)request.getParameter("userid");
String password = (String)request.getParameter("password");
conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dbname", "root", "123456");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM users WHERE USERNAME =? AND PWD =?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, userid);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()){
StringBuffer fullName = new StringBuffer();
fullName.append(rs.getString(1));
fullName.append(" ");
fullName.append(rs.getString(2));
request.setAttribute ("fullName", fullName.toString());
nextJSP = "/LoginOK.jsp";
}
else{
nextJSP = "/LoginFailed.jsp";
}
conn.close();
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
RequestDispatcher rd = context.getRequestDispatcher(nextJSP);
rd.forward(request, response);
}
catch (SQLException e){
throw new ServletException("SQL call failed");
}
catch (Exception e){
throw new ServletException(e.getMessage());
}
finally{
if (conn != null){
try{
conn.close();
}
catch (SQLException e){
throw new ServletException("connection close failed");
}}}}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
doPost(request, response);
}} |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 02:16 PM
|
显示全部楼层
|
要如何修改Servlets.java可以连接MySQL?谢谢 |
|
|
|
|
|
|
|
|
|
|
发表于 20-11-2009 02:24 PM
|
显示全部楼层
可以 写出来 你 的 ERROR CONSOLE 吗 ????
P.S : 建议你用 DEBUG MODE 。。。。 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 03:30 PM
|
显示全部楼层
回复 4# 兔仙人 的帖子
不好意思,我用Netbeans 编写的。我选择Debug --> Debug Main Project
Connected to KVM
KdpDebugTask connecting to debugger 1 ..
KdpDebugTask connecting to debugger 2 ..
KdpDebugTask connecting to debugger 3 ..
KdpDebugTask connecting to debugger 4 ..
KdpDebugTask connecting to debugger 5 ..
KdpDebugTask connecting to debugger 6 ..
Connecting JPDA Debugger to emulator timed out after 6 attempts and 33 seconds. |
|
|
|
|
|
|
|
|
|
|
发表于 20-11-2009 03:45 PM
|
显示全部楼层
。。。。。 如果 CONNECT 不到 , 应该 会 PROMPT EXCEPTION 出来 。。  |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 04:08 PM
|
显示全部楼层
谢谢回复。我的Midlet 如下。它PROMPT “Connection Not FOund”
Thread thread = new Thread() {
public void run() {
try {
String url = "http://127.0.0.1:8080/Servlet";
HTTPCommunication hc = new HTTPCommunication(url,progressObserverUI);
if(hc.login(userName,password) == true){
switchDisplayable(null, getMenuList());
}else{
//showErrorAlert("Invalid Username/Password!", display.getCurrent());
switchDisplayable(null, getErrorForm(lang.INDEX_HEADER, lang.INDEX_ERRALERT_INVLOGIN));
}
if(progressObserverUI != null)
progressObserverUI = null;
} catch (Exception e) {
switchDisplayable(null, getErrorForm("", "Connection Not FOund"));
}
}
};
runWithProgress(thread, lang.INDEX_HEADER, false);
} |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 04:11 PM
|
显示全部楼层
|
您可以帮忙修改以上的Servlet.java Connect 去mySQL? Thanks |
|
|
|
|
|
|
|
|
|
|
发表于 20-11-2009 04:39 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 20-11-2009 05:20 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|