当前位置:首页 » 网页前端 » web对实体类进行序列化
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

web对实体类进行序列化

发布时间: 2023-01-12 18:38:35

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