A. 寫webservice為什麼要序列化
webservice 是基於http的 也就是走tcp/ip協議傳輸 需要通過網路傳輸的所有東東都需要進行序列化 和反序列化
B. 淺談java中為什麼實體類需要實現序列化
序列化的意義
客戶端訪問了某個能開啟會話功能的資源,
web伺服器就會創建一個與該客戶端對應的HttpSession對象,每個HttpSession對象都要站用一定的內存空間。
如果在某一時間段內訪問站點的用戶很多,web伺服器內存中就會積累大量的HttpSession對象,消耗大量的伺服器內存,即使用戶已經離開或者關閉了瀏覽器,web伺服器仍要保留與之對應的HttpSession對象,在他們超時之前,一直佔用web伺服器內存資源。
web伺服器通常將那些暫時不活動但未超時的HttpSession對象轉移到文件系統或資料庫中保存,伺服器要使用他們時再將他們從文件系統或資料庫中裝載入內存,這種技術稱為Session的持久化。
將HttpSession對象保存到文件系統或資料庫中,需要採用序列化的方式將HttpSession對象中的每個屬性對象保存到文件系統或資料庫中;將HttpSession對象從文件系統或資料庫中裝載如內存時,需要採用反序列化的方式,恢復HttpSession對象中的每個屬性對象。
所以存儲在HttpSession對象中的每個屬性對象必須實現Serializable介面
C. 為什麼實體類要實現serializable介面序列化
當客戶端訪問可以打開會話功能的資源時,web伺服器會創建一個與客戶端對應的HttpSession對象,每個HttpSession對象都會使用一定的內存空間。如果在一定時間內有大量用戶訪問網站,那麼大量的HttpSession對象就會堆積在web伺服器的內存中,這會消耗大量的伺服器內存。即使用戶已經離開或關閉了瀏覽器,web伺服器仍然會保留相應的HttpSession對象,這將佔用web伺服器的內存資源,直到它們超時。
Web伺服器通常會將那些暫時處於非活動狀態但尚未超時的HttpSession對象傳輸到文件系統或資料庫中進行存儲,然後在伺服器想要使用它們時將它們從文件系統或資料庫載入到內存中。這項技術被稱為會話持久性。
要將HttpSession對象保存到文件系統或資料庫,需要將HttpSession對象中的每個屬性對象序列化到文件系統或資料庫。當從文件系統或資料庫(如內存)載入HttpSession對象時,需要對其進行反序列化,以恢復HttpSession對象中的每個屬性對象。因此,存儲在HttpSession對象中的每個屬性對象都必須實現Serializable介面。
簡言之,就是為了 將對象的狀態保存在存儲媒體中以便可以在以後重新創建出完全相同的副本。實現 Serializable介面還能 按值將對象從一個應用程序域發送至另一個應用程序域。
D. java實體類為什麼要實現序列化
解答如下:
當客戶端訪問某個能開啟會話功能的資源,web伺服器就會創建一個HTTPSession對象,每個HTTPSession對象都會佔用一定的內存,如果在同一個時間段內訪問的用戶太多,就會消耗大量的伺服器內存,為了解決這個問題我們使用一種技術:session的持久化。
什麼是session的持久化?
web伺服器會把暫時不活動的並且沒有失效的HTTPSession對象轉移到文件系統或資料庫中儲存,伺服器要用時在把他們轉載到內存。
把Session對象轉移到文件系統或資料庫中儲存就需要用到序列化; java.io.Serializable。
在tomcat重啟的時候進行一個鈍化操作、啟動成功之後再進活化。
在對應的區域載入進來,不會丟失(前提是session中的存放的變數必須實現序列化介面才能鈍化,才能序列到硬碟上的一個二進制文件中去)。
E. 如何將程序生成的對象進行序列化傳遞
序列化與反序列化
先在webserver端序列化,然後再客戶端反序列化,需要注意的是兩次序列化方式要一致,從下面選擇一種方式來實現吧,一般都是把對象序列化成字元串,然後再把字元串反序列化成相應的對象,當然根據需要你也可以序列化成byte數組
/****************************************
* 作者:張江松
* 創始時間:2008-5-29
* 功能:
*
* 修改人:
* 修改時間:
* 描述:
****************************************/
namespace MultiMedia.Common
{
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
/// <summary>
/// SerializeHelper 用於簡化序列化和反序列化操作 。
/// 作者:朱偉 [email protected]
/// 2004.05.12
/// </summary>
public static class SerializeHelper
{
#region BinaryFormatter
#region SerializeObject
public static byte[] SerializeObject(object obj) //obj 可以是數組
{
IFormatter formatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();//此種情況下,mem_stream的緩沖區大小是可變的
formatter.Serialize(memoryStream, obj);
byte[] buff = memoryStream.ToArray();
memoryStream.Close();
return buff;
}
public static void SerializeObject(object obj, ref byte[] buff, int offset) //obj 可以是數組
{
byte[] rude_buff = SerializeHelper.SerializeObject(obj);
for (int i = 0; i < rude_buff.Length; i++)
{
buff[offset + i] = rude_buff[i];
}
}
#endregion
#region DeserializeBytes
public static object DeserializeBytes(byte[] buff, int index, int count)
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(buff, index, count);
object obj = formatter.Deserialize(stream);
stream.Close();
return obj;
}
#endregion
#endregion
#region SoapFormatter
#region SerializeObjectToString
/// <summary>
/// SerializeObjectToString 將對象序列化為SOAP XML 格式。
/// 如果要將對象轉化為簡潔的xml格式,請使用ESBasic.Persistence.SimpleXmlConverter類。
/// </summary>
public static string SerializeObjectToString(object obj)
{
IFormatter formatter = new SoapFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string res = reader.ReadToEnd();
stream.Close();
return res;
}
#endregion
#region DeserializeString
public static object DeserializeString(string str,System.Text.Encoding ecnoding)
{
byte[] buff = ecnoding.GetBytes(str);
IFormatter formatter = new SoapFormatter();
MemoryStream stream = new MemoryStream(buff, 0, buff.Length);
object obj = formatter.Deserialize(stream);
stream.Close();
return obj;
}
#endregion
#endregion
#region XmlSerializer
#region XmlObject
public static string XmlObject(object obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
xmlSerializer.Serialize(stream, obj);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string res = reader.ReadToEnd();
stream.Close();
return res;
}
#endregion
#region ObjectXml
public static T ObjectXml<T>(string str, System.Text.Encoding ecnoding)
{
return (T)SerializeHelper.ObjectXml(str, typeof(T), ecnoding);
}
public static object ObjectXml(string str, Type targetType, System.Text.Encoding ecnoding)
{
byte[] buff = ecnoding.GetBytes(str);
XmlSerializer xmlSerializer = new XmlSerializer(targetType);
MemoryStream stream = new MemoryStream(buff, 0, buff.Length);
object obj = xmlSerializer.Deserialize(stream);
stream.Close();
return obj;
}
#endregion
#endregion
#region SaveToFile
/// <summary>
/// SaveToFile 將對象的二進制序列化後保存到文件。
/// </summary>
public static void SaveToFile(object obj, string filePath)
{
FileStream stream = new FileStream(filePath, FileMode.CreateNew);
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Flush();
stream.Close();
}
#endregion
#region ReadFromFile
/// <summary>
/// ReadFromFile 從文件讀取二進制反序列化為對象。
/// </summary>
public static object ReadFromFile(string filePath)
{
byte[] buff = FileHelper.ReadFileReturnBytes(filePath);
return SerializeHelper.DeserializeBytes(buff, 0, buff.Length);
}
#endregion
}
/// <summary>
/// 序列化類
/// </summary>
public static class Serializer
{
/// <summary>
/// Static Constructor is used to set the CanBinarySerialize value only once for the given security policy
/// </summary>
static Serializer()
{
SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.SerializationFormatter );
try
{
sp.Demand();
CanBinarySerialize = true;
}
catch ( SecurityException )
{
CanBinarySerialize = false;
}
}
/// <summary>
/// Readonly value indicating if Binary Serialization (using BinaryFormatter) is allowed
/// </summary>
public static readonly bool CanBinarySerialize;
/// <summary>
/// Converts a .NET object to a byte array. Before the conversion happens, a check with
/// Serializer.CanBinarySerialize will be made
/// </summary>
/// <param name="objectToConvert">Object to convert</param>
/// <returns>A byte arry representing the object paramter. Null will be return if CanBinarySerialize is false</returns>
public static byte[] ConvertToBytes( object objectToConvert )
{
byte[] byteArray = null;
if ( CanBinarySerialize )
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
using ( MemoryStream ms = new MemoryStream() )
{
binaryFormatter.Serialize( ms, objectToConvert );
// Set the position of the MemoryStream back to 0
//
ms.Position = 0;
// Read in the byte array
//
byteArray = new Byte[ ms.Length ];
ms.Read( byteArray, 0, byteArray.Length );
ms.Close();
}
}
return byteArray;
}
/// <summary>
/// Saves an object to disk as a binary file.
/// </summary>
/// <param name="objectToSave">Object to Save</param>
/// <param name="path">Location of the file</param>
/// <returns>true if the save was succesful.</returns>
public static bool SaveAsBinary( object objectToSave, string path )
{
if ( objectToSave != null && CanBinarySerialize )
{
byte[] ba = ConvertToBytes( objectToSave );
if ( ba != null )
{
using ( FileStream fs = new FileStream( path, FileMode.OpenOrCreate, FileAccess.Write ) )
{
using ( BinaryWriter bw = new BinaryWriter( fs ) )
{
bw.Write( ba );
return true;
}
}
}
}
return false;
}
/// <summary>
/// Converts a .NET object to a string of XML. The object must be marked as Serializable or an exception
/// will be thrown.
/// </summary>
/// <param name="objectToConvert">Object to convert</param>
/// <returns>A xml string represting the object parameter. The return value will be null of the object is null</returns>
public static string ConvertToString( object objectToConvert )
{
string xml = null;
if ( objectToConvert != null )
{
//we need the type to serialize
Type t = objectToConvert.GetType();
XmlSerializer ser = new XmlSerializer( t );
//will hold the xml
using ( StringWriter writer = new StringWriter( CultureInfo.InvariantCulture ) )
{
ser.Serialize( writer, objectToConvert );
xml = writer.ToString();
writer.Close();
}
}
return xml;
}
public static void SaveAsXML( object objectToConvert, string path )
{
if ( objectToConvert != null )
{
//we need the type to serialize
Type t = objectToConvert.GetType();
XmlSerializer ser = new XmlSerializer( t );
//will hold the xml
using ( StreamWriter writer = new StreamWriter( path ) )
{
ser.Serialize( writer, objectToConvert );
writer.Close();
}
}
}
/// <summary>
/// Converts a byte array to a .NET object. You will need to cast this object back to its expected type.
/// If the array is null or empty, it will return null.
/// </summary>
/// <param name="byteArray">An array of bytes represeting a .NET object</param>
/// <returns>The byte array converted to an object or null if the value of byteArray is null or empty</returns>
public static object ConvertToObject( byte[] byteArray )
{
object convertedObject = null;
if ( CanBinarySerialize && byteArray != null && byteArray.Length > 0 )
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
using ( MemoryStream ms = new MemoryStream() )
{
ms.Write( byteArray, 0, byteArray.Length );
// Set the memory stream position to the beginning of the stream
//
ms.Position = 0;
if ( byteArray.Length > 4 )
convertedObject = binaryFormatter.Deserialize( ms );
ms.Close();
}
}
return convertedObject;
}
/// <summary>
/// Converts a string of xml to the supplied object type.
/// </summary>
/// <param name="xml">Xml representing a .NET object</param>
/// <param name="objectType">The type of object which the xml represents</param>
/// <returns>A instance of object or null if the value of xml is null or empty</returns>
public static object ConvertToObject( XmlNode node, Type objectType )
{
object convertedObject = null;
if ( node != null )
{
using ( StringReader reader = new StringReader( node.OuterXml ) )
{
XmlSerializer ser = new XmlSerializer( objectType );
convertedObject = ser.Deserialize( reader );
reader.Close();
}
}
return convertedObject;
}
public static object ConvertFileToObject( string path, Type objectType )
{
object convertedObject = null;
if ( path != null && path.Length > 0 )
{
using ( FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read ) )
{
XmlSerializer ser = new XmlSerializer( objectType );
convertedObject = ser.Deserialize( fs );
fs.Close();
}
}
return convertedObject;
}
/// <summary>
/// Converts a string of xml to the supplied object type.
/// </summary>
/// <param name="xml">Xml representing a .NET object</param>
/// <param name="objectType">The type of object which the xml represents</param>
/// <returns>A instance of object or null if the value of xml is null or empty</returns>
public static object ConvertToObject( string xml, Type objectType )
{
object convertedObject = null;
if ( !string.IsNullOrEmpty( xml ) )
{
using ( StringReader reader = new StringReader( xml ) )
{
XmlSerializer ser = new XmlSerializer( objectType );
convertedObject = ser.Deserialize( reader );
reader.Close();
}
}
return convertedObject;
}
public static object LoadBinaryFile( string path )
{
if ( !File.Exists( path ) )
return null;
using ( FileStream fs = new FileStream( path, FileMode.Open, FileAccess.Read ) )
{
BinaryReader br = new BinaryReader( fs );
byte[] ba = new byte[ fs.Length ];
br.Read( ba, 0, ( int )fs.Length );
return ConvertToObject( ba );
}
}
/// <summary>
/// Creates a NameValueCollection from two string. The first contains the key pattern and the second contains the values
/// spaced according to the kys
/// </summary>
/// <param name="keys">Keys for the namevalue collection</param>
/// <param name="values">Values for the namevalue collection</param>
/// <returns>A NVC populated based on the keys and vaules</returns>
/// <example>
/// string keys = "key1:S:0:3:key2:S:3:2:";
/// string values = "12345";
/// This would result in a NameValueCollection with two keys (Key1 and Key2) with the values 123 and 45
/// </example>
public static NameValueCollection ConvertToNameValueCollection( string keys, string values )
{
NameValueCollection nvc = new NameValueCollection();
if ( keys != null && values != null && keys.Length > 0 && values.Length > 0 )
{
char[] splitter = new char[ 1 ] { ':' };
string[] keyNames = keys.Split( splitter );
for ( int i = 0; i < ( keyNames.Length / 4 ); i++ )
{
int start = int.Parse( keyNames[ ( i * 4 ) + 2 ], CultureInfo.InvariantCulture );
int len = int.Parse( keyNames[ ( i * 4 ) + 3 ], CultureInfo.InvariantCulture );
string key = keyNames[ i * 4 ];
//Future version will support more complex types
if ( ( ( keyNames[ ( i * 4 ) + 1 ] == "S" ) && ( start >= 0 ) ) && ( len > 0 ) && ( values.Length >= ( start + len ) ) )
{
nvc[ key ] = values.Substring( start, len );
}
}
}
return nvc;
}
/// <summary>
/// Creates a the keys and values strings for the simple serialization based on a NameValueCollection
/// </summary>
/// <param name="nvc">NameValueCollection to convert</param>
/// <param name="keys">the ref string will contain the keys based on the key format</param>
/// <param name="values">the ref string will contain all the values of the namevaluecollection</param>
public static void ( NameValueCollection nvc, ref string keys, ref string values )
{
if ( nvc == null || nvc.Count == 0 )
return;
StringBuilder sbKey = new StringBuilder();
StringBuilder sbValue = new StringBuilder();
int index = 0;
foreach ( string key in nvc.AllKeys )
{
if ( key.IndexOf( ':' ) != -1 )
throw new ArgumentException( "ExtendedAttributes Key can not contain the character \":\"" );
string v = nvc[ key ];
if ( !string.IsNullOrEmpty( v ) )
{
sbKey.AppendFormat( "{0}:S:{1}:{2}:", key, index, v.Length );
sbValue.Append( v );
index += v.Length;
}
}
keys = sbKey.ToString();
values = sbValue.ToString();
}
}
}
F. 實體類實現序列化介面,才能存到資料庫嗎那為什麼。。
你用habernate保存數據,只要XML文件配置好了,實體類DAO層都沒錯,調用SAVE方法 然後COMMIT就可以保存數據。
序列化主要就是把你要保存的數據,轉換成位元組碼的形式,反序列化就是把位元組碼變成數據。
你直接把數據通過本機伺服器提交給硬碟,確實不需要序列化。
但是你在網路傳輸的時候就不行了,你傳給別人一個東西,它接收了所有的位元組碼之後,卻不知道你原本傳的是什麼對象,也就沒法把這個東西按照原始去解析。
你序列化之後,在傳給對方,他接收到的時候會按照序列化特定的模式,給反序列化出來,也就是說你傳了什麼,對方接收的也是什麼,解析成功,可以正確使用方法以及屬性。
G. unity發布web怎麼處理結構體的序列化
實體類代碼 namespace XulieHua { [Serializable] public class Information { private string id; public string Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name