J2ME用户登录验证
[说明]
J2ME用户登录验证,一直没有搞定怎么回事,网上搜到 [J2ME/J2EE实现用户登录交互] ,还是不能运行,问题主要出在Servlet上,没有看过,不会配置,很是郁闷,前天在同学SpringChen的指点下,学会了配置,今天终于搞懂了J2ME用户登录验证机制,非常高兴,随把调试的程序贴出来,以备以后查阅。
代码中,修改了原程序不合理及条例不清楚的部分,故升级为2.0版本,特此声明。
[代码部分]
实现功能:
用手机客户端进行登录服务器,然后服务器返回消息进行交互。
服务器代码:
需要配置Servlet,首先熟悉Servlet相关知识。
LoginServlet:
package packageOne;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** *//**
* 服务器端代码, 需配置Servlet.
* Time: 2008 09 03 .
*/
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// 得到客户端传入的数据(用户名和密码)
String username = request.getParameter("username");
String password = request.getParameter("password");
// 构建输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// 逻辑操作(这里写你的逻辑判断)
if (username.equals("dcf") && password.equals("admin"))
{
// 响应数据
dos.writeUTF("true");
} else
{
// 响应数据
dos.writeUTF("false");
}
//获得写入的字节数组流
byte[] data = baos.toByteArray();
// 设置服务器响应参数
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength(data.length);
response.setContentType("application/octet-stream");
// 构建输出流, 写入要返回给客户端的数据
OutputStream os = response.getOutputStream();
os.write(data);
os.close();
}
}
手机客户端代码:
LoginForm:
package com;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
/** *//**
* 用Http Post方式与服务器交互
* 修改了转贴源代码中不合理的部分
* @author Du Changfeng 2008 09 03
* @version 2.0
*/
public class LoginForm extends MIDlet implements CommandListener
{
private Form form = null;
private Display display = Display.getDisplay(this);;
private Command login = null;
private Command exit = null;
private TextField username = null;
private TextField password = null;
private Alert alert = null;
private Alert error = null;
public LoginForm()
{
form = new Form("用户登录");
display.setCurrent(form);
login = new Command("登录", Command.SCREEN, 1);
exit = new Command("退出", Command.EXIT, 1);
form.addCommand(login);
form.addCommand(exit);
username = new TextField("用户名", "", 20, TextField.ANY);
password = new TextField("密 码", "", 20, TextField.PASSWORD);
form.append(username);
form.append(password);
form.setCommandListener(this);
}
public void initAlertOK()
{
alert = new Alert("提示", "登录成功 !\r\n您的用户名为:" + username.getString()
+ "\r\n密码为:" + password.getString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
public void initAlertError()
{
error = new Alert("提示", "登录失败,用户名或密码错误", null, AlertType.ERROR);
display.setCurrent(error);
}
protected void startApp() throws MIDletStateChangeException
{
}
/** *//**
* 事件处理
*/
public void commandAction(Command cmd, Displayable dis)
{
// 点击退出按钮事件
if (cmd.getCommandType() == Command.EXIT)
{
System.out.println("exit");
this.notifyDestroyed();
}
if (cmd == login)
{
// 必须开启独立线程来处理Http请求,否则会造成死锁
new Thread(new Runnable()
{
public void run()
{
try
{
inTurnServer();
} catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
}
/** *//***********************************************
* 用Post与服务器交互相关代码
*/
public void inTurnServer()
{
// 服务器请求地址
String url = "http://localhost:80/testLogin/login";
// 用户输入的用户名
String username = this.username.getString();
// 用户输入的密码
String password = this.password.getString();
// 要发送的数据
String formData = "username=" + username + "&password=" + password;
// 转换显字节流
byte[] data = formData.getBytes();
try {
// 用url建立一个Http连接(安全的)
HttpConnection conn = (HttpConnection) Connector.open(url);
/** *//****以下为 设置连接属性****/
// 设置请求类型为POST
conn.setRequestMethod(HttpConnection.POST);
// 设置一般的请求属性
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Configuration/CLDC-1.0");
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.setRequestProperty("Connection", "close");
// 设置写入流的长度
conn.setRequestProperty("Content-Length", Integer
.toString(data.length));
// 新建输出流,对数据流进行操作
OutputStream os = conn.openOutputStream();
// 写入要Post的数据
os.write(data);
os.close();
// 得到Http响应代码
int rc = conn.getResponseCode();
if (rc == HttpConnection.HTTP_OK)
{
// 构建输入流
DataInputStream dism = new DataInputStream(conn
.openInputStream());
// 读取服务器返回的字节流
String result = dism.readUTF();
dism.close();
// 判断
if (result.equals("true"))
{
// 显示登录成功
this.initAlertOK();
}
if (result.equals("false"))
{
// 显示登录失败
this.initAlertError();
// 将输入框置空
this.username.delete(0, this.username.getString().length());
this.password.delete(0, this.password.getString().length());
}
}
} catch (IOException e)
{
e.printStackTrace();
System.out.println("联网出错。");
//如果请求路径不正确,或属性设置错误,或服务器端的问题导致无法正确联网
error = new Alert("提示", "联网出错", null, AlertType.ERROR);
display.setCurrent(error);
}
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
{
}
protected void pauseApp()
{
}
}
附一:服务器端Web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>packageOne.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
附二:服务器端index.jsp配置(可选内容)
<FORM action="<%=request.getContextPath()%>/login" method="post" name="99">
<input type="text" name="username" />
<input type="text" name="password" />
<INPUT type="submit" name="toLogin" value="登录">
</FORM>
<End>