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


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

hessian:

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

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

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

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

protocol buffer:

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

EasyUI:

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

案例如下:

需求介紹:

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

主要功能點如下:

① 用戶登錄

② 顯示用戶信息

登錄流程

①用戶通過瀏覽器訪問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頁面


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM