|
2011年3月8日
beans.xml  beans<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="cc.rm" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--DataSource -->
<bean id="sf"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>cc.rm.vo</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sf"></property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sf" />
</bean>
<aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * cc.rm.*.*(..))" />
<aop:advisor pointcut-ref="bussinessService"
advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>
jdbc.properties
 propertiesjdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ll
jdbc.username=root
jdbc.password=1244
在web.xml里加入
 web.xml<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/:beans.xml,</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
需要先安裝ODBC,才可以使用ODBC連接方式連接數(shù)據(jù)庫(kù) 下載地址:mysql-connector-odbc-5.1.8-win32.msi 1 2 3 4 5 
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
<?xml version='1.0' encoding='gb2312'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--顯示執(zhí)行的SQL語(yǔ)句-->
<property name="show_sql">true</property>
<!--連接字符串-->
<property name="connection.url">jdbc:mysql://localhost:3306/Test</property>
<!--連接數(shù)據(jù)庫(kù)的用戶名-->
<property name="connection.username">sa</property>
<!--數(shù)據(jù)庫(kù)用戶密碼-->
<property name="connection.password">sa</property>
<!--數(shù)據(jù)庫(kù)驅(qū)動(dòng)-->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--JDBC連接池(使用內(nèi)置的連接池)-->
<property name="connection.pool_size">1</property>
<!--設(shè)置Hibernate自動(dòng)管理上下文的策略-->
<property name="current_session_context_class">thread</property>
<!--選擇使用的方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--在啟動(dòng)時(shí)刪除并重新創(chuàng)建數(shù)據(jù)庫(kù)-->
<property name="hbm2ddl.auto">create</property>
<mapping resource="events/User.hbm.xml"/>
<mapping resource="events/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
一、設(shè)計(jì)過(guò)程包含五個(gè)主要步驟。
第 1 步:確定實(shí)體和關(guān)系
第 2 步:確定所需數(shù)據(jù)
第 3 步:規(guī)范化數(shù)據(jù)
第 4 步:解析關(guān)系
第 5 步:驗(yàn)證設(shè)計(jì)
二、閱讀別人的概念模型圖:
不管是從左到右讀取還是從右到左讀取,下面的規(guī)則都會(huì)使讀取這些圖示變得容易:讀取 (1) 第一個(gè)實(shí)體的名稱,(2) 第一個(gè)實(shí)體 旁邊的角色,(3) 到第二個(gè)實(shí)體 的連接的基數(shù),(4) 第二個(gè)實(shí)體的名稱。
三、確定所需數(shù)據(jù)(實(shí)體屬性的設(shè)計(jì))需要注意的:
確定支持?jǐn)?shù)據(jù)時(shí),一定要參考前面確定的活動(dòng)以了解將如何訪問(wèn)這些數(shù)據(jù)。
例如,在某些情況下可能需要按雇員的名字列出雇員,而在另一些情況下可能需要按姓氏列出。要滿足這兩種需要,應(yīng)創(chuàng)建一個(gè) First Name 屬性和一個(gè) Last Name 屬性,而不應(yīng)創(chuàng)建一個(gè)既包含名字又包含姓氏的屬性。將姓氏和名字分開后,以后可以創(chuàng)建兩個(gè)索引,分別適用于這兩項(xiàng)任務(wù)。
請(qǐng)選擇一致的名稱。使用一致的名稱可以使數(shù)據(jù)庫(kù)便于維護(hù),并且便于閱讀報(bào)告和輸出窗口。
例如,如果一個(gè)屬性使用了縮略名稱,如 Emp_status,則另一個(gè)屬性不應(yīng)使用完整名稱,如 Employee_ID。應(yīng)使名稱保持一致,如 Emp_status 和 Emp_ID。
在這個(gè)階段,數(shù)據(jù)是否與正確的實(shí)體相關(guān)聯(lián)并不十分重要。您可以根據(jù)自己的判斷進(jìn)行設(shè)計(jì)。在下一節(jié)中,將對(duì)設(shè)計(jì)進(jìn)行測(cè)試,檢查您的判斷是否正確。
四、規(guī)范化是指一系列測(cè)試,通過(guò)這些測(cè)試可以消除冗余的數(shù)據(jù),并確保數(shù)據(jù)與正確的實(shí)體或關(guān)系相關(guān)聯(lián)。共有五項(xiàng)測(cè)試。本節(jié)介紹其中前三項(xiàng)測(cè)試。這三項(xiàng)測(cè)試最重要,因此也最常使用。
五、范式:
數(shù)據(jù)規(guī)范化包括幾項(xiàng)測(cè)試。數(shù)據(jù)在通過(guò)了第一項(xiàng)測(cè)試后,我們認(rèn)為它滿足第一范式;通過(guò)了第二項(xiàng)測(cè)試后,它滿足第二范式;通過(guò)了第三項(xiàng)測(cè)試后,則滿足第三范式。
六、標(biāo)識(shí)符是唯一地標(biāo)識(shí)實(shí)體中各行的一組屬性,至少由一個(gè)屬性組成。
七、解析關(guān)系:
執(zhí)行完規(guī)范化過(guò)程后,設(shè)計(jì)幾乎就完成了。唯一還需要做的事情就是生成與概念數(shù)據(jù)模型相對(duì)應(yīng)的物理數(shù)據(jù)模型。這個(gè)過(guò)程也稱作解析關(guān)系,因?yàn)槠渲猩婕暗拇罅抗ぷ骶褪菍⒏拍钅P椭械年P(guān)系轉(zhuǎn)換為相應(yīng)的表和外鍵關(guān)系。
八、概念數(shù)據(jù)模型可以簡(jiǎn)化設(shè)計(jì)過(guò)程,因?yàn)樗鼘⒋罅考?xì)節(jié)隱藏起來(lái)。例如,多對(duì)多關(guān)系總會(huì)生成一個(gè)額外的表和兩個(gè)外鍵引用。在概念數(shù)據(jù)模型中,通常可以用一個(gè)連接來(lái)標(biāo)識(shí)這類結(jié)構(gòu)。
九、域(用戶定義的數(shù)據(jù)類型)
十、數(shù)據(jù)庫(kù)對(duì)象的定義構(gòu)成了數(shù)據(jù)庫(kù)模式:您可以將模式看做一個(gè)空數(shù)據(jù)庫(kù)。(是否可以理解成C#的命名空間或java里的包概念)
十一、
這個(gè)插件在JQuery1.5.1版下無(wú)法使用。 項(xiàng)目地址:http://dev.iceburg.net/jquery/tableEditor/demo.php html文件:  html<table id="editableTable" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th name="ID">ID</th>
<th name="first">First Name</th>
<th name="last">Last Name</th>
<th>Phone</th>
<th name="city">City</th>
<th name="email">Email</th>
</tr>
<tr>
<td><key>233</key> <button class="eventLink">edit</button></td>
<td><input type="text" name="XXXX" val="YYYY"></input></td>
<td>XXX</td>
<td><input type="checkbox" checked name="zzTop"></input></td>
<td><input type="checkbox" name="yyy"></input></td>
<td><select name="yyy"><option>XXX</option><option SELECTED>YYY</option></select></td>
</tr>
</thead>
<tbody>
<tr>
<td><key>1</key> <button class="eventLink">edit</button></td>
<td>Brice</td>
<td>Burgess</td>
<td>(800)768-5283</td>
<td>Milwaukee</td>
<td>b@b.com</td>
</tr>
<tr>
<td><key>2</key> <button class="eventLink">edit</button></td>
<td>Christian</td>
<td>Bach</td>
<td>(800)768-6288</td>
<td>Chicago</td>
<td>c@c.com</td>
</tr>
<tr>
<td><key>3</key> <button class="eventLink">edit</button></td>
<td>Abe</td>
<td>Lincoln</td>
<td>(800)223-2331</td>
<td>Washington D.C.</td>
<td>l@l.com</td>
</tr>
<tr>
<td><key>8</key> <button class="eventLink">edit</button></td>
<td>Sam Lightning</td>
<td>Hopkings</td>
<td>(800)728-1221</td>
<td>Houston</td>
<td>s@s.com</td>
</tr>
<tr>
<td><key>15</key> <button class="eventLink">edit</button></td>
<td>Rudyard</td>
<td>Kipling</td>
<td>(512)121-1280</td>
<td>London</td>
<td>r@r.com</td>
</tr>
</tbody>
</table>
js文件
 js<script type="text/javascript">
$().ready(function() {
$("#editableTable").tableSorter({
sortClassAsc: 'headerSortUp', // class name for ascending sorting action to header
sortClassDesc: 'headerSortDown', // class name for descending sorting action to header
headerClass: 'header', // class name for headers (th's)
disableHeader: 'ID' // DISABLE Sorting on ID
}).tableEditor({
EDIT_HTML: 'edit',
SAVE_HTML: 'save',
EVENT_LINK_SELECTOR: 'button.eventLink',
FUNC_UPDATE: 'updateTable'
});
document.counter = 0;
});
function updateTable(o) {
document.counter++;
if ((document.counter%2) == 0) {
// restore row
alert('Update failed. Row restore.');
$.tableEditor.lib.restoreRow(o.row,o.original);
}
else
alert('Update Success');
return true;
}
</script>
從DLOG4J讀到的Request的工具類:  java/*
* RequestUtils.java
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Author: Winter Lau (javayou@gmail.com)
* http://dlog4j.sourceforge.net
*/
package com.liusoft.dlog4j.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.liusoft.dlog4j.Globals;
/**
* 用于Request的工具類
* @author Winter Lau
*/
public class RequestUtils extends org.apache.struts.util.RequestUtils{
final static Log log = LogFactory.getLog(RequestUtils.class);
private static Properties header_map;
private static String default_mobile;
static{
InputStream in = RequestUtils.class.getResourceAsStream("/com/liusoft/dlog4j/util/mobile_match.properties");
header_map = new Properties();
try{
header_map.load(in);
default_mobile = header_map.getProperty("empty");
}catch(IOException e){
log.error("加載手機(jī)號(hào)碼匹配策略文件/mobile_match.conf失敗",e);
}
}
public static boolean isMultipart(HttpServletRequest req) {
return ((req.getContentType() != null) && (req.getContentType()
.toLowerCase().startsWith("multipart")));
}
/**
* 獲取FCKUpload過(guò)程中生成的會(huì)話ID
* @return
*/
public static String getDlogSessionId(HttpServletRequest req){
//優(yōu)先從Cookie中獲取ssn_id值
String ssn_id = null;
Cookie cok = RequestUtils.getCookie(req, Globals.SESSION_ID_KEY_IN_COOKIE);
if(cok != null){
ssn_id = cok.getValue();
}
if(StringUtils.isEmpty(ssn_id)){
//如果Cookie得不到則從服務(wù)器的會(huì)話中讀取
HttpSession ssn = req.getSession(false);
if (ssn != null)
ssn_id = ssn.getId();
}
return ssn_id;
}
/**
* 清除FCKUpload過(guò)程中生成的Cookie
* @param req
* @param res
*/
public static void clearDlogSessionId(HttpServletRequest req, HttpServletResponse res){
Cookie cok = RequestUtils.getCookie(req, Globals.SESSION_ID_KEY_IN_COOKIE);
if(cok != null){
cok.setMaxAge(0);
res.addCookie(cok);
}
}
/**
* 獲取COOKIE
*
* @param name
*/
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if(cookies == null)
return null;
for (int i = 0; i < cookies.length; i++) {
if (name.equals(cookies[i].getName())) {
return cookies[i];
}
}
return null;
}
/**
* 設(shè)置COOKIE
*
* @param name
* @param value
* @param maxAge
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
String serverName = request.getServerName();
String domain = getDomainOfServerName(serverName);
if(domain!=null && domain.indexOf('.')!=-1){
cookie.setDomain('.' + domain);
}
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* 獲取用戶訪問(wèn)URL中的根域名
* 例如: www.dlog.cn -> dlog.cn
* @param req
* @return
*/
public static String getDomainOfServerName(String host){
if(StringUtils.isIPAddr(host))
return null;
String[] names = StringUtils.split(host, '.');
int len = names.length;
if(len>=2)
return names[len-2]+'.'+names[len-1];
return host;
}
public static void main(String[] args){
String host = "127.0.0.1";
System.out.println("DOMAIN: " + getDomainOfServerName(host));
host = "dlog.cn";
System.out.println("DOMAIN: " + getDomainOfServerName(host));
host = "abc.mail.dlog.cn";
System.out.println("DOMAIN: " + getDomainOfServerName(host));
}
/**
* 從URL地址中解析出URL前綴,例如
* http://wap.mo168.com:8081/index.jsp -> http://wap.mo168.com:8081
* @param req
* @return
*/
public static String getUrlPrefix(HttpServletRequest req){
StringBuffer url = new StringBuffer(req.getScheme());
url.append("://");
url.append(req.getServerName());
int port = req.getServerPort();
if(port!=80){
url.append(":");
url.append(port);
}
return url.toString();
}
/**
* 獲取訪問(wèn)的URL全路徑
* @param req
* @return
*/
public static String getRequestURL(HttpServletRequest req){
StringBuffer url = new StringBuffer(req.getRequestURI());
String param = req.getQueryString();
if(param!=null){
url.append('?');
url.append(param);
}
String path = url.toString();
return path.substring(req.getContextPath().length());
}
/**
* 打印所有的頭信息
* @param out
* @param req
*/
public static void dumpHeaders(PrintStream out, HttpServletRequest req){
Enumeration names = req.getHeaderNames();
while(names.hasMoreElements()){
String name = (String)names.nextElement();
out.println(name+"="+req.getHeader(name));
}
}
/**
* 從請(qǐng)求中解析手機(jī)號(hào)碼
* @param req
* @return
*/
public static String getRequestMobile(HttpServletRequest req){
String mobile = default_mobile;
Iterator keys = header_map.keySet().iterator();
while(keys.hasNext()){
String header = (String)keys.next();
String value = getHeader(req,header);
if(value!=null){
String pattern = (String)header_map.get(header);
MessageFormat mf = new MessageFormat(pattern);
try{
Object[] vs = mf.parse(value);
mobile = (String)vs[0];
if(mobile.startsWith("86"))
mobile = mobile.substring(2);
break;
}catch(Exception e){
log.warn("解析header失敗",e);
dumpHeaders(req, System.err);
continue;
}
}
}
return mobile;
}
/**
* 獲取header信息,名字大小寫無(wú)關(guān)
* @param req
* @param name
* @return
*/
public static String getHeader(HttpServletRequest req, String name){
String value = req.getHeader(name);
if(value!=null)
return value;
Enumeration names = req.getHeaderNames();
while(names.hasMoreElements()){
String n = (String)names.nextElement();
if(n.equalsIgnoreCase(name)){
return req.getHeader(n);
}
}
return null;
}
/**
* 打印所有頭信息
* @param req
* @param out
*/
public static void dumpHeaders(HttpServletRequest req, PrintStream out){
Enumeration hds = req.getHeaderNames();
out.println("=============== HEADERS ===============");
while(hds.hasMoreElements()){
String name = (String)hds.nextElement();
out.println(name+"="+req.getHeader(name));
}
}
/**
* 判斷手機(jī)是否支持某種類型的格式
* @param req
* @param contentType
* @return
*/
public static boolean support(HttpServletRequest req, String contentType){
String accept = getHeader(req, "accept");
if(accept!=null){
accept = accept.toLowerCase();
return accept.indexOf(contentType.toLowerCase())!=-1;
}
return false;
}
/**
* 判斷瀏覽器是否與Mozilla兼容
* @param req
* @return
*/
public static boolean isMozillaCompatible(HttpServletRequest req){
String user_agent = req.getHeader("user-agent");
return user_agent==null || user_agent.indexOf("Mozilla")!=-1;
}
/**
* 獲取瀏覽器提交的整形參數(shù)
* @param param
* @param defaultValue
* @return
*/
public static int getParam(HttpServletRequest req, String param, int defaultValue){
try{
String value = req.getParameter(param);
int idx = value.indexOf('#');
if(idx!=-1)
value = value.substring(0,idx);
return Integer.parseInt(value);
}catch(Exception e){}
return defaultValue;
}
/**
* 獲取瀏覽器提交的字符串參數(shù)
* @param param
* @param defaultValue
* @return
*/
public static String getParam(HttpServletRequest req, String param, String defaultValue){
String value = req.getParameter(param);
return (StringUtils.isEmpty(value))?defaultValue:value;
}
}
 java/*
* SiteAction.java
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Author: Winter Lau
* http://dlog4j.sourceforge.net
*/
package com.liusoft.dlog4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
/**
* DLOG在安全方面的一些處理方法
* 敏感詞匯表:/WEB-INF/conf/illegal_glossary.dat
*
* @author Winter Lau
*/
public class DLOGSecurityManager {
/**
* 初始化
* @param sc
* @throws IOException
*
* @see com.liusoft.dlog4j.servlet.DLOG_ActionServlet#init()
*/
public static void init(ServletContext sc) throws IOException {
IllegalGlossary.init(sc);
}
public static void destroy(){
IllegalGlossary.destroy();
}
/**
* 敏感字匯
* @author Winter Lau
*/
public static class IllegalGlossary {
private final static String file_glossary = "/WEB-INF/conf/illegal_glossary.dat";
private static List glossary = null;
public static void init(ServletContext sc) throws IOException {
glossary = new ArrayList(1000);
if(sc!=null)
loadIllegalGlossary(sc);
}
public static void destroy(){
if(glossary!=null)
glossary.clear();
}
/**
* 加載敏感詞匯表
* @param sc
* @throws IOException
*/
private synchronized static void loadIllegalGlossary(ServletContext sc) throws IOException {
InputStream in = sc.getResourceAsStream(file_glossary);
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(in));
do{
String line = reader.readLine();
if(line==null)
break;
glossary.add(line.trim());
}while(true);
}finally{
in.close();
}
}
/**
* 自動(dòng)將敏感詞匯用XXX替換
*
* @param content
* @return
*/
public static String autoGlossaryFiltrate(String content) {
if(StringUtils.isEmpty(content))
return content;
for (int i = 0; i < glossary.size(); i++) {
String word = (String)glossary.get(i);
content = StringUtils.replace(content, word, StringUtils
.repeat("X", word.length()));
}
return content;
}
/**
* 判斷是否存在非法內(nèi)容
* @param content
* @return
*/
public static boolean existIllegalWord(String content){
if(StringUtils.isEmpty(content))
return false;
for (int i = 0; i < glossary.size(); i++) {
String word = (String) glossary.get(i);
if(content.indexOf(word)>=0)
return true;
}
return false;
}
/**
* 刪除內(nèi)容中存在的關(guān)鍵字
* @param content
* @return
*/
public static String deleteIllegalWord(String content){
if(StringUtils.isEmpty(content))
return content;
for (int i = 0; i < glossary.size(); i++) {
String word = (String) glossary.get(i);
content = StringUtils.remove(content, word);
}
return content;
}
}
public static void main(String[] args) throws IOException{
init(null);
String text = "中華人民共和國(guó)國(guó)家主席毛澤東,我們叫他毛主席";
System.out.println(IllegalGlossary.autoGlossaryFiltrate(text));
}
}
這個(gè)類,是從DLOG4J上學(xué)到的。
 sqlDROP DATABASE IF EXISTS `local` ;
CREATE DATABASE `local`;
use `local` ;
DROP TABLE IF EXISTS actionmanager;
CREATE TABLE actionmanager(
actionid INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
actionName VARCHAR(255) NOT NULL ,
action VARCHAR(255) NOT NULL,
createDate DATE,
viewmode INT DEFAULT 0
#index inx(`action`)
)type=InnoDB;
DROP TABLE IF EXISTS actioncolumn ;
CREATE TABLE actioncolumn(
actioncolumnid INT AUTO_INCREMENT NOT NULL PRIMARY KEY ,
actioncolumnname VARCHAR(255) NOT NULL
)type=InnoDB;
DROP TABLE IF EXISTS groupmanager;
CREATE TABLE groupmanager(
groupid INT AUTO_INCREMENT NOT NULL PRIMARY KEY ,
groupname VARCHAR(255) NOT NULL,
groupinfo VARCHAR(255) DEFAULT NULL,
masterid INT NOT NULL, #who created this group
mastername VARCHAR(255),
createdate DATE
)type=InnoDB;
DROP TABLE IF EXISTS master;
CREATE TABLE master(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
sex VARCHAR(255) NOT NULL ,
position VARCHAR(255) NOT NULL,
masterid INT , #whoe created this master
mastername VARCHAR(255),
createdate DATE
)type=InnoDB;
DROP TABLE IF EXISTS actiongroup ;
CREATE TABLE actiongroup(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`action` VARCHAR(255) NOT NULL,
groupid INT NOT NULL ,
masterid int NOT NULL,
mastername VARCHAR(255) NOT NULL ,
createdate DATE,
index inx_ag(`action`)
)type=InnoDB;
DROP TABLE IF EXISTS mastergroup ;
CREATE TABLE mastergroup(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
masterid INT NOT NULL ,
groupid INT NOT NULL ,
masterid2 INT NOT NULL , # who created or modified this mastergroup
creatDate DATE
)type=InnoDB ;
##############action link group ######################
CREATE INDEX idx_actionmanager_action ON actionmanager(`action`);
CREATE INDEX idx_groupmanager_groupid ON groupmanager(`groupid`);
ALTER TABLE actiongroup
ADD CONSTRAINT fk_action
FOREIGN KEY (action) REFERENCES actionmanager(`action`)
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE actiongroup
ADD CONSTRAINT fk_groupid
FOREIGN KEY (groupid) REFERENCES groupmanager(`groupid`)
ON DELETE CASCADE ON UPDATE CASCADE;
##############action link master######################
CREATE INDEX idx_master_id ON master(`id`);
ALTER TABLE mastergroup
ADD CONSTRAINT fk_masterg_mid
FOREIGN KEY (masterid) REFERENCES master(`id`)
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE mastergroup
ADD CONSTRAINT fk_masterg_gid
FOREIGN KEY (groupid) REFERENCES groupmanager(`groupid`)
ON DELETE CASCADE ON UPDATE CASCADE;
1 --創(chuàng)建表
2 if exists(select * from sysobjects where name='user' and type='U') drop table [user] ;
3 create table [user](
4 id int identity(1,1) , --自增字段
5 name varchar(50) ,
6 pwd varchar(50) ,
7 constraint pk_user_id primary key(id) --主鍵
8 --constraint pk_user_id primary key(id,[name])
9 );
10
11 -- 變量的聲明,sql里面聲明變量時(shí)必須在變量前加@符號(hào)
12 DECLARE @I INT
13
14 -- 變量的賦值,變量賦值時(shí)變量前必須加set
15 SET @I = 30
16
17 -- 聲明多個(gè)變量
18 DECLARE @s varchar(10),@a INT
19
20 -- Sql 里if語(yǔ)句
21 IF 條件 BEGIN
22 執(zhí)行語(yǔ)句
23 END
24 ELSE BEGIN
25 執(zhí)行語(yǔ)句
26 END
27
28 DECLARE @d INT
29 set @d = 1
30
31 IF @d = 1 BEGIN
32
33 -- 打印
34 PRINT '正確'
35 END
36 ELSE BEGIN
37 PRINT '錯(cuò)誤'
38 END
39
40
41 -- Sql 里的多條件選擇語(yǔ)句.
42 DECLARE @iRet INT, @PKDisp VARCHAR(20)
43 SET @iRet = 1
44 Select @iRet =
45 CASE
46 WHEN @PKDisp = '一' THEN 1
47 WHEN @PKDisp = '二' THEN 2
48 WHEN @PKDisp = '三' THEN 3
49 WHEN @PKDisp = '四' THEN 4
50 WHEN @PKDisp = '五' THEN 5
51 ELSE 100
52 END
53
54 -- 循環(huán)語(yǔ)句
55 WHILE 條件 BEGIN
56 執(zhí)行語(yǔ)句
57 END
58
59 DECLARE @i INT
60 SET @i = 1
61 WHILE @i<1000000 BEGIN
62 set @i=@i+1
63 END
64 -- 打印
65 PRINT @i
66
67
68 -- TRUNCATE 刪除表中的所有行,而不記錄單個(gè)行刪除操作,不能帶條件
69
70 /*
71 TRUNCATE TABLE 在功能上與不帶 Where 子句的 Delete 語(yǔ)句相同:二者均刪除表中的全部行
72
73 。但 TRUNCATE TABLE 比 Delete 速度快,且使用的系統(tǒng)和事務(wù)日志資源少。
74 Delete 語(yǔ)句每次刪除一行,并在事務(wù)日志中為所刪除的每行記錄一項(xiàng)。TRUNCATE TABLE 通過(guò)
75
76 釋放存儲(chǔ)表數(shù)據(jù)所用的數(shù)據(jù)頁(yè)來(lái)刪除數(shù)據(jù),并且只在事務(wù)日志中記錄頁(yè)的釋放。
77 TRUNCATE TABLE 刪除表中的所有行,但表結(jié)構(gòu)及其列、約束、索引等保持不變。新行標(biāo)識(shí)所用
78
79 的計(jì)數(shù)值重置為該列的種子。如果想保留標(biāo)識(shí)計(jì)數(shù)值,請(qǐng)改用 Delete。如果要?jiǎng)h除表定義及其數(shù)據(jù),請(qǐng)
80
81 使用 Drop TABLE 語(yǔ)句。
82 對(duì)于由 FOREIGN KEY 約束引用的表,不能使用 TRUNCATE TABLE,而應(yīng)使用不帶 Where 子句的
83
84 Delete 語(yǔ)句。由于 TRUNCATE TABLE 不記錄在日志中,所以它不能激活觸發(fā)器。
85 TRUNCATE TABLE 不能用于參與了索引視圖的表。
86 示例
87 下例刪除 authors 表中的所有數(shù)據(jù)。*/
88
89 TRUNCATE TABLE authors
90
91
92 -- Select INTO 從一個(gè)查詢的計(jì)算結(jié)果中創(chuàng)建一個(gè)新表。 數(shù)據(jù)并不返回給客戶端,這一點(diǎn)和普通的
93 -- Select 不同。 新表的字段具有和 Select 的輸出字段相關(guān)聯(lián)(相同)的名字和數(shù)據(jù)類型。
94
95 select * into NewTable
96 from Uname
97
98
99 -- Insert INTO Select
100 -- 表ABC必須存在
101 -- 把表Uname里面的字段Username復(fù)制到表ABC
102 Insert INTO ABC Select Username FROM Uname
103
104 -- 創(chuàng)建臨時(shí)表
105 Create TABLE #temp(
106 UID int identity(1, 1) PRIMARY KEY,
107 UserName varchar(16),
108 Pwd varchar(50),
109 Age smallint,
110 Sex varchar(6)
111 )
112 -- 打開臨時(shí)表
113 Select * from #temp
114
115 -- 存儲(chǔ)過(guò)程
116 -- 要?jiǎng)?chuàng)建存儲(chǔ)過(guò)程的數(shù)據(jù)庫(kù)
117 Use Test
118 -- 判斷要?jiǎng)?chuàng)建的存儲(chǔ)過(guò)程名是否存在
119 if Exists(Select name From sysobjects Where name='csp_AddInfo' And
120
121 type='P')
122 -- 刪除存儲(chǔ)過(guò)程
123 Drop Procedure dbo.csp_AddInfo
124 Go
125
126
127 -- 創(chuàng)建存儲(chǔ)過(guò)程
128 Create Proc dbo.csp_AddInfo
129 -- 存儲(chǔ)過(guò)程參數(shù)
130 @UserName varchar(16),
131 @Pwd varchar(50),
132 @Age smallint,
133 @Sex varchar(6)
134 AS
135 -- 存儲(chǔ)過(guò)程語(yǔ)句體
136 insert into Uname (UserName,Pwd,Age,Sex)
137 values (@UserName,@Pwd,@Age,@Sex)
138 RETURN
139 -- 執(zhí)行
140 GO
141
142 -- 執(zhí)行存儲(chǔ)過(guò)程
143 EXEC csp_AddInfo 'Junn.A','123456',20,'男';
144 修改自:http://blog.csdn.net/mx1029/archive/2007/07/06/1680910.aspx
1、 ServletFileUpload.isMultipartContent(request) 檢測(cè)request中是否包含有multipart內(nèi)容 2、如果有,生成DiskFileItemFactory工廠將進(jìn)行相關(guān)的設(shè)置 DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("d:/")); 3、生成上傳ServletFileUpload類,并將DiskFileFactory工廠傳給它,并對(duì)ServletFileUpload進(jìn)行配置 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); 4、從request得到上傳的文件列表 // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); 5、處理文件:寫入或者其他操作 while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File( filePath + fileName.substring(fileName .lastIndexOf("\\"))); } else { file = new File( filePath + fileName.substring(fileName .lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } } 說(shuō)明: FileItem接口是對(duì)用戶上傳文件的封裝 DiskFileItemFactory實(shí)現(xiàn)了FileItemFactory接口,主要方法有public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) ServletFileUpload從FileUpload繼承,而FileUpload又從FileUploadBase繼承,功能:分析傳入的request對(duì)象、得到文件列表FileItemIterator……
簡(jiǎn)明步驟 1、下載所需包:commons-FileUpload http://commons.apache.org/fileupload/ 依賴commons-IO包 commons-IO http://commons.apache.org/io/ 2、前端: 3、書寫Servlet 4、web.xml中配置上傳文件存放地址 5、web.xml中配置Servlet 一、前端
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
二、書寫Servlet
 web.xml// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
三、web.xml中配置上傳文件存放地址
 web.xml<web-app>
....
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>
四、web.xml中配置Servlet
 web.xml<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
原文地址:http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm
一個(gè)Servlet可以通過(guò)HTML表單標(biāo)簽將文件上傳到服務(wù)器。支待上傳的有文本、圖像及任何文件。
創(chuàng)建文件上傳表單:
下面的html代碼創(chuàng)建了一個(gè)上傳表單。創(chuàng)建過(guò)程需要注意以下幾點(diǎn):
l form標(biāo)簽中的method屬性必須設(shè)置為POST,即GET方法是不可以的。
l form標(biāo)簽中的enctype屬性應(yīng)該設(shè)置為multipart/form-data。
l from標(biāo)簽中的action屬性應(yīng)該與服務(wù)器后臺(tái)的servlet映射路徑相同。接下來(lái)的實(shí)例,我們將使用UploadServlet實(shí)現(xiàn)文件上傳。
l 要上傳一個(gè)文件,你應(yīng)該使用一個(gè)<input type=”file”.../>標(biāo)記。要多個(gè)文件上傳,必須包含多個(gè)具有不同的名稱屬性值的<input type=”file”.../>標(biāo)記。The browser associates a Browse button with each of them。
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
|
以上代碼將得到以下效果。你可以在本地PC上選擇一個(gè)文件。當(dāng)你點(diǎn)擊“Upload File”,表單將會(huì)隨著你選擇的文件一起被提交。
后臺(tái)servlet:
以下UploadServlet servlet將接收上傳的文件并將其保存入<Tomcat-installation-directory>/webapps/data文件夾。這個(gè)文件夾的名稱可以通過(guò)外部配置文件web.xml中的context-param元素內(nèi)容增加。代碼如下:
<web-app>
....
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:"apache-tomcat-5.5.29"webapps"data"
</param-value>
</context-param>
....
</web-app>
|
以下是實(shí)現(xiàn)了多文件同時(shí)上傳功能的UploadServlet。在此之前您必須確定以下幾點(diǎn):
l 以下實(shí)例依賴F ileUpload類,所以您須將最新版的commons-fileupload.x.x.jar放到您的classpath下。可以從這里下載:http://commons.apache.org/fileupload/。
l FileUpload類依賴于Commons IO包,所以您須將最新版commons-fileupload.x.x.jar放到您的classpath下??梢詮倪@里下載:http://commons.apache.org/io/。
l 在測(cè)試以下例子的時(shí)候,您應(yīng)該上傳小于maxFileSize的文件,否則無(wú)法上傳。
l 事先確定你已經(jīng)建議好文件夾:c:"temp和c:"apache-tomcat-5.5.29"webapps"data。
// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:""temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("""") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf(""""))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("""")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
|
編譯并運(yùn)行Servlet
編譯以上UploadServlet并在web.xml中創(chuàng)建必須的實(shí)體,如下:
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
|
現(xiàn)在可以嘗試使用你創(chuàng)建的HTML表單上傳文件。當(dāng)你訪問(wèn)http://localhost:8080/UploadFile.htm,瀏覽器里將會(huì)顯示如下效果,您可以從本地上傳你想要上傳的任何文件。
如果您的servlet腳本運(yùn)行成功,您的文件上傳在c:"apache-tomcat-5.5.29"webapps"data"directory文件夾。
1、取得系統(tǒng)Properties,并配置 Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); // smtp協(xié)議 props.setProperty("mail.smtp.host", m_server); // 服務(wù)器地址 props.setProperty("mail.smtp.port", "" + m_port); // 端口號(hào) props.setProperty("mail.smtp.auth", "true"); //// 認(rèn)證信息 2、將取得Session javax.mail.Session sess = javax.mail.Session.getDefaultInstance(props); 3、實(shí)例MimeMessage類,然后設(shè)置收件人、主題、發(fā)件日期 MimeMessage msg = new MimeMessage(sess); msg.setFrom(new InternetAddress(m_from)); // 發(fā)件人 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(m_to)); //收件人 msg.setSubject(m_subject); //主題 msg.setSentDate(new Date()); //發(fā)件日期 4、向MimeMessage中添加文本內(nèi)容及附件 MimeMultipart content = new MimeMultipart();// 文本內(nèi)容 MimeBodyPart part = new MimeBodyPart(); //part還需要加入頭,類型之類的屬性 content.addBodyPart(part); part = new MimeBodyPart(); //這里是加入附件 FileDataSource fds = new FileDataSource(filename); part.setDataHandler(new DataHandler(fds)); part.setFileName(MimeUtility.encodeText(fds.getName())); content.addBodyPart(part); msg.setContent(content); //設(shè)置并保存 msg.saveChanges(); 5、使用Session取得Transport Transport trans = sess.getTransport(); 6、使用Transport連接服務(wù)器 trans.connect(m_server, m_user, m_pass); 7、發(fā)送郵件并關(guān)閉 trans.sendMessage(msg, InternetAddress.parse(m_to)); trans.close();
1、java對(duì)象序列化不保存對(duì)象中的靜態(tài)變量  serpublic class Test implements Serializable {
private static final long serialVersionUID = 1L;
public static int staticVar = 5;
public static void main(String[] args) {
try {
//初始時(shí)staticVar為5
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("result.obj"));
out.writeObject(new Test());
out.close();
//序列化后修改為10
Test.staticVar = 10;
ObjectInputStream oin = new ObjectInputStream(new FileInputStream(
"result.obj"));
Test t = (Test) oin.readObject();
oin.close();
//再讀取,通過(guò)t.staticVar打印新的值
System.out.println(t.staticVar);//10
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2、虛擬機(jī)是否允許反序列化,不僅取決于類路徑和功能代碼是否一致,一個(gè)非常重要的一點(diǎn)是兩個(gè)類的序列化 ID 是否一致(就是 private static final long serialVersionUID = 1L)。
3、父類的序列化與transient關(guān)鍵字
只有子類和父類都實(shí)現(xiàn)了Serializable接口時(shí),對(duì)子類反序列化時(shí)才會(huì)將父類也序列化。反序列化過(guò)程是先反序列過(guò)父類對(duì)象再反序列化子類。而如果不想序列化某一個(gè)變量,則可以在定義變量時(shí)使用transient關(guān)鍵字。
 Parentimport java.io.Serializable;
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
public int pi = 2;
public String pstr ="pstr";
public transient String ts ;
}
 Son and mainimport java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Son extends Parent implements Serializable {
private static final long serialVersionUID = 1L;
public int si = 1;
public String sstr = " sstr";
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
String path = "d:" + File.separator + "son.dll";
Son s = new Son();
s.si = 2;
s.pi = 2;
s.ts = "ts"; // ts在父類中的定義使用transient關(guān)鍵字
ObjectOutputStream op = null;
ObjectInputStream oi = null;
op = new ObjectOutputStream(new FileOutputStream(new File(path)));
op.writeObject(s);
op.close();
oi = new ObjectInputStream(new FileInputStream(path));
Son s1 = (Son) oi.readObject();
System.out.println("父類中的String pstr:" + s1.pstr);
System.out.println("父類中的int pi:" + s1.pi);
System.out.println("子類中的int si:" + s1.si);
System.out.println("父類中的transient String ts :" + s1.ts);//
}
}
4、Java 序列化機(jī)制為了節(jié)省磁盤空間,具有特定的存儲(chǔ)規(guī)則,當(dāng)寫入文件的為同一對(duì)象時(shí),并不會(huì)再將對(duì)象的內(nèi)容進(jìn)行存儲(chǔ),而只是再次存儲(chǔ)一份引用。
從IBM DW 整理而來(lái)
http://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html#icomments
Class.froName(“cc.a.C”) 返回:C這個(gè)類的class(其實(shí)是這個(gè)類的字節(jié)碼) 作用:告訴jvm使用相應(yīng)的加載器,將C.class加載入jvm(至于加載到哪個(gè)位置,本人還不知道) 而Class.forName(“cc.a.C”).newInstance()則是實(shí)例化一個(gè)對(duì)象;而new關(guān)鍵的作用也是實(shí)例化一個(gè)對(duì)象 所以可以粗略的將這兩種實(shí)例化對(duì)象的方法等同。 當(dāng)然它們有不同的地方。 在網(wǎng)上看到別人是這樣區(qū)別的: newInstance: 弱類型。低效率。只能調(diào)用無(wú)參構(gòu)造。 new: 強(qiáng)類型。相對(duì)高效。能調(diào)用任何public構(gòu)造。
將myeclipes安裝目錄C:\Program Files\Genuitec\Common\plugins 所有的東西復(fù)制到eclipes安裝目錄的\plugins里,并覆蓋。 重新啟動(dòng)eclipes就可以了。
1、比較兩個(gè)對(duì)象是否類型相同 array1.getClass().getName().equals(array2.getClass().getName() 2、倒置(reverse)數(shù)組中的元素 int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } 3、得到數(shù)組的容器類型 array.getClass().getComponentType(); 4、lastIndex()這類方法的實(shí)現(xiàn) for (int i = startIndex; i >= 0; i--) { if (objectToFind.equals(array[i])) { return i; } } 5、isEmpty()這類方法的實(shí)現(xiàn)只要一句話,isNotEmpty方法依此推 return array == null || array.length == 0; 6、將兩個(gè)數(shù)組合并addAll boolean[] joinedArray = new boolean[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); 7、將新元素加入到數(shù)組中 int arrayLength = Array.getLength(array); Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); System.arraycopy(array, 0, newArray, 0, arrayLength); return newArray; 8、獲得數(shù)組長(zhǎng)度的方法 int arrayLength = Array.getLength(array); 9、以反射的方式獲得數(shù)組對(duì)象 Array.newInstance(array.getClass().getComponentType(), arrayLength + 1) 10、將某一元素從數(shù)組中移除 Object result = Array.newInstance(array.getClass().getComponentType(), getLength(array)- 1); System.arraycopy(array, 0, result, 0, index); if (index < length - 1) { System.arraycopy(array, index + 1, result, index, length - index - 1); }
|