Jetty(二)登录实现

InterlliJ+Jetty+Cocos2d-JS

服务端:

JettyServer.java

package com.mind.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class JettyServer {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8030);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        // http://localhost:8030/mysql
        context.addServlet(new ServletHolder(new ServletDataBase()), "/mysql");

        try {
            server.start();
            server.join();
        } finally {
            server.destroy();
        }
    }
}

ServletDataBase.java

package com.mind.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDataBase extends HttpServlet implements Servlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletDataBase() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
	}

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String username = request.getParameter("name");
        String password = request.getParameter("password");

        System.out.println(username);
        System.out.println(password);


        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名
        String url = "jdbc:mysql://192.168.19.130/test";
        // MySQL配置时的用户名
        String user = "root";
        // Java连接MySQL配置时的密码
        String userpwd = "root";

        try {
            /**
             * 加载驱动程序
             */
            Class.forName(driver);

            // 连续数据库
            Connection conn = DriverManager.getConnection(url, user, userpwd);
            if(!conn.isClosed())
                System.out.println("Succeeded connecting to the Database!");

            // statement用来执行SQL语句
            Statement statement = conn.createStatement();

            // 要执行的SQL语句id和content是表review中的项。
            String sql = "select * from mytable where name='"+username+"' and password='" + password +"'";

            // 得到结果
            ResultSet rs = statement.executeQuery(sql);

            PrintWriter toClient = response.getWriter();
            if(rs.next()){
                System.out.println("Logon");
                toClient.println("1");

            }else{
                System.out.println("Login Faild");
            }
            /**
             * 跨域设置
             */
            response.setHeader("Access-Control-Allow-Origin", "*");

            rs.close();
            conn.close();
        } catch(ClassNotFoundException e) {
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
        } catch(SQLException e) {
            e.printStackTrace();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}
客户端

cf.LoginLayer = cc.Layer.extend({
    _usernameTextField:null,
    _passwordTextField:null,
    _registerButton:null,
    _loginButton:null,
    _activityController:null,
    ctor:function () {
        this._super();
        return true;
    },
    onEnter:function () {
        this._super();
        var l = new cc.LabelTTF("Get infos via XHR", "Thonburi", 16);
        this.addChild(l, 1);
        l.x = cc.winSize.width / 2;
        l.y = cc.winSize.height - 60;

        this._usernameTextField = new ccui.TextField();
        this._usernameTextField.setPosition(cc.p(cc.winSize.width/2, cc.winSize.height/2 + 100))
        this._usernameTextField.setPlaceHolder("请输入您的昵称");
        this.addChild(this._usernameTextField, 1);

        this._passwordTextField = new ccui.TextField();
        this._passwordTextField.setPosition(cc.p(cc.winSize.width/2, cc.winSize.height/2))
        this._passwordTextField.setPlaceHolder("请输入您的密码");
        this._passwordTextField.setPasswordEnabled(true);
        this.addChild(this._passwordTextField, 1);

        this._registerButton = new ccui.Button();
        this._registerButton.setTouchEnabled(true);
        this._registerButton.loadTextures(res.register_button_png, "", "");
        this._registerButton.addTouchEventListener(this.onTouchEvent, this);
        this._registerButton.setPosition(cc.p(cc.winSize.width /2 - this._registerButton.getContentSize().width/2, this._passwordTextField.getPosition().y - this._passwordTextField.getContentSize().height -50));
        this.addChild(this._registerButton, 1, 1);

        this._loginButton = new ccui.Button();
        this._loginButton.setTouchEnabled(true);
        this._loginButton.loadTextures(res.login_button_png, "", "");
        this._loginButton.addTouchEventListener(this.onTouchEvent, this);
        this._loginButton.setPosition(cc.p(cc.winSize.width /2 + this._loginButton.getContentSize().width/2, this._passwordTextField.getPosition().y - this._passwordTextField.getContentSize().height -50));
        this.addChild(this._loginButton, 1, 2);
    },

    sendPostForms: function() {
        var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12);
        this.addChild(statusPostLabel, 1);
        statusPostLabel.x = cc.winSize.width / 10 * 7;
        statusPostLabel.y = cc.winSize.height - 100;
        this.ensureLeftAligned(statusPostLabel);
        statusPostLabel.setString("Status: Send Post Request to httpbin.org width form data");

        var responseLabel = new cc.LabelTTF("", "Thonburi", 16);
        this.addChild(responseLabel, 1);
        this.ensureLeftAligned(responseLabel);
        responseLabel.x = cc.winSize.width / 10 * 7;
        responseLabel.y = cc.winSize.height / 2;

        var xhr = cc.loader.getXMLHttpRequest();
        this.streamXHREventsToLabel(xhr, responseLabel, responseLabel, "POST");
        xhr.open("POST", "http://192.168.199.132:8030/mysql");

        //set Content-Type "application/x-www-form-urlencoded" to post form data
        //mulipart/form-data for upload
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        /**
         form : {
            "name" : "liuwei",
            "password" : "123456"
        }
         **/
        var args = "name="+ this._usernameTextField.getString() +"&password="+ this._passwordTextField.getString();
        xhr.send(args);
    },
    scrollViewDidScroll:function (view) {
    },
    scrollViewDidZoom:function (view) {
    },
    onTouchEvent:function (sender, type) {
        switch (type) {
            case ccui.Widget.TOUCH_BEGAN:
                break;
            case ccui.Widget.TOUCH_MOVED:
                break;
            case ccui.Widget.TOUCH_ENDED:
                if (sender.getTag() == 2) {
                    if(this._usernameTextField.getString() && this._passwordTextField.getString()) {
                        this.sendPostForms();
                    }
                } else if (sender.getTag() == 1) {
                    //
                }
        }
    },
    streamXHREventsToLabel:function ( xhr, label, textbox, method ) {
        // Simple events
        ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'].forEach(function (eventname) {
            xhr["on" + eventname] = function () {
                label.string += "\nEvent : " + eventname
            }
        });
        // Special event
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                var httpStatus = xhr.statusText;
                cc.log("httpstatus==>"+ httpStatus);
                if(xhr.responseText){
                    that._usernameTextField.setString("");
                    that._passwordTextField.setString("");
                    that._loginButton.setTouchEnabled(false);
                    that._registerButton.setTouchEnabled(false);
                    // cc.director.runScene(new GameMainScene);
                    cc.log("login in");
                }else{
                    that._usernameTextField.setString("");
                    that._passwordTextField.setString("");
                    cc.log("login out");
                }
                cc.log("xhr.responseText==>"+ xhr.responseText);
            }
        }
    },
    ensureLeftAligned:function (label) {
        label.anchorX = 0;
        label.anchorY = 1;
        label.textAlign = cc.TEXT_ALIGNMENT_LEFT;
    }
});

cf.LoginScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new cf.LoginLayer();
        this.addChild(layer);
    }
});

 

运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Netty和Jetty都是Java中常用的网络通信库,它们的实现原理如下: 1. Netty Netty是一个基于事件驱动的异步网络通信库,它采用NIO(非阻塞IO)模型实现高性能的网络通信。Netty的主要特点包括: - 基于NIO模型,实现高性能的网络通信; - 采用事件驱动的方式,支持异步IO操作; - 提供了丰富的编解码器和处理器,方便用户进行网络通信协议的实现; - 支持多种网络协议,如TCP、UDP、HTTP、WebSocket等。 Netty的实现原理主要包括以下几个方面: - Reactor模式:Netty采用Reactor模式作为底层通信框架,通过Selector轮询IO事件,然后分发给对应的Handler进行处理; - Channel和EventLoop:Netty中的Channel表示一个网络连接,EventLoop表示一个事件循环,一个EventLoop可以对应多个Channel,通过事件驱动的方式进行异步IO操作; - Pipeline机制:Netty中的Pipeline是一种处理器链,每个Channel都有一个对应的Pipeline,通过添加不同的处理器,可以实现对网络通信数据的编解码、处理等操作; - ByteBuf:Netty中的ByteBuf是一种高效的字节缓冲区,支持读写操作,可以减少内存拷贝和提高IO效率。 2. Jetty Jetty是一个基于Servlet容器的Web务器和Servlet容器,它采用线程池和NIO模型实现高性能的Web务。Jetty的主要特点包括: - 基于Servlet容器,支持常用的Web应用开发技术; - 支持异步Servlet和WebSocket等技术,提高Web应用的性能和交互效果; - 支持HTTP/2和WebSocket协议,提升Web应用的传输效率; - 支持多种Web容器集群部署方式,提高Web应用的可伸缩性。 Jetty实现原理主要包括以下几个方面: - Servlet容器:Jetty采用Servlet容器作为底层通信框架,通过处理HTTP请求和响应来实现Web务; - 线程池和NIO模型:Jetty采用线程池和NIO模型实现高性能的Web务,通过异步IO操作来提高Web应用的吞吐量; - WebSocket和HTTP/2支持:Jetty支持WebSocket和HTTP/2协议,提高Web应用的传输效率和交互效果; - Web容器集群:Jetty支持多种Web容器集群部署方式,提高Web应用的可伸缩性。 总的来说,Netty和Jetty都是高性能的网络通信库,它们实现原理的核心都是采用了NIO模型和事件驱动的方式来实现异步IO操作。Netty主要用于实现网络通信协议,如TCP、UDP、HTTP、WebSocket等,而Jetty主要用于实现Web务器和Servlet容器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值