使用hessian+protocol buffer+easyUI綜合案例--登錄

首先先簡單介紹下hessian ,protocol buffer, easyUI框架javascript

hessian:

Hessian是一個輕量級的remoting on http工具,採用的是Binary RPC協議,因此它很適合於發送二進制數據,同時又具備防火牆穿透能力。Hessian通常是經過Web應用來提供服務,所以很是相似於平時咱們用的 WebService。只是它不使用SOAP協議,但相比webservice而言更簡單、快捷。Hessian官網:http://hessian.caucho.com/css

Hessian 可經過Servlet提供遠程服務,須要將匹配某個模式的請求映射到Hessian服務。也可Spring框架整合,經過它的 DispatcherServlet能夠完成該功能,DispatcherServlet可將匹配模式的請求轉發到Hessian服務。Hessian的server端提供一個servlet基類, 用來處理髮送的請求,而Hessian的這個遠程過程調用,徹底使用動態代理來實現的,,建議採用面向接口編程,Hessian服務經過接口暴露。html

Hessian處理過程示意圖:客戶端——>序列化寫到輸出流——>遠程方法(服務器端)——>序列化寫到輸出流 ——>客戶端讀取輸入流——>輸出結果前端

使用hessian所要下載的包:hessian-4.0.37.jarjava

protocol buffer:

protocolbuffer(如下簡稱PB)是google 的一種數據交換的格式,它獨立於語言,獨立於平臺。google 提供了三種語言的實現:java、c++ 和 python,每一種實現都包含了相應語言的編譯器以及庫文件。因爲它是一種二進制的格式,比使用 xml 進行數據交換快許多。能夠把它用於分佈式應用之間的數據通訊或者異構環境下的數據交換。做爲一種效率和兼容性都很優秀的二進制數據傳輸格式,能夠用於諸如網絡傳輸、配置文件、數據存儲等諸多領域。python

EasyUI:

jQuery EasyUI是一組基於jQuery的UI插件集合體,而jQuery EasyUI的目標就是幫助web開發者更輕鬆的打造出功能豐富而且美觀的UI界面。開發者不須要編寫複雜的javascript,也不須要對css樣式有深刻的瞭解,開發者須要瞭解的只有一些簡單的html標籤。jquery

案例以下:

需求介紹:c++

實現Server1上的用戶帳號可在其餘應用(Server2)上登陸的功能,達到一號多用和用戶數據共享的目的。web

主要功能點以下:編程

① 用戶登陸

② 顯示用戶信息

登陸流程

①用戶經過瀏覽器訪問Server2的登錄界面。

②用戶輸入帳號密碼,點擊登錄按鈕。

③Server2收到用戶的登陸請求,調用Server1的帳號驗證接口。

④Server1驗證Server2發送過來的帳號信息(用戶名、密碼)後,返回驗證結果。

⑤Server2收到並處理Server1返回的驗證結果,再將相關信息返回給用戶(提示登陸失敗或者顯示用戶信息)。 

技術需求

①全部網頁界面均採用easyui編寫。

②服務器之間(Server1和Server2)的通訊基於protobuf和 hessian(protobuf用於數據傳輸,hessian用於遠程接口調用)。

③hessian遠程接口方法的入參和返回值類型均爲字節數組。

Server2調用Server1的接口時,先構造protobuf對象,將屬性填充完畢後,將該對象序列化獲得的字節數組填入接口方法傳給Server1;Server1收到該請求,將Server2傳過來的字節數組反序列化成protobuf對象,獲取其中的屬性值(好比用戶賬號、密碼),處理完成後,將處理結果填入protobuf對象,並返回該對象的序列化結果(字節數組)。

流程圖:

具體實現:

先下載所必須的包 hessioan-4.0.37.jar,必須安裝protocol buffer,下載easyUI包

首先先寫服務端:

建立web項目hessianServer

目錄以下:

在protocol安裝目錄下的examples下建立user.proto文件

package com.hessian.model;
option java_package="com.hessian.model";
option java_outer_classname="UserProtos";
message User{
    required string name=1;
    required string password=2;
    required string birth=3;
    optional string email = 4;
    optional int64 phone=5;
}

進入XXX\protobuf-2.4.1\examples目錄,能夠看到user.proto文件,執行命令 protoc --java_out=. user.proto 命令,若是生成com文件夾並在最終生成UserProtos類。

將UserProtos.java和XXX\protobuf-2.4.1\java\target目錄下的protobuf-java-2.4.1.jar, hessioan-4.0.37.jar導入到web項目中

下面編寫服務端代碼

IService:

package com.hessian.service;

public interface IService {
    
    public Boolean login(byte[] user);
    
}

ServiceImpl

package com.hessian.service.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import com.google.protobuf.InvalidProtocolBufferException;
import com.hessian.model.UserProtos;
import com.hessian.model.UserProtos.User;
import com.hessian.service.IService;

public class ServiceImpl implements IService {

   
    public Boolean login(byte[] user) {
    
        UserProtos.User use=null;
        try {
             use=UserProtos.User.parseFrom(user); //將字節數組轉化爲對象
            System.out.println(use);
            
        } catch (InvalidProtocolBufferException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //進行用戶名,密碼驗證
        if(use.getName().equals("oumyye")&&use.getPassword().equals("oumyye")){
        return true;
        }
        else {
            return false;
        }
    }
  
}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <!-- 配置 HessianServlet,Servlet的名字隨便配置,例如這裏配置成ServiceServlet-->
        <servlet-name>ServiceServlet</servlet-name>
        <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
        
        <!-- 配置接口的具體實現類 -->
        <init-param>
            <param-name>service-class</param-name>
            <param-value>com.hessian.service.impl.ServiceImpl</param-value>
        </init-param>
    </servlet>
    <!-- 映射 HessianServlet的訪問URL地址-->
    <servlet-mapping>
        <servlet-name>ServiceServlet</servlet-name>
        <url-pattern>/ServiceServlet</url-pattern>
    </servlet-mapping>

</web-app>

到此服務service1編寫完成

進入http://localhost:8080/HessianServer/ServiceServlet出現

則編寫成功,將src下的代碼打包成hessian-common.jar文件。

下面進行service2客戶端的編寫loginClient

首先也要導入相關jar包,及目錄以下:

編寫前端代碼:

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ValidateBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="themes/icon.css">
    <link rel="stylesheet" type="text/css" href="demo.css">
    <style type="text/css">
        input,textarea{
            width:200px;
            border:1px solid #ccc;
            padding:2px;
        }
    </style>
    <script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="jquery/jquery.easyui.min.js"></script>
</head>
<body>
    <h2>登錄</h2>
    ${info}
    <div>
    <form action="Login" method="post">
    <table>
        <tr>
            <td>用戶名:</td>
            <td><input class="easyui-validatebox" data-options="required:true,validType:'length[1,3]'" name="name"></td>
        </tr>
        <tr>
            <td>密碼:</td>
            <td><input class="easyui-validatebox" data-options="validType:'password'" name="password"></td>
        </tr>
        </table>
        <input type="submit"  value="登錄" style="width: 50px">
    </form>
        </div>
        </body>
        </html>

success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ValidateBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="themes/icon.css">
    <link rel="stylesheet" type="text/css" href="demo.css">
    <style type="text/css">
        input,textarea{
            width:200px;
            border:1px solid #ccc;
            padding:2px;
        }
    </style>
    <script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="jquery/jquery.easyui.min.js"></script>
</head>
<body>
    <h2>登錄成功</h2>
    
    ${name}
    
        </body>
        </html>

而後編寫servlet代碼

package com.hessian.servlet;

import java.io.IOException;

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

import com.caucho.hessian.client.HessianProxyFactory;
import com.hessian.model.UserProtos.User.Builder;
import com.hessian.service.IService;

public class loginServlet extends HttpServlet {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;

     public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            
            String url = "http://192.168.2.108:8080/HessianServer/ServiceServlet";
            HessianProxyFactory factory = new HessianProxyFactory();
            IService service = (IService) factory.create(IService.class, url);//建立IService接口的實例對象
            com.hessian.model.UserProtos.User.Builder ump=com.hessian.model.UserProtos.User.newBuilder();
            ump.setName(request.getParameter("name"));
            ump.setPassword(request.getParameter("password"));
            ump.setEmail("54654@qq.com");
            ump.setBirth("19931223");
            ump.setPhone(12313213);
            com.hessian.model.UserProtos.User info=ump.build();
            byte[] user=info.toByteArray();
            if(service.login(user)){
                    RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
                    dispatcher .forward(request, response);
                }else {
                    request.setAttribute("info", "登錄失敗!");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                    dispatcher .forward(request, response);
                }
        }
        
}

編寫web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>com.hessian.servlet.loginServlet</servlet-class>
    </servlet>
        <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
        </servlet-mapping>
</web-app>

這樣整個代碼就算編寫完成了,下面進行測試:

http://localhost:8080/loginClient/ 可進行登錄,當用戶名密碼爲oumyye時可登錄成功,跳轉success.jsp頁面

相關文章
相關標籤/搜索