|
2011年3月3日
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連接方式連接數據庫 下載地址: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>
<!--顯示執行的SQL語句-->
<property name="show_sql">true</property>
<!--連接字符串-->
<property name="connection.url">jdbc:mysql://localhost:3306/Test</property>
<!--連接數據庫的用戶名-->
<property name="connection.username">sa</property>
<!--數據庫用戶密碼-->
<property name="connection.password">sa</property>
<!--數據庫驅動-->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--JDBC連接池(使用內置的連接池)-->
<property name="connection.pool_size">1</property>
<!--設置Hibernate自動管理上下文的策略-->
<property name="current_session_context_class">thread</property>
<!--選擇使用的方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--在啟動時刪除并重新創建數據庫-->
<property name="hbm2ddl.auto">create</property>
<mapping resource="events/User.hbm.xml"/>
<mapping resource="events/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
一、設計過程包含五個主要步驟。
第 1 步:確定實體和關系
第 2 步:確定所需數據
第 3 步:規范化數據
第 4 步:解析關系
第 5 步:驗證設計
二、閱讀別人的概念模型圖:
不管是從左到右讀取還是從右到左讀取,下面的規則都會使讀取這些圖示變得容易:讀取 (1) 第一個實體的名稱,(2) 第一個實體 旁邊的角色,(3) 到第二個實體 的連接的基數,(4) 第二個實體的名稱。
三、確定所需數據(實體屬性的設計)需要注意的:
確定支持數據時,一定要參考前面確定的活動以了解將如何訪問這些數據。
例如,在某些情況下可能需要按雇員的名字列出雇員,而在另一些情況下可能需要按姓氏列出。要滿足這兩種需要,應創建一個 First Name 屬性和一個 Last Name 屬性,而不應創建一個既包含名字又包含姓氏的屬性。將姓氏和名字分開后,以后可以創建兩個索引,分別適用于這兩項任務。
請選擇一致的名稱。使用一致的名稱可以使數據庫便于維護,并且便于閱讀報告和輸出窗口。
例如,如果一個屬性使用了縮略名稱,如 Emp_status,則另一個屬性不應使用完整名稱,如 Employee_ID。應使名稱保持一致,如 Emp_status 和 Emp_ID。
在這個階段,數據是否與正確的實體相關聯并不十分重要。您可以根據自己的判斷進行設計。在下一節中,將對設計進行測試,檢查您的判斷是否正確。
四、規范化是指一系列測試,通過這些測試可以消除冗余的數據,并確保數據與正確的實體或關系相關聯。共有五項測試。本節介紹其中前三項測試。這三項測試最重要,因此也最常使用。
五、范式:
數據規范化包括幾項測試。數據在通過了第一項測試后,我們認為它滿足第一范式;通過了第二項測試后,它滿足第二范式;通過了第三項測試后,則滿足第三范式。
六、標識符是唯一地標識實體中各行的一組屬性,至少由一個屬性組成。
七、解析關系:
執行完規范化過程后,設計幾乎就完成了。唯一還需要做的事情就是生成與概念數據模型相對應的物理數據模型。這個過程也稱作解析關系,因為其中涉及的大量工作就是將概念模型中的關系轉換為相應的表和外鍵關系。
八、概念數據模型可以簡化設計過程,因為它將大量細節隱藏起來。例如,多對多關系總會生成一個額外的表和兩個外鍵引用。在概念數據模型中,通常可以用一個連接來標識這類結構。
九、域(用戶定義的數據類型)
十、數據庫對象的定義構成了數據庫模式:您可以將模式看做一個空數據庫。(是否可以理解成C#的命名空間或java里的包概念)
十一、
這個插件在JQuery1.5.1版下無法使用。 項目地址: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("加載手機號碼匹配策略文件/mobile_match.conf失敗",e);
}
}
public static boolean isMultipart(HttpServletRequest req) {
return ((req.getContentType() != null) && (req.getContentType()
.toLowerCase().startsWith("multipart")));
}
/**
* 獲取FCKUpload過程中生成的會話ID
* @return
*/
public static String getDlogSessionId(HttpServletRequest req){
//優先從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得不到則從服務器的會話中讀取
HttpSession ssn = req.getSession(false);
if (ssn != null)
ssn_id = ssn.getId();
}
return ssn_id;
}
/**
* 清除FCKUpload過程中生成的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;
}
/**
* 設置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);
}
/**
* 獲取用戶訪問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();
}
/**
* 獲取訪問的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));
}
}
/**
* 從請求中解析手機號碼
* @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信息,名字大小寫無關
* @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));
}
}
/**
* 判斷手機是否支持某種類型的格式
* @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;
}
/**
* 獲取瀏覽器提交的整形參數
* @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;
}
/**
* 獲取瀏覽器提交的字符串參數
* @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();
}
}
/**
* 自動將敏感詞匯用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;
}
/**
* 判斷是否存在非法內容
* @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;
}
/**
* 刪除內容中存在的關鍵字
* @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 = "中華人民共和國國家主席毛澤東,我們叫他毛主席";
System.out.println(IllegalGlossary.autoGlossaryFiltrate(text));
}
}
這個類,是從DLOG4J上學到的。
 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 --創建表
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里面聲明變量時必須在變量前加@符號
12 DECLARE @I INT
13
14 -- 變量的賦值,變量賦值時變量前必須加set
15 SET @I = 30
16
17 -- 聲明多個變量
18 DECLARE @s varchar(10),@a INT
19
20 -- Sql 里if語句
21 IF 條件 BEGIN
22 執行語句
23 END
24 ELSE BEGIN
25 執行語句
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 '錯誤'
38 END
39
40
41 -- Sql 里的多條件選擇語句.
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 -- 循環語句
55 WHILE 條件 BEGIN
56 執行語句
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 刪除表中的所有行,而不記錄單個行刪除操作,不能帶條件
69
70 /*
71 TRUNCATE TABLE 在功能上與不帶 Where 子句的 Delete 語句相同:二者均刪除表中的全部行
72
73 。但 TRUNCATE TABLE 比 Delete 速度快,且使用的系統和事務日志資源少。
74 Delete 語句每次刪除一行,并在事務日志中為所刪除的每行記錄一項。TRUNCATE TABLE 通過
75
76 釋放存儲表數據所用的數據頁來刪除數據,并且只在事務日志中記錄頁的釋放。
77 TRUNCATE TABLE 刪除表中的所有行,但表結構及其列、約束、索引等保持不變。新行標識所用
78
79 的計數值重置為該列的種子。如果想保留標識計數值,請改用 Delete。如果要刪除表定義及其數據,請
80
81 使用 Drop TABLE 語句。
82 對于由 FOREIGN KEY 約束引用的表,不能使用 TRUNCATE TABLE,而應使用不帶 Where 子句的
83
84 Delete 語句。由于 TRUNCATE TABLE 不記錄在日志中,所以它不能激活觸發器。
85 TRUNCATE TABLE 不能用于參與了索引視圖的表。
86 示例
87 下例刪除 authors 表中的所有數據。*/
88
89 TRUNCATE TABLE authors
90
91
92 -- Select INTO 從一個查詢的計算結果中創建一個新表。 數據并不返回給客戶端,這一點和普通的
93 -- Select 不同。 新表的字段具有和 Select 的輸出字段相關聯(相同)的名字和數據類型。
94
95 select * into NewTable
96 from Uname
97
98
99 -- Insert INTO Select
100 -- 表ABC必須存在
101 -- 把表Uname里面的字段Username復制到表ABC
102 Insert INTO ABC Select Username FROM Uname
103
104 -- 創建臨時表
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 -- 打開臨時表
113 Select * from #temp
114
115 -- 存儲過程
116 -- 要創建存儲過程的數據庫
117 Use Test
118 -- 判斷要創建的存儲過程名是否存在
119 if Exists(Select name From sysobjects Where name='csp_AddInfo' And
120
121 type='P')
122 -- 刪除存儲過程
123 Drop Procedure dbo.csp_AddInfo
124 Go
125
126
127 -- 創建存儲過程
128 Create Proc dbo.csp_AddInfo
129 -- 存儲過程參數
130 @UserName varchar(16),
131 @Pwd varchar(50),
132 @Age smallint,
133 @Sex varchar(6)
134 AS
135 -- 存儲過程語句體
136 insert into Uname (UserName,Pwd,Age,Sex)
137 values (@UserName,@Pwd,@Age,@Sex)
138 RETURN
139 -- 執行
140 GO
141
142 -- 執行存儲過程
143 EXEC csp_AddInfo 'Junn.A','123456',20,'男';
144 修改自:http://blog.csdn.net/mx1029/archive/2007/07/06/1680910.aspx
1、 ServletFileUpload.isMultipartContent(request) 檢測request中是否包含有multipart內容 2、如果有,生成DiskFileItemFactory工廠將進行相關的設置 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工廠傳給它,并對ServletFileUpload進行配置 // 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>"); } } } 說明: FileItem接口是對用戶上傳文件的封裝 DiskFileItemFactory實現了FileItemFactory接口,主要方法有public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) ServletFileUpload從FileUpload繼承,而FileUpload又從FileUploadBase繼承,功能:分析傳入的request對象、得到文件列表FileItemIterator……
簡明步驟 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
一個Servlet可以通過HTML表單標簽將文件上傳到服務器。支待上傳的有文本、圖像及任何文件。
創建文件上傳表單:
下面的html代碼創建了一個上傳表單。創建過程需要注意以下幾點:
l form標簽中的method屬性必須設置為POST,即GET方法是不可以的。
l form標簽中的enctype屬性應該設置為multipart/form-data。
l from標簽中的action屬性應該與服務器后臺的servlet映射路徑相同。接下來的實例,我們將使用UploadServlet實現文件上傳。
l 要上傳一個文件,你應該使用一個<input type=”file”.../>標記。要多個文件上傳,必須包含多個具有不同的名稱屬性值的<input type=”file”.../>標記。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上選擇一個文件。當你點擊“Upload File”,表單將會隨著你選擇的文件一起被提交。
后臺servlet:
以下UploadServlet servlet將接收上傳的文件并將其保存入<Tomcat-installation-directory>/webapps/data文件夾。這個文件夾的名稱可以通過外部配置文件web.xml中的context-param元素內容增加。代碼如下:
<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>
|
以下是實現了多文件同時上傳功能的UploadServlet。在此之前您必須確定以下幾點:
l 以下實例依賴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 在測試以下例子的時候,您應該上傳小于maxFileSize的文件,否則無法上傳。
l 事先確定你已經建議好文件夾: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.");
}
}
|
編譯并運行Servlet
編譯以上UploadServlet并在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>
|
現在可以嘗試使用你創建的HTML表單上傳文件。當你訪問http://localhost:8080/UploadFile.htm,瀏覽器里將會顯示如下效果,您可以從本地上傳你想要上傳的任何文件。
如果您的servlet腳本運行成功,您的文件上傳在c:"apache-tomcat-5.5.29"webapps"data"directory文件夾。
1、取得系統Properties,并配置 Properties props = System.getProperties(); props.setProperty("mail.transport.protocol", "smtp"); // smtp協議 props.setProperty("mail.smtp.host", m_server); // 服務器地址 props.setProperty("mail.smtp.port", "" + m_port); // 端口號 props.setProperty("mail.smtp.auth", "true"); //// 認證信息 2、將取得Session javax.mail.Session sess = javax.mail.Session.getDefaultInstance(props); 3、實例MimeMessage類,然后設置收件人、主題、發件日期 MimeMessage msg = new MimeMessage(sess); msg.setFrom(new InternetAddress(m_from)); // 發件人 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(m_to)); //收件人 msg.setSubject(m_subject); //主題 msg.setSentDate(new Date()); //發件日期 4、向MimeMessage中添加文本內容及附件 MimeMultipart content = new MimeMultipart();// 文本內容 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); //設置并保存 msg.saveChanges(); 5、使用Session取得Transport Transport trans = sess.getTransport(); 6、使用Transport連接服務器 trans.connect(m_server, m_user, m_pass); 7、發送郵件并關閉 trans.sendMessage(msg, InternetAddress.parse(m_to)); trans.close();
1、java對象序列化不保存對象中的靜態變量  serpublic class Test implements Serializable {
private static final long serialVersionUID = 1L;
public static int staticVar = 5;
public static void main(String[] args) {
try {
//初始時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();
//再讀取,通過t.staticVar打印新的值
System.out.println(t.staticVar);//10
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2、虛擬機是否允許反序列化,不僅取決于類路徑和功能代碼是否一致,一個非常重要的一點是兩個類的序列化 ID 是否一致(就是 private static final long serialVersionUID = 1L)。
3、父類的序列化與transient關鍵字
只有子類和父類都實現了Serializable接口時,對子類反序列化時才會將父類也序列化。反序列化過程是先反序列過父類對象再反序列化子類。而如果不想序列化某一個變量,則可以在定義變量時使用transient關鍵字。
 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關鍵字
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 序列化機制為了節省磁盤空間,具有特定的存儲規則,當寫入文件的為同一對象時,并不會再將對象的內容進行存儲,而只是再次存儲一份引用。
從IBM DW 整理而來
http://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html#icomments
Class.froName(“cc.a.C”) 返回:C這個類的class(其實是這個類的字節碼) 作用:告訴jvm使用相應的加載器,將C.class加載入jvm(至于加載到哪個位置,本人還不知道) 而Class.forName(“cc.a.C”).newInstance()則是實例化一個對象;而new關鍵的作用也是實例化一個對象 所以可以粗略的將這兩種實例化對象的方法等同。 當然它們有不同的地方。 在網上看到別人是這樣區別的: newInstance: 弱類型。低效率。只能調用無參構造。 new: 強類型。相對高效。能調用任何public構造。
將myeclipes安裝目錄C:\Program Files\Genuitec\Common\plugins 所有的東西復制到eclipes安裝目錄的\plugins里,并覆蓋。 重新啟動eclipes就可以了。
1、比較兩個對象是否類型相同 array1.getClass().getName().equals(array2.getClass().getName() 2、倒置(reverse)數組中的元素 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、得到數組的容器類型 array.getClass().getComponentType(); 4、lastIndex()這類方法的實現 for (int i = startIndex; i >= 0; i--) { if (objectToFind.equals(array[i])) { return i; } } 5、isEmpty()這類方法的實現只要一句話,isNotEmpty方法依此推 return array == null || array.length == 0; 6、將兩個數組合并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、將新元素加入到數組中 int arrayLength = Array.getLength(array); Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); System.arraycopy(array, 0, newArray, 0, arrayLength); return newArray; 8、獲得數組長度的方法 int arrayLength = Array.getLength(array); 9、以反射的方式獲得數組對象 Array.newInstance(array.getClass().getComponentType(), arrayLength + 1) 10、將某一元素從數組中移除 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); }
1、泛型是給java編譯器使用的,在源文件經過編譯后,編譯器會將類型信息去掉,所以  testList<String> ls = new ArrayList<String>();
List<Boolean> ls1 = new ArrayList<Boolean>();
System.out.println(ls==ls1) ;
//true;
2、可以繞過編譯器的類型信息檢查,而直接加入對象
 testimport java.util.* ;
import java.lang.* ;
public class Fanx {
public static void main (String args[]) {
ArrayList<Integer> ls = new ArrayList<Integer>();
try{
ls.getClass().getMethod("add", Object.class).invoke(ls,"abc") ;
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println(ls.get(0));
}
}//out:abc
3、泛型通配符
 testpublic static void printCollection(Collection<?> coll) {
//可以傳Collection<String>,Collection<Integer>,Collection<Boolean>等等,但在此方法內不能使用諸如coll.add(“Strin”)這樣具有類型信息的方法
for(Object obj:coll){
System.out.println(obj);
}//coll.add(“str”); 報錯
}
4、限定通配符上邊界,限定通配符上邊界
 testpublic static void printCollection1(Collection<? extends Number> coll) {
//
for(Object obj:coll){
System.out.println(obj);
}
}
//printCollection1(new ArrayList<Integer>()) ;//不報錯
//printCollection1(new ArrayList<String>()) ; //報錯,傳入泛型參數必須為Number的子類
 testpublic static void printCollection2(Collection<? super Number> coll) {
//
for(Object obj:coll){
System.out.println(obj);
}
}
//printCollection1(new ArrayList<Integer>()) ;//不報錯
//printCollection1(new ArrayList<String>()) ; //報錯,傳的參數化必須是以Number為父類
5、自定義泛型方法
 testpublic <T> T swap(T[] t,int i,int j){
T temp = t[i] ;
t[i] = t[j] ;
t[j] = t[i] ;
return (T) t ;
}
6、類級別泛型
 testpublic class Dao<T> {
public <T> T getEntity(int id){
return null;
}
}
7、通過反射獲得泛型的實際類型參數
 testimport java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Map;
import java.util.Vector;
//假如我們要想獲得 Vector<Date> v = new Vector<Date>(); v的實際類型參數
//我們必須寫一個如applyRef的方法
public class Dao {
public void applyRef1(Map<String,Integer> map,Vector<Date> v){
}
public static void main(String[] args) {
try {
Method method = new Dao().getClass().getMethod("applyRef1", Map.class,Vector.class) ;
Type[] pType = method.getParameterTypes();
Type[] neiType = method.getGenericParameterTypes();
System.out.println(pType[0]) ;
System.out.println(pType[1]) ;
System.out.println(neiType[0]) ;
System.out.println(neiType[1]) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
 Combinationsimport java.io.File;
import java.io.Serializable;
public class Combinations implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6509436857839528414L;
private int min;
private int max;
private char[] chars;// 字符數組
private int charLen;// 字符串長度
private String path ;
private String trueStr ;
private IOUtil iou;
public Combinations() {
this.min = 1;
this.max = trueStr.length() ;
this.charLen = trueStr.length();
this.chars = trueStr.toCharArray();
}
public Combinations(String str, int min, int max, String path) {
this.min = min;
this.max = max;
this.trueStr = str ;
this.charLen = str.length();
this.chars = str.toCharArray();
iou = IOUtil.getInstence(path);
}
public void combination() {
if (min > max) {
int t = max;
max = min;
min = t;
}
for (int i = min; i <= max; i++) {
combination(new StringBuffer(""), i);
}
}
public void combination(StringBuffer str, int length) {
if (length < 1) {
System.out.println("長度小于1");
}
if (length == 1) {
for (int i = 0; i < charLen; i++) {
StringBuffer result = new StringBuffer(str);
result.append(chars[i]);
iou.put(result.toString(),
MD5Util.getMD5Str(result.toString()));
}
}
if (length > 1) {
for (int i = 0; i < charLen; i++) {
StringBuffer temp = new StringBuffer(str);
combination(temp.append(chars[i]), length - 1);
}
}
}
/**
*setter getter
*/
public IOUtil getIou() {
return iou;
}
public void setIou(IOUtil iou) {
this.iou = iou;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public char[] getChars() {
return chars;
}
public void setChars(char[] chars) {
this.chars = chars;
}
public int getCharLen() {
return charLen;
}
public void setCharLen(int charLen) {
this.charLen = charLen;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTrueStr() {
return trueStr;
}
public void setTrueStr(String trueStr) {
this.trueStr = trueStr;
}
public static void main(String[] args) {
String path = "F:"+File.separator+"md5"
+File.separator+"md5.txt";
Combinations ct = new Combinations("123456",1,4,path);
ct.combination() ;
ct.getIou().close() ;
}
}
 md5Utilimport java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
/**
* MD5 加密
*/
public static String getMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException caught!");
System.exit(-1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString();
}
}
IO工具包
 md5Utilimport java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IOUtil implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1611785226109373473L;
/*
* 接收key 和 value,然后寫入一個map,計數器count++如果count>30,IOWrite進入flush;
* 判斷文件是否大于30MB,則新建另一文件將map清空,將count設置為0;
*/
private String sourcePath;
private String newPath;
private int MAXSIZE = 30000;
private int fileCount = 0; // 文件計數器
private PrintWriter pw = null;
private List<String> list = new ArrayList<String>();
private static IOUtil instance = new IOUtil();
private IOUtil() {
}
public static IOUtil getInstence(String path) {
if (null == instance) {
instance = new IOUtil();
}
instance.setSourcePath(path);
instance.setNewPath(path);
return instance;
}
public void put(String key, String value) {
//判斷path中的文件
File file = new File(newPath) ;
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
}
try {
pw = new PrintWriter(new FileWriter(file));
} catch (IOException e) {
System.out.println("找不到文件" + e.getMessage());
}
if (list.size() <= MAXSIZE) {
list.add(key + " " + value);
} else {
Iterator<String> it = list.iterator();
while (it.hasNext()) {
pw.println(it.next());
}
// 刷新
pw.flush();
list.clear();
this.fileCount++;
this.newPath = this.sourcePath.substring(0, this.sourcePath
.lastIndexOf('.'))
+ "_"
+ this.fileCount
+ this.sourcePath.substring(this.sourcePath
.lastIndexOf('.'));
}
}
@SuppressWarnings("unchecked")
public void close() {
Iterator itor = null;
if (list.size() > 0 && this.pw != null) {
itor = list.iterator();
while (itor.hasNext()) {
pw.println(itor.next());
}
pw.close();
}
itor = null;
pw = null;
}
/*******************
* getter setter
*******************/
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public String getNewPath() {
return newPath;
}
public void setNewPath(String newPath) {
this.newPath = newPath;
}
public PrintWriter getPw() {
return pw;
}
public void setPw(PrintWriter pw) {
this.pw = pw;
}
}
|