我的漫漫程序之旅

专注于JavaWeb开发
随笔 - 39, 文章 - 310, 评论 - 411, 引用 - 0
数据加载中……

[原创]J2ME/J2EE实现用户登录交互

实现功能:
用手机客户端进行登录服务器,然后返回消息进行交互.

服务器代码:
LoginServlet:
package com;

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;

/*******************************************************************************
 * 
 * 
@author zdw
 * 
 
*/

@SuppressWarnings(
"serial")
public class LoginServlet extends HttpServlet
{

    
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 ("zdw".equals(username) && "admin".equals(password))
        
{
            
// 响应数据
            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方式与服务器交互
 * 
 * 
@author zdw
 * 
 
*/

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

        }

    }


    
/***************************************************************************
     * 与服务器交互相关代码
     
*/

    
public void inTurnServer()
    
{
        
try
        
{
            
// 服务器请求地址
            String url = "http://localhost:8888/LoginWeb/LoginServlet";
            
// 用户输入的用户名
            String username = this.username.getString();
            
// 用户输入的密码
            String password = this.password.getString();
            
// 用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");

            
// 要发送的数据
            String formData = "username=" + username + "&password=" + password;
            
// 转换显字节流
            byte[] data = formData.getBytes();
            
// 设置写入流的长度
            conn.setRequestProperty("Content-Length", Integer
                    .toString(data.length));
            OutputStream os 
= conn.openOutputStream();
            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(0this.username.getString().length());
                    
this.password.delete(0this.password.getString().length());
                }

            }

        }
 catch (IOException e)
        
{
            e.printStackTrace();
        }

    }


    
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
    
{

    }


    
protected void pauseApp()
    
{

    }


}


源码下载:点此下载

注意此工程为MyEclipse工程,您需要安装wtk和tomcat才能正常运行此程序.
登录图:

posted on 2008-06-23 17:41 々上善若水々 阅读(3404) 评论(9)  编辑  收藏

评论

# re: [原创]J2ME/J2EE实现用户登录交互[未登录]  回复  更多评论   

麻雀虽小,五脏俱全.

收藏.
2008-06-23 17:57 |

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

用手机客户端进行登录服务器,这个功能真是我工作中要学习的,谢谢。
2008-06-23 21:58 | DVD比价

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

谢谢不错的案例
2008-06-24 07:40 | Java_do

# re: [原创]J2ME/J2EE实现用户登录交互[未登录]  回复  更多评论   

在某些情况下username和password可能还需要encoding一下才行
2008-06-24 09:46 | Gary

# re: [原创]J2ME/J2EE实现用户登录交互[未登录]  回复  更多评论   

学习,还有些细节方面的没看懂!
2008-06-25 18:54 | 石头

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

不錯,學習了.
線程創建那裡,不錯.
2008-08-14 13:53 | mooring

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

网上关于这方面的内容还真少。谢。
2008-11-03 17:55 | log

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

看了这个 想在毕业设计中加入 手机客户端 挺酷的 能不能给一些这方面的资料呀 我的邮箱522315678@qq.com
2009-03-24 13:29 | 爽哦

# re: [原创]J2ME/J2EE实现用户登录交互  回复  更多评论   

不错!感谢楼主你的分享!
2011-11-15 19:21 | tianyake

只有注册用户登录后才能发表评论。


网站导航: