`
lohasle
  • 浏览: 253837 次
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
jquery 动态创建form提交
因为a标签的url长度是有限制的,采用post方式就没有限制了。
 <a href="javascript:modifyData('{\'stcd\':\'${stcd}\',\'type\':\'${type}\',\'modelId\':\'${modelId}\',\'grz\':\'${grz}\',\'wrz\':\'${wrz}\'}')" class="button edit" title="xx">xx</a>


           function postwith(url, pjsondata) {
                 var $form = $("<form></form>");
                 $form.attr('action',url);
                 $form.attr('method','post');
                 for(var o in pjsondata){
                     var $input = $("<input type='hidden' name='"+o+"'/>");
                     $input.attr('value',pjsondata[o]);
                     $form.append($input);
                 }
                 $form.appendTo("body");
                 $form.css('display','none');
                 $form.submit();
             }
            function modifyData(str){
                var jsonstr = str.replace(/\'/g,"\"");
                var jsonObject = jQuery.parseJSON(jsonstr);
                postwith('update.view',jsonObject);
            }
java获得格式化日期最小单位的整点时间 java
   /**
     * 取得符合规范的data
     *
     * @param sourDate
     * @param pattern
     * @return
     */
    public static Date praseDateToDataByPattern(Date sourDate, String pattern) throws ParseException {
        if (sourDate == null || pattern == null) {
            throw new ParseException("错误的日期和格式化字符", 0);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String result_date = sdf.format(sourDate);
        return sdf.parse(result_date);
    }

    /**
     * 取得格式化字符串的整点数据
     * 根据格式化的字符串的最小单位四舍五入的对时间进行操作
     * 如  2013-05-01 02:12:34  -->2013-05-01 02:13:00
     * 2013-05-01 02:12:12  -->2013-05-01 02:12:00
     *
     * @param date   日期
     * @param format 格式化的字符串
     * @return
     */
    public static String getCorrectDateOnEntire(Date date, String format) throws ParseException {
        if (date == null || format == null) {
            throw new ParseException("错误的日期和格式化字符", 0);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        char[] ch = format.toCharArray();
        StringBuffer least_precision = new StringBuffer();
        for (int i = ch.length; i > 0; i--) {
            if (ch[ch.length - 1] == ch[i - 1]) {
                least_precision.append(ch[i - 1]);
            } else {
                break;
            }
        }
        Date run_date = praseDateToDataByPattern(date, format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(run_date);
        int field = TimeAccuracy.valueOf(least_precision.toString()).textVal;
        int real_time = calendar.get(field);
        int possible_max_time = calendar.getMaximum(field);// 12小时制
        if (real_time > possible_max_time) {
            calendar.roll(field, true);
        } else {
            calendar.roll(field, calendar.getMinimum(field));
        }
        return sdf.format(calendar.getTime());
    }


    public static enum TimeAccuracy {
        yyyy(Calendar.YEAR),
        MM(Calendar.MONTH),
        dd(Calendar.DATE),
        HH(Calendar.HOUR),
        mm(Calendar.MINUTE),
        ss(Calendar.MILLISECOND);

        private int textVal;

        private TimeAccuracy(int textVal) {
            this.textVal = textVal;
        }

        private int getIntValue() {
            return textVal;
        }
    }
因数分解 递归和非递归方法 java
private Integer[] fators(int a,List<Integer> re ){
		if (a<=3) {
			re.add(a);
		}else {
			for (int i = 2; i <=a; i++) {
				if (a%i==0) {
					re.add(i);
					a/=i;
					if (a!=1) {
						fators(a,re);
						break;
					}
				}
			}
		}
		return re.toArray(new Integer[]{0});
	}
	
	//非递归
	private Integer[] fators2(int a){
		List<Integer> re = new ArrayList<Integer>();
		if (a<=3) {
			re.add(a);
		}else {
			int count = 2;
			while(a!=1){
				if (a%count==0) {
					re.add(count);
					a/=count;
					while(a%count!=0){
						count++;
						break;
					}
				}else {
					count++;
				}
			}
		}
		return re.toArray(new Integer[]{0});
	}
打乱List顺序 java中容易忽略的shuffle用法
List<String> clouds=new ArrayList<String)(6);
Collctions.shuffle(clouds);

日历的加减操作
	       Date tpTime = (Date) endTime.clone();// copy
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(tpTime);
		calendar.add(Calendar.MINUTE, -spacingTime);  
		Date newDate = calendar.getTime();
spring mvc中redirect导致内存泄露? 解决方法 spring 探讨:spring mvc中redirect导致内存泄露?
@RequestMapping(method = RequestMethod.POST)  
public String onPost(RedirectAttributes redirectAttrs) {  
    // ...
    redirectAttrs.addAttribute("entityId", entityId)
    return "redirect:form.html?entityId={entityId}";  
} 
spring mvc中redirect导致内存泄露? spring 探讨:spring mvc中redirect导致内存泄露?
public abstract class AbstractCachingViewResolver extends WebApplicationObjectSupport implements ViewResolver {
    /** Whether we should cache views, once resolved */
    private boolean cache = true;

    /** Map from view key to View instance */
    private final Map<Object, View> viewCache = new HashMap<Object, View>();

    //... set/get方法略

    public View resolveViewName(String viewName, Locale locale) throws Exception {
        if (!isCache()) {
            return createView(viewName, locale);
        } else { 
            Object cacheKey = getCacheKey(viewName, locale);
            synchronized (this.viewCache) {
                View view = this.viewCache.get(cacheKey);
                if (view == null && (!this.cacheUnresolved || !this.viewCache.containsKey(cacheKey))) {
                    // Ask the subclass to create the View object.
                    view = createView(viewName, locale);
                    if (view != null || this.cacheUnresolved) {
                        this.viewCache.put(cacheKey, view);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Cached view [" + cacheKey + "]");
                        }
                    }
                }
                return view;
            }
        }
    }
}
JS中判断是否相等有"=="和"==="两种符号,它们之间有很多不同。 JS中"=="与"==="的区别
alert(0 == ""); // true 
alert(0 == false); // true 
alert("" == false); // true 

alert(0 === ""); // false 
alert(0 === false); // false 
alert("" === false); // false 
java获取今天,明天,昨天的日期 java
Date date=new Date();//取时间
 Calendar calendar = new GregorianCalendar();
 calendar.setTime(date);
 calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
 date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
 String dateString = formatter.format(date);
 
 System.out.println(dateString);
function, new function, new Function之间的区别 javascript
函数是JavaScript中很重要的一个语言元素,并且提供了一个function关键字和内置对象Function,下面是其可能的用法和它们之间的关系。 
使用方法一: 
代码如下:

var foo01 = function() //or fun01 = function() 
{ 
var temp = 100; 
this.temp = 200; 
return temp + this.temp; 
} 
alert(typeof(foo01)); 
alert(foo01()); 
运行结果: 
function 
300 最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的却别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。 
使用方法二: 
复制代码 代码如下:

var foo02 = new function() 
{ 
var temp = 100; 
this.temp = 200; 
return temp + this.temp; 
} 
alert(typeof(foo02)); 
alert(foo02.constructor()); 
运行结果: object 
300 这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个JavaScript中的用户自定义对象,不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。 
使用方法三:
复制代码 代码如下:

var foo3 = new Function('var temp = 100; this.temp = 200; return temp + this.temp;'); 
alert(typeof(foo3)); 
alert(foo3()); 
运行结果: function 
300 使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。 
使用方法四: 
复制代码 代码如下:

var foo4 = Function('var temp = 100; this.temp = 200; return temp + this.temp;'); 
alert(typeof(foo4)); 
alert(foo4()); 
运行结果: 
function 
300 这个方式是不常使用的,效果和方法三一样,不过不清楚不用new来生成有没有什么副作用,这也体现了JavaScript一个最大的特性:灵活!能省就省。 
关于函数初始化优先级这个问题,可以参看:"JS类定义原型方法的两种实现的区别"的回复。 
java获得当前系统的中文字体列表 java 工具代码
String[]   fontlist   = 
			    GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); //获得当前字体列表
		String except = "^[a-zA-Z0-9_ -.]+$";
		Pattern pattern = Pattern.compile(except);
		for (String string : fontlist) {
			if (!pattern.matcher(string).matches()) {
				System.out.println(string);
			}	
		}
正则匹配中文,数字 字母下划线 常用正则 java正则表达式-匹配中文数字字母下划线
String chinese = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";//仅中文
//用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串
String username = "^\\w+$";

String all  = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w]{1,6}$";
Pattern pattern = Pattern.compile(all);
boolean tf = pattern.matcher("12長").matches();
System.out.println(tf);
Spring文件资源操作和Web相关工具类 spring http://tech.ccidnet.com/art/12013/20090417/1743093_1.html
Spring 不但提供了一个功能全面的应用开发框架,本身还拥有众多可以在程序编写时直接使用的工具类,您不但可以在 Spring 应用中使用这些工具类,也可以在其它的应用中使用,这些工具类中的大部分是可以在脱离 Spring 框架时使用的。了解 Spring 中有哪些好用的工具类并在程序编写时适当使用,将有助于提高开发效率、增强代码质量。在这个分为两部分的文章中,我们将从众多的 Spring 工具类中遴选出那些好用的工具类介绍给大家。第 1 部分将介绍与文件资源操作和 Web 相关的工具类。
文件资源操作

  文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等。我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来说,JDK 的这些操作类所提供的方法过于底层,直接使用它们进行文件操作不但程序编写复杂而且容易产生错误。相比于 JDK 的 File,Spring 的 Resource 接口(资源概念的描述接口)抽象层面更高且涵盖面更广,Spring 提供了许多方便易用的资源操作工具类,它们大大降低资源操作的复杂度,同时具有更强的普适性。这些工具类不依赖于 Spring 容器,这意味着您可以在程序中象一般普通类一样使用它们。

  加载文件资源

  Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL 地址以及资源内容的操作方法。

  访问文件资源 

  假设有一个文件地位于 Web 应用的类路径下,您可以通过以下方式对这个文件资源进行访问:

通过 FileSystemResource 以文件系统绝对路径的方式进行访问; 
通过 ClassPathResource 以类路径的方式进行访问; 
通过 ServletContextResource 以相对于Web应用根目录的方式进行访问。

  相比于通过 JDK 的 File 类访问文件资源的方式,Spring 的 Resource 实现类无疑提供了更加灵活的操作方式,您可以根据情况选择适合的 Resource 实现类访问资源。下面,我们分别通过 FileSystemResource 和 ClassPathResource 访问同一个文件资源:


清单 1. FileSourceExample
package com.baobaotao.io; 
import java.io.IOException; 
import java.io.InputStream; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.FileSystemResource; 
import org.springframework.core.io.Resource; 
public class FileSourceExample {
public static void main(String[] args) {
try {
String filePath = 
"D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt"; 
// ① 使用系统文件路径方式加载文件
Resource res1 = new FileSystemResource(filePath); 
// ② 使用类路径方式加载文件
Resource res2 = new ClassPathResource("conf/file1.txt"); 
InputStream ins1 = res1.getInputStream(); 
InputStream ins2 = res2.getInputStream(); 
System.out.println("res1:"+res1.getFilename()); 
System.out.println("res2:"+res2.getFilename()); 
} catch (IOException e) {
e.printStackTrace(); 
}
}
}

  在获取资源后,您就可以通过 Resource 接口定义的多个方法访问文件的数据和其它的信息:如您可以通过 getFileName() 获取文件名,通过 getFile() 获取资源对应的 File 对象,通过 getInputStream() 直接获取文件的输入流。此外,您还可以通过 createRelative(String relativePath) 在资源相对地址上创建新的资源。

  在 Web 应用中,您还可以通过 ServletContextResource 以相对于 Web 应用根目录的方式访问文件资源,如下所示:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<jsp:directive.page import="org.springframework.
web.context.support.ServletContextResource"/>
<jsp:directive.page import="org.springframework.core.io.Resource"/>
<%
// ① 注意文件资源地址以相对于 Web 应用根路径的方式表示
Resource res3 = new ServletContextResource(application, 
"/WEB-INF/classes/conf/file1.txt"); 
out.print(res3.getFilename()); 
%>


  对于位于远程服务器(Web 服务器或 FTP 服务器)的文件资源,您则可以方便地通过 UrlResource 进行访问。

  为了方便访问不同类型的资源,您必须使用相应的 Resource 实现类,是否可以在不显式使用 Resource 实现类的情况下,仅根据带特殊前缀的资源地址直接加载文件资源呢?Spring 提供了一个 ResourceUtils 工具类,它支持“classpath:”和“file:”的地址前缀,它能够从指定的地址加载文件资源,请看下面的例子:

清单 2. ResourceUtilsExample
package com.baobaotao.io; 
import java.io.File; 
import org.springframework.util.ResourceUtils; 
public class ResourceUtilsExample {
public static void main(String[] args) throws Throwable{
File clsFile = ResourceUtils.getFile("classpath:conf/file1.txt"); 
System.out.println(clsFile.isFile()); 
String httpFilePath = "file:D:/masterSpring/chapter23/src/conf/file1.txt"; 
File httpFile = ResourceUtils.getFile(httpFilePath); 
System.out.println(httpFile.isFile()); 
}
}



  ResourceUtils 的 getFile(String resourceLocation) 方法支持带特殊前缀的资源地址,这样,我们就可以在不和 Resource 实现类打交道的情况下使用 Spring 文件资源加载的功能了。

本地化文件资源 

  本地化文件资源是一组通过本地化标识名进行特殊命名的文件,Spring 提供的 LocalizedResourceHelper 允许通过文件资源基名和本地化实体获取匹配的本地化文件资源并以 Resource 对象返回。假设在类路径的 i18n 目录下,拥有一组基名为 message 的本地化文件资源,我们通过以下实例演示获取对应中国大陆和美国的本地化文件资源:


清单 3. LocaleResourceTest
package com.baobaotao.io; 
import java.util.Locale; 
import org.springframework.core.io.Resource; 
import org.springframework.core.io.support.LocalizedResourceHelper; 
public class LocaleResourceTest {
public static void main(String[] args) {
LocalizedResourceHelper lrHalper = new LocalizedResourceHelper(); 
// ① 获取对应美国的本地化文件资源
Resource msg_us = lrHalper.findLocalizedResource("i18n/message", ".properties", 
Locale.US); 
// ② 获取对应中国大陆的本地化文件资源
Resource msg_cn = lrHalper.findLocalizedResource("i18n/message", ".properties", 
Locale.CHINA); 
System.out.println("fileName(us):"+msg_us.getFilename()); 
System.out.println("fileName(cn):"+msg_cn.getFilename()); 
}
}


  虽然 JDK 的 java.util.ResourceBundle 类也可以通过相似的方式获取本地化文件资源,但是其返回的是 ResourceBundle 类型的对象。如果您决定统一使用 Spring 的 Resource 接表征文件资源,那么 LocalizedResourceHelper 就是获取文件资源的非常适合的帮助类了。

  文件操作

  在使用各种 Resource 接口的实现类加载文件资源后,经常需要对文件资源进行读取、拷贝、转存等不同类型的操作。您可以通过 Resource 接口所提供了方法完成这些功能,不过在大多数情况下,通过 Spring 为 Resource 所配备的工具类完成文件资源的操作将更加方便。

  文件内容拷贝 

  第一个我们要认识的是 FileCopyUtils,它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。下面的实例展示了 FileCopyUtils 具体使用方法:

清单 4. FileCopyUtilsExample
package com.baobaotao.io; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileReader; 
import java.io.OutputStream; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.Resource; 
import org.springframework.util.FileCopyUtils; 
public class FileCopyUtilsExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt"); 
// ① 将文件内容拷贝到一个 byte[] 中
byte[] fileData = FileCopyUtils.copyToByteArray(res.getFile()); 
// ② 将文件内容拷贝到一个 String 中
String fileStr = FileCopyUtils.copyToString(new FileReader(res.getFile())); 
// ③ 将文件内容拷贝到另一个目标文件
FileCopyUtils.copy(res.getFile(), 
new File(res.getFile().getParent()+ "/file2.txt")); 
// ④ 将文件内容拷贝到一个输出流中
OutputStream os = new ByteArrayOutputStream(); 
FileCopyUtils.copy(res.getInputStream(), os); 
}
}



  往往我们都通过直接操作 InputStream 读取文件的内容,但是流操作的代码是比较底层的,代码的面向对象性并不强。通过 FileCopyUtils 读取和拷贝文件内容易于操作且相当直观。如在 ① 处,我们通过 FileCopyUtils 的 copyToByteArray(File in) 方法就可以直接将文件内容读到一个 byte[] 中;另一个可用的方法是 copyToByteArray(InputStream in),它将输入流读取到一个 byte[] 中。

  如果是文本文件,您可能希望将文件内容读取到 String 中,此时您可以使用 copyToString(Reader in) 方法,如 ② 所示。使用 FileReader 对 File 进行封装,或使用 InputStreamReader 对 InputStream 进行封装就可以了。

  FileCopyUtils 还提供了多个将文件内容拷贝到各种目标对象中的方法,这些方法包括:

  方法 说明 
static void copy(byte[] in, File out) 将 byte[] 拷贝到一个文件中 
static void copy(byte[] in, OutputStream out) 将 byte[] 拷贝到一个输出流中 
static int copy(File in, File out) 将文件拷贝到另一个文件中 
static int copy(InputStream in, OutputStream out) 将输入流拷贝到输出流中 
static int copy(Reader in, Writer out) 将 Reader 读取的内容拷贝到 Writer 指向目标输出中 
static void copy(String in, Writer out) 将字符串拷贝到一个 Writer 指向的目标中 

  在实例中,我们虽然使用 Resource 加载文件资源,但 FileCopyUtils 本身和 Resource 没有任何关系,您完全可以在基于 JDK I/O API 的程序中使用这个工具类。

  属性文件操作 

  我们知道可以通过 java.util.Properties的load(InputStream inStream) 方法从一个输入流中加载属性资源。Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源,请看下面的例子:

package com.baobaotao.io; 
import java.util.Properties; 
import org.springframework.core.io.support.PropertiesLoaderUtils; 
public class PropertiesLoaderUtilsExample {
public static void main(String[] args) throws Throwable { 
// ① jdbc.properties 是位于类路径下的文件
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties"); 
System.out.println(props.getProperty("jdbc.driverClassName")); 
}
}


  一般情况下,应用程序的属性文件都放置在类路径下,所以 PropertiesLoaderUtils 比之于 Properties#load(InputStream inStream) 方法显然具有更强的实用性。此外,PropertiesLoaderUtils 还可以直接从 Resource 对象中加载属性资源:

  方法 说明 
  static Properties loadProperties(Resource resource) 从 Resource 中加载属性 
static void fillProperties(Properties props, Resource resource) 将 Resource 中的属性数据添加到一个已经存在的 Properties 对象中 

  特殊编码的资源 

  当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如 UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。

清单 5. EncodedResourceExample
package com.baobaotao.io; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.Resource; 
import org.springframework.core.io.support.EncodedResource; 
import org.springframework.util.FileCopyUtils; 
public class EncodedResourceExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt"); 
// ① 指定文件资源对应的编码格式(UTF-8)
EncodedResource encRes = new EncodedResource(res,"UTF-8"); 
// ② 这样才能正确读取文件的内容,而不会出现乱码
String content = FileCopyUtils.copyToString(encRes.getReader()); 
System.out.println(content); 
}
}


  EncodedResource 拥有一个 getResource() 方法获取 Resource,但该方法返回的是通过构造函数传入的原 Resource 对象,所以必须通过 EncodedResource#getReader() 获取应用编码后的 Reader 对象,然后再通过该 Reader 读取文件的内容。

  Web 相关工具类

  您几乎总是使用 Spring 框架开发 Web 的应用,Spring 为 Web 应用提供了很多有用的工具类,这些工具类可以给您的程序开发带来很多便利。在这节里,我们将逐一介绍这些工具类的使用方法。

  操作 Servlet API 的工具类

  当您在控制器、JSP 页面中想直接访问 Spring 容器时,您必须事先获取 WebApplicationContext 对象。Spring 容器在启动时将 WebApplicationContext 保存在 ServletContext的属性列表中,通过 WebApplicationContextUtils 工具类可以方便地获取 WebApplicationContext 对象。

  WebApplicationContextUtils 

  当 Web 应用集成 Spring 容器后,代表 Spring 容器的EebApplicationContext 对象将以
  WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在 ServletContext 属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:

  WebApplicationContext wac = (WebApplicationContext)servletContext.
  getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 

  但通过位于 org.springframework.web.context.support 包中的WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:

  WebApplicationContext wac =WebApplicationContextUtils.
  getWebApplicationContext(servletContext); 

  当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。如果后续代码直接访问返回的结果将引发一个 NullPointerException 异常,而 WebApplicationContextUtils 另一个 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 属性列表中一定要包含一个有效的 WebApplicationContext 对象,否则马上抛出一个 IllegalStateException 异常。我们推荐使用后者,因为它能提前发现错误的时间,强制开发者搭建好必备的基础设施。

  WebUtils 

  位于 org.springframework.web.util 包中的 WebUtils 是一个非常好用的工具类,它对很多 Servlet API 提供了易用的代理方法,降低了访问 Servlet API 的复杂度,可以将其看成是常用 Servlet API 方法的门面类。

  下面这些方法为访问 HttpServletRequest 和 HttpSession 中的对象和属性带来了方便:

  方法 说明 
  Cookie getCookie(HttpServletRequest request, String name) 获取 HttpServletRequest 中特定名字的 Cookie 对象。如果您需要创建 Cookie, Spring 也提供了一个方便的 CookieGenerator 工具类; 
  Object getSessionAttribute(HttpServletRequest request, String name) 获取 HttpSession 特定属性名的对象,否则您必须通过request.getHttpSession.getAttribute(name) 完成相同的操作; 
  Object getRequiredSessionAttribute(HttpServletRequest request, String name) 和上一个方法类似,只不过强制要求 HttpSession 中拥有指定的属性,否则抛出异常; 
String getSessionId(HttpServletRequest request) 获取 Session ID 的值; 
  void exposeRequestAttributes(ServletRequest request, Map attributes) 将 Map 元素添加到 ServletRequest 的属性列表中,当请求被导向(forward)到下一个处理程序时,这些请求属性就可以被访问到了; 

  此外,WebUtils还提供了一些和ServletContext相关的方便方法:


方法 说明 
  String getRealPath(ServletContext servletContext, String path) 获取相对路径对应文件系统的真实文件路径; 
  File getTempDir(ServletContext servletContext) 获取 ServletContex 对应的临时文件地址,它以 File 对象的形式返回。 

  下面的片断演示了使用 WebUtils 从 HttpSession 中获取属性对象的操作:


protected Object formBackingObject(HttpServletRequest request) throws Exception {
UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, 
"userSession"); 
if (userSession != null) {
return new AccountForm(this.petStore.getAccount(
userSession.getAccount().getUsername())); 
} else {
return new AccountForm(); 
}
}


  Spring 所提供的过滤器和监听器

  Spring 为 Web 应用提供了几个过滤器和监听器,在适合的时间使用它们,可以解决一些常见的 Web 应用问题。

  延迟加载过滤器 

  Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session 已经关闭,这些导致延迟加载数据的访问异常。

  Spring 为此专门提供了一个 OpenSessionInViewFilter 过滤器,它的主要功能是使每个请求过程绑定一个 Hibernate Session,即使最初的事务已经完成了,也可以在 Web 层进行延迟加载的操作。

  OpenSessionInViewFilter 过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到。所以 OpenSessionInViewFilter 适用于 Service 层使用HibernateTransactionManager 或 JtaTransactionManager 进行事务管理的环境,也可以用于非事务只读的数据操作中。

  要启用这个过滤器,必须在 web.xml 中对此进行配置:

…
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
…


  上面的配置,我们假设使用 .html 的后缀作为 Web 框架的 URL 匹配模式,如果您使用 Struts 等 Web 框架,可以将其改为对应的“*.do”模型。 
中文乱码过滤器 

  在您通过表单向服务器提交数据时,一个经典的问题就是中文乱码问题。虽然我们所有的 JSP 文件和页面编码格式都采用 UTF-8,但这个问题还是会出现。解决的办法很简单,我们只需要在 web.xml 中配置一个 Spring 的编码转换过滤器就可以了:

<web-app>
<!---listener的配置-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter ① Spring 编辑过滤器
</filter-class>
<init-param> ② 编码方式
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param> ③ 强制进行编码转换
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping> ② 过滤器的匹配 URL
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<!---servlet的配置-->
</web-app>


  这样所有以 .html 为后缀的 URL 请求的数据都会被转码为 UTF-8 编码格式,表单中文乱码的问题就可以解决了。

  请求跟踪日志过滤器 

  除了以上两个常用的过滤器外,还有两个在程序调试时可能会用到的请求日志跟踪过滤器,它们会将请求的一些重要信息记录到日志中,方便程序的调试。这两个日志过滤器只有在日志级别为 DEBUG 时才会起作用:

  方法 说明 
  org.springframework.web.filter.ServletContextRequestLoggingFilter 该过滤器将请求的 URI 记录到 Common 日志中(如通过 Log4J 指定的日志文件); 
  org.springframework.web.filter.ServletContextRequestLoggingFilter 该过滤器将请求的 URI 记录到 ServletContext 日志中。 

  以下是日志过滤器记录的请求跟踪日志的片断:

(JspServlet.java:224) - JspEngine --> /htmlTest.jsp
(JspServlet.java:225) - ServletPath: /htmlTest.jsp
(JspServlet.java:226) - PathInfo: null
(JspServlet.java:227) - RealPath: D:\masterSpring\chapter23\webapp\htmlTest.jsp
(JspServlet.java:228) - RequestURI: /baobaotao/htmlTest.jsp
…


  通过这个请求跟踪日志,程度调试者可以详细地查看到有哪些请求被调用,请求的参数是什么,请求是否正确返回等信息。虽然这两个请求跟踪日志过滤器一般在程序调试时使用,但是即使程序部署不将其从 web.xml 中移除也不会有大碍,因为只要将日志级别设置为 DEBUG 以上级别,它们就不会输出请求跟踪日志信息了。

  转存 Web 应用根目录监听器和 Log4J 监听器 

  Spring 在 org.springframework.web.util 包中提供了几个特殊用途的 Servlet 监听器,正确地使用它们可以完成一些特定需求的功能。比如某些第三方工具支持通过 ${key} 的方式引用系统参数(即可以通过 System.getProperty() 获取的属性),WebAppRootListener 可以将 Web 应用根目录添加到系统参数中,对应的属性名可以通过名为“webAppRootKey”的 Servlet 上下文参数指定,默认为“webapp.root”。下面是该监听器的具体的配置:

清单 6. WebAppRootListener 监听器配置
…
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>baobaotao.root</param-value> ① Web 应用根目录以该属性名添加到系统参数中
</context-param>
…
② 负责将 Web 应用根目录以 webAppRootKey 上下文参数指定的属性名添加到系统参数中
<listener>
<listener-class> 
org.springframework.web.util.WebAppRootListener
</listener-class>
</listener>
…

  这样,您就可以在程序中通过 System.getProperty("baobaotao.root") 获取 Web 应用的根目录了。不过更常见的使用场景是在第三方工具的配置文件中通过${baobaotao.root} 引用 Web 应用的根目录。比如以下的 log4j.properties 配置文件就通过 ${baobaotao.root} 设置了日志文件的地址:

log4j.rootLogger=INFO,R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${baobaotao.root}/WEB-INF/logs/log4j.log ① 指定日志文件的地址
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n


  另一个专门用于 Log4J 的监听器是 Log4jConfigListener。一般情况下,您必须将 Log4J 日志配置文件以 log4j.properties 为文件名并保存在类路径下。Log4jConfigListener 允许您通过 log4jConfigLocation Servlet 上下文参数显式指定 Log4J 配置文件的地址,如下所示:

① 指定 Log4J 配置文件的地址
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
…
② 使用该监听器初始化 Log4J 日志引擎
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
…


  提示

  一些Web应用服务器(如 Tomcat)不会为不同的Web应用使用独立的系统参数,也就是说,应用服务器上所有的 Web 应用都共享同一个系统参数对象。这时,您必须通过webAppRootKey 上下文参数为不同Web应用指定不同的属性名:如第一个 Web 应用使用 webapp1.root 而第二个 Web 应用使用 webapp2.root 等,这样才不会发生后者覆盖前者的问题。此外,WebAppRootListener 和 Log4jConfigListener 都只能应用在 Web 应用部署后 WAR 文件会解包的 Web 应用服务器上。一些 Web 应用服务器不会将Web 应用的 WAR 文件解包,整个 Web 应用以一个 WAR 包的方式存在(如 Weblogic),此时因为无法指定对应文件系统的 Web 应用根目录,使用这两个监听器将会发生问题。 

  Log4jConfigListener 监听器包括了 WebAppRootListener 的功能,也就是说,Log4jConfigListener 会自动完成将 Web 应用根目录以 webAppRootKey 上下文参数指定的属性名添加到系统参数中,所以当您使用 Log4jConfigListener 后,就没有必须再使用 WebAppRootListener了。

  Introspector 缓存清除监听器 

  Spring 还提供了一个名为
org.springframework.web.util.IntrospectorCleanupListener 的监听器。它主要负责处理由 JavaBean Introspector 功能而引起的缓存泄露。IntrospectorCleanupListener 监听器在 Web 应用关闭的时会负责清除 JavaBean Introspector 的缓存,在 web.xml 中注册这个监听器可以保证在 Web 应用关闭的时候释放与其相关的 ClassLoader 的缓存和类引用。如果您使用了 JavaBean Introspector 分析应用中的类,Introspector 缓存会保留这些类的引用,结果在应用关闭的时候,这些类以及Web 应用相关的 ClassLoader 不能被垃圾回收。不幸的是,清除 Introspector 的唯一方式是刷新整个缓存,这是因为没法准确判断哪些是属于本 Web 应用的引用对象,哪些是属于其它 Web 应用的引用对象。所以删除被缓存的 Introspection 会导致将整个 JVM 所有应用的 Introspection 都删掉。需要注意的是,Spring 托管的 Bean 不需要使用这个监听器,因为 Spring 的 Introspection 所使用的缓存在分析完一个类之后会马上从 javaBean Introspector 缓存中清除掉,并将缓存保存在应用程序特定的 ClassLoader 中,所以它们一般不会导致内存资源泄露。但是一些类库和框架往往会产生这个问题。例如 Struts 和 Quartz 的 Introspector 的内存泄漏会导致整个的 Web 应用的 ClassLoader 不能进行垃圾回收。在 Web 应用关闭之后,您还会看到此应用的所有静态类引用,这个错误当然不是由这个类自身引起的。解决这个问题的方法很简单,您仅需在 web.xml 中配置 IntrospectorCleanupListener 监听器就可以了:


<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>


  小结

  本文介绍了一些常用的 Spring 工具类,其中大部分 Spring 工具类不但可以在基于 Spring 的应用中使用,还可以在其它的应用中使用。使用 JDK 的文件操作类在访问类路径相关、Web 上下文相关的文件资源时,往往显得拖泥带水、拐弯抹角,Spring 的 Resource 实现类使这些工作变得轻松了许多。

  在 Web 应用中,有时你希望直接访问 Spring 容器,获取容器中的 Bean,这时使用 WebApplicationContextUtils 工具类从 ServletContext 中获取 WebApplicationContext 是非常方便的。WebUtils 为访问 Servlet API 提供了一套便捷的代理方法,您可以通过 WebUtils 更好的访问 HttpSession 或 ServletContext 的信息。

  Spring 提供了几个 Servlet 过滤器和监听器,其中 ServletContextRequestLoggingFilter 和 ServletContextRequestLoggingFilter 可以记录请求访问的跟踪日志,你可以在程序调试时使用它们获取请求调用的详细信息。WebAppRootListener 可以将 Web 应用的根目录以特定属性名添加到系统参数中,以便第三方工具类通过 ${key} 的方式进行访问。Log4jConfigListener 允许你指定 Log4J 日志配置文件的地址,且可以在配置文件中通过 ${key} 的方式引用 Web 应用根目录,如果你需要在 Web 应用相关的目录创建日志文件,使用 Log4jConfigListener 可以很容易地达到这一目标。

  Web 应用的内存泄漏是最让开发者头疼的问题,虽然不正确的程序编写可能是这一问题的根源,也有可能是一些第三方框架的 JavaBean Introspector 缓存得不到清除而导致的,Spring 专门为解决这一问题配备了 IntrospectorCleanupListener 监听器,它只要简单在 web.xml 中声明该监听器就可以了。

多线程远程下载 java
class  --MyMutilDown

public class MyMutilDown {
/**
	 * 单线程的远程下载
	 */
	public void testOneTDown(String filePath, String url) {
		try {
			// 要写入的文件
			File file = new File(filePath + getFileExtName(url));
			FileWriter fWriter = new FileWriter(file);
			URL ul = new URL(url);
			URLConnection conn = ul.openConnection();
			conn.setConnectTimeout(2000);// 请求超时时间
			// int len = conn.getContentLength();
			InputStream in = conn.getInputStream();
			// byte[] by = new byte[1024];
			int temp = 0;
			while ((temp = in.read()) != -1) {
				fWriter.write(temp);
			}
			fWriter.close();
			in.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 文件后缀名
	 * 
	 * @param path
	 * @return
	 */
	public String getFileExtName(String path) {
		return path.substring(path.lastIndexOf("."));
	}
/**
	 * 测试多线程
	 * 
	 * @param filePath
	 *            文件保存路径
	 * @param url
	 *            url
	 * @param tnum
	 *            线程数量
	 */
	public void testMoreTDown(String filePath, String url, int tnum) {
		try {
			// 要写入的文件
			final File file = new File(filePath + getFileExtName(url));
			RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 建立随机访问
			final URL ul = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
			conn.setConnectTimeout(2000);// 请求超时时间
			conn.setRequestMethod("GET");
			int len = conn.getContentLength();// 文件长度
			accessFile.setLength(len);
			accessFile.close();
			final int block = (len + tnum - 1) / tnum;// 每个线程下载的快大小
			
			for (int i = 0; i < tnum; i++) {
				final int a = i;
				new Thread(new Runnable() {
					int start = block * a;// 开始位置
					int end = block * (a + 1) - 1;// 结束位置
					@Override
					public void run() {
						HttpURLConnection conn2 = null;//http连接
						RandomAccessFile accessFile2 = null;
						InputStream in = null;//从http连接拿到的流
						try {
							conn2 = (HttpURLConnection) ul.openConnection();
							conn2.setConnectTimeout(2000);// 请求超时时间
							conn2.setRequestMethod("GET");
							// TODO Auto-generated method stub
							conn2.setRequestProperty("Range", "bytes=" + start
									+ "-" + end + "");// 设置一般请求属性 范围
							in = conn2.getInputStream();
							byte[] data = new byte[1024];
							int len = 0;
							accessFile2 = new RandomAccessFile(file, "rwd");
							accessFile2.seek(start);
							
							while ((len = in.read(data)) != -1) {
								accessFile2.write(data, 0, len);
							}
							System.out.println("线程:" + a + "下载完成!");
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} finally {
							try {
								accessFile2.close();
								in.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					}
				}).start();
			  
			}
			

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		MyMutilDown mydown = new MyMutilDown();
		String path = "http://static.ishare.down.sina.com.cn/5585234.txt?ssig=f7CrV3UL8%2B&Expires=1347724800&KID=sina,ishare&ip=1347592902,117.40.138.&fn=%E5%8E%9A%E9%BB%91%E5%AD%A6.TXT";
		// mydown.downLoad(path, "D:\\aa", 1);
		// mydown.testOneTDown("D:\\", path);
		mydown.testMoreTDown("D:\\aa", path, 3);
	}
}








list转数组 java
List<TestSql> list
list.toArray(new TestSql[0])
jav全排列 java Java 全排列输出
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class ListAllPrint2 {
	/**
	 * 使用createList方法,填充参数列表传递过来的List,默认是Integer,一般是这个类型,你可以修改别的类型
	 */
	public void createList(int n,List list){
		if(n==0){
			n=3;
		}
		for(int i=1;i<=n;i++){
			list.add(i);
		}
	}
	/**
	 * printAll是输出全排列的递归调用方法,list是传入的list,用LinkedList实现,
	 * 而prefix用于转载以及输出的数据
	 * length用于记载初始list的长度,用于判断程序结束。
	 */
	public void printAll(List candidate, String prefix,int length){
		if(prefix.length()==length)
			 System.out.println(prefix);
		for (int i = 0; i < candidate.size(); i++) {
			 List temp = new LinkedList(candidate);
			 printAll(temp, prefix + temp.remove(i),length);
		}
	}

	/**
	 * 测试代码
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<Integer> list=new ArrayList<Integer>();
		ListAllPrint2 lap=new ListAllPrint2();
		lap.createList(3, list);
		lap.printAll(list,"",list.size());
	}
}
页面刷新记得位置 html
在div处加锚点:<a name="anchor"></a> 
然后页面初始化处加js代码:location.hash="anchor" 
页面刷新就自动定位到锚点了 
list对象排序 list对象排序 List排序

 /**
 * 根据order对User排序 */ 
public class User { 
//此处无需实现Comparable接口 
    private String name; 
    private Integer order; 
    public String getName() {
         return name; 
    }
    public void setName(String name) { 
        this.name = name;
    } 
    public Integer getOrder() {
        return order; 
    }
    public void setOrder(Integer order) { 
       this.order = order;
    } 
}




public class Test{ 
    public static void main(String[] args) {
       User user1 = new User(); 
       user1.setName("a"); 
       user1.setOrder(1);
       User user2 = new User();
       user2.setName("b"); 
       user2.setOrder(2); 
       List<User> list = new ArrayList<User>(); 
       list.add(user2); 
       list.add(user1); 
       Collections.sort(list,new Comparator<User>(){ 
           public int compare(User arg0, User arg1) { 
               return arg0.getOrder().compareTo(arg1.getOrder()); 
           } 
       }); 
       for(User u : list){ 
          System.out.println(u.getName()); 
       } 
    }
 }

iteye分页 jsp 猜测 javaye的分页设计

  int curPage = pageInfo.getPageNo();
        int pageCount = pageInfo.getPageCount();

        if (curPage > pageCount) {   //当前页大于最大页
            curPage = pageCount;
        }

        StringBuffer sb = new StringBuffer();
        sb.append("<div class=\"pagination\">");
        if (curPage > 1) {    // 添加 "上一页"
            // 加上链接 curpage-1
            sb.append("<a href=\"" + getHref(curPage - 1)
                    + "\" class=\"prev_page\" rel=\"prev start\">"
                    + PREVIOUS_PAGE + "</a>");
        } else {
            sb.append("<span class=\"disabled prev_page\">" + PREVIOUS_PAGE + "</span>");
        }

        if ((curPage < liststep) && (pageCount - curPage + 1 < liststep)) {  //显示全部
            for (int i = 1; i <= pageCount; i++) {
                if (i == curPage) {
                    sb.append("<span class=\"current\">" + i + "</span>");
                } else {
                    sb.append(goHref(i));
                }
            }
        } else if ((curPage < liststep) && (pageCount - curPage + 1 >= liststep)) { //显示 1 2 3 ... 45 46
            int left = curPage < 3 ? 3 : curPage + 1;
            for (int i = 1; i <= left; i++) {
                if (i == curPage) {
                    sb.append("<span class=\"current\">" + i + "</span>");
                } else {
                    sb.append(goHref(i));
                }
            }
            sb.append("<span class=\"gap\">&hellip;</span>");
            sb.append(goHref(pageCount - 1));
            sb.append(goHref(pageCount));
        } else if ((curPage >= liststep) && (pageCount - curPage + 1 >= liststep)) {  //显示 1 2 。。。5 6 7 。。45  46
            sb.append(goHref(1));
            sb.append(goHref(2));
            sb.append("<span class=\"gap\">&hellip;</span>");
            sb.append(goHref(curPage - 1));
            sb.append("<span class=\"current\">" + curPage + "</span>");
            sb.append(goHref(curPage + 1));
            sb.append("<span class=\"gap\">&hellip;</span>");
            sb.append(goHref(pageCount - 1));
            sb.append(goHref(pageCount));
        } else if ((curPage >= liststep) && (pageCount - curPage + 1 < liststep)) {  //显示  1 2 。。。 44 45 46
            sb.append(goHref(1));
            sb.append(goHref(2));
            sb.append("<span class=\"gap\">&hellip;</span>");

            int begin = pageCount - curPage + 1 < 3 ? pageCount - 2 : curPage - 1;
            for (int i = begin; i <= pageCount; i++) {
                if (i == curPage) {
                    sb.append("<span class=\"current\">" + i + "</span>");
                } else {
                    sb.append(goHref(i));
                }
            }
        }

        // 显示下-页
        if (curPage != pageCount) {
            // 加上链接 curpage+1
            sb.append("<a href=\"" + getHref(curPage + 1)
                    + "\" class=\"next_page\" rel=\"next\">" + NEXT_PAGE
                    + "</a>");
        } else {
            sb.append("<span class=\"disabled next_page\">" + NEXT_PAGE
                    + "</span>");
        }

        sb.append("</div>");
Collections list对象排序 List排序
/**
* 根据order对User排序
*/
public class User implements Comparable<User>{
    private String name;
    private Integer order;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getOrder() {
        return order;
    }
    public void setOrder(Integer order) {
        this.order = order;
    }
    public int compareTo(User arg0) {
        return this.getOrder().compareTo(arg0.getOrder());
    }
}



public class Test{
    public static void main(String[] args) {
         User user1 = new User();
         user1.setName("a"); user1.setOrder(1); 
         User user2 = new User(); user2.setName("b");
         user2.setOrder(2); 
         List<User> list = new ArrayList<User>(); 
        //此处add user2再add user1 
        list.add(user2); list.add(user1); 
        Collections.sort(list); 
        for(User u : list){ 
            System.out.println(u.getName()); 
        } 
    } 
}


在sqlserver2000与sqlserver2005存储过程的一个问题 sqlserver
一段sql在2005中,编译能通过。2005对动态的sql有很好的支持。
declare cur_votedept cursor  for select  top(@topnum) * from sp_vote_dept_records 
							where deptId=@deptId and voteId=@voteIdOut order by ticketNum desc ;--每个部门的十件大事
						open cur_votedept  
						fetch next from cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
							while(@@FETCH_STATUS=0) 
								begin
									insert into sp_vote_depe_records_ones values(@temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId);
									fetch next from cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
								end
						close cur_votedept;  
						deallocate cur_votedept    
					fetch next from cur_group into @deptId;  


但是在2000中 动态游标中的变量不能直接的使用变量,应该使用全部都是sql拼接的形式。
如
declare @sqlExec  varchar(6000);
						set @sqlExec='declare @cur_votedept cursor for ';
						set @sqlExec=@sqlExec+'SELECT TOP ('+convert(varchar,@topnum)+')* FROM sp_vote_dept_records 
							where deptId='+@deptId+' and voteId='+@voteIdOut+' order by ticketNum desc'
						set @sqlExec=@sqlExec+
						'
								open @cur_votedept  
										fetch next from @cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
											while(@@FETCH_STATUS=0) 
												begin
													insert into sp_vote_depe_records_ones values(@temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId);
													fetch next from cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
												end
										close @cur_votedept;  
										deallocate @cur_votedept    
									fetch next from cur_group into @deptId;   
						';
sqlserver游标作为输出参数 sqlserver
	---各个单位的n件大事   一轮统计结束   返统计之后的结果
if(OBJECT_ID('pro_fristCount','P') is not null)  
    drop procedure  pro_fristCount;
    
go
create procedure  pro_fristCount(@topnum int,@vote_Id nvarchar(100),@cur_fristRecord CURSOR VARYING OUTPUT  )
as
begin
if object_id('tempdb..##depe_records') is not null
	drop table ##depe_records;
create table ##depe_records(   -- 创建临时表
	deptId nvarchar(100),
	deptName nvarchar(100),
	itemId nvarchar(100),
	itemName nvarchar(100),
	ticketNum int,
	voteId nvarchar(100)
);
declare @temp_deptId nvarchar(100),@temp_deptName nvarchar(100),@temp_itemId nvarchar(100),@temp_itemName nvarchar(100),@temp_ticketNum int,@temp_voteId nvarchar(100);--临时表数据
declare @deptId nvarchar(100);
declare cur_group cursor  for select deptId from sp_vote_dept_records where voteId=@vote_Id group by deptId;--按照部门分组
open cur_group 
fetch next from cur_group into @deptId;
while(@@FETCH_STATUS=0)  
	begin  
			declare cur_votedept cursor  for select  top(@topnum) * from sp_vote_dept_records 
				where deptId=@deptId and voteId=@vote_Id order by ticketNum desc ;--每个部门的十件大事
			open cur_votedept  
			fetch next from cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
				while(@@FETCH_STATUS=0) 
					begin
						insert into ##depe_records values(@temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId);
						fetch next from cur_votedept into @temp_deptId,@temp_deptName,@temp_itemId,@temp_itemName,@temp_ticketNum,@temp_voteId;
					end
			close cur_votedept;  
			deallocate cur_votedept    
		fetch next from cur_group into @deptId;  
	end  
close cur_group
deallocate cur_group 
SET @cur_fristRecord = CURSOR  FORWARD_ONLY  STATIC  FOR 
	select * from  ##depe_records where voteId=@vote_Id order by deptId,ticketNum desc; 
open @cur_fristRecord;
end

---测试 调用
begin
declare @temp1_deptId nvarchar(100),@temp1_deptName nvarchar(100),@temp1_itemId nvarchar(100),@temp1_itemName nvarchar(100),@temp1_ticketNum int,@temp1_voteId nvarchar(100);--临时表数据
declare @ss CURSOR;
exec pro_fristCount 10 , '201001081917205007', @ss OUTPUT;
fetch next from  @ss into  @temp1_deptId,@temp1_deptName,@temp1_itemId,@temp1_itemName,@temp1_ticketNum,@temp1_voteId;
while(@@FETCH_STATUS=0) 
	begin
		print @temp1_deptId;
		fetch next from  @ss into  @temp1_deptId,@temp1_deptName,@temp1_itemId,@temp1_itemName,@temp1_ticketNum,@temp1_voteId;
	end
close @ss;  
deallocate @ss 
end
还需要改进,做成电子书生成工具 java
package com.ztenc.oa.proj.util;



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

/**
 * 文字写入图层背景工具类
 * 
 * 内容过多自动分页
 * 
 * 落款自动写入格式
 * 
 * @author fule
 */
public class ImageWUtil {

	// 常量字体大小
	public final static int LARGESIZE = 100; // 大字体
	public final static int NORMALSIZE = 50; // 普通字体
	public final static int SMALLSIZE = 30; // 小字体
	// 段间距
	public final static int SECTSIZE = 80;
	// 文字区边距
	public final static int PADDING = 100;
	public final static Color DEAUFT_COLOR = Color.WHITE;

	// 连续书写时的记录位
	int pointIndex;

	// title书写之后的记录位
	int pointOnTitle;

	// 当前第几页
	int indexPage = 1;

	Map<Integer, String> map;

	/**
	 * 设置当前书写的像素位子
	 * 
	 * @return
	 */
	private int setPointIndex(int increment) {
		pointIndex += increment;
		return pointIndex;
	}

	/**
	 * 内容区字体大小
	 */
	private int contentFontSize = NORMALSIZE;

	/**
	 * 标题字体大小
	 */
	private int titleFontSize = LARGESIZE;

	/**
	 * 段间距
	 */
	private int secttSize = SECTSIZE;

	/**
	 * 文本域边距大小
	 */
	private int contentPadding = PADDING;

	/**
	 * 画笔颜色
	 */

	private Color color;

	/**
	 * 背景图片
	 */
	private File bgFile;

	/**
	 * 设置背景图
	 * 
	 * @param bgFile
	 */
	public void setBgFile(File bgFile) {
		this.bgFile = bgFile;
	}

	/**
	 * 设置画笔颜色 默认白色
	 * 
	 * @param color
	 */
	public void setColor(Color color) {
		this.color = color;
	}

	/**
	 * 设置内容区字体大小 默认NORMALSIZE = 50
	 */
	public void setContentFontSize(int contentFontSize) {
		this.contentFontSize = contentFontSize;
	}

	/**
	 * 设置标题字体大小 默认LARGESIZE = 100
	 */
	public void setTitleFontSize(int titleFontSize) {
		this.titleFontSize = titleFontSize;
	}

	/**
	 * 设置段间距 默认SECTSIZE = 70
	 * 
	 * @param secttSize
	 */
	public void setSecttSize(int secttSize) {
		this.secttSize = secttSize;
	}

	/**
	 * 设置文本边距 默认PADDING70
	 * 
	 * @param contentPadding
	 */
	public void setContentPadding(int contentPadding) {
		this.contentPadding = contentPadding;
	}

	/**
	 * 合成图片 title 标题 testContext 段落
	 * 
	 * @return
	 * @throws Exception
	 */

	public boolean compound(String strTitleString, String context,
			String[] luokuan) throws Exception {

		BufferedImage bi = null;
		try {
			bi = ImageIO.read(bgFile);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		int imgWidth = bi.getWidth();
		int ImgHeight = bi.getHeight();
		Graphics2D g = getGraphics(bi);
		Font titleFont = new Font("微软雅黑", Font.PLAIN, titleFontSize);// 标题
		Font contentFont = new Font("微软雅黑", Font.PLAIN, contentFontSize);// 内容
		Font luoKuanFont = new Font("微软雅黑", Font.PLAIN, contentFontSize);// 落款
		if (strTitleString == null && context == null && luokuan == null) {
			throw new Exception("没有数据,没有写入任何数据");
		} else {
			g.setFont(contentFont);
			Map<Integer, String> pagemap = getPageStrings(imgWidth, ImgHeight,
					strTitleString, context);
			for (int i = 1; i <= pagemap.size(); i++) {
				pointIndex = 0;// 初始化
				String pageContent = pagemap.get(i);
				if (strTitleString != null) {
					drawTitle(titleFont, imgWidth, strTitleString, g);
				}
				String[] testContext = getContents(pageContent);// 每一页段数据
				if (testContext != null) {
					for (int j = 0; j < testContext.length; j++) {
						drawContent(imgWidth, testContext[j], g);
					}
					if (pagemap.size() == 1 || i == pagemap.size()) {
						setPointIndex(2 * secttSize);// 设置落款 开始位置
						if (luokuan != null) {
							drawLuoKuan(imgWidth, luokuan, luoKuanFont, g);
						}
					}
				}
				try {
					String fatherPath = bgFile.getParent();
					String filenameString = fatherPath+"/"+bgFile.getName() + i + ".jpg";
					File f = new File(filenameString);
					// ImageIO.write(bi, "jpg", bgFile);
					ImageIO.write(bi, "jpg", f);
					bi = ImageIO.read(bgFile);
					g = getGraphics(bi);
					g.setFont(contentFont);
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
			g.dispose();
			System.out.println("合成完毕");
			return true;
		}

	}

	private Graphics2D getGraphics(BufferedImage bi) {
		Graphics2D g = bi.createGraphics();
		// 字体平滑
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g.setColor(color);
		return g;
	}

	/**
	 * 写入标题 居中 字数过多换行
	 * 
	 * @param width
	 * @param title
	 * @param g
	 */
	public void drawTitle(Font font, int width, String title, Graphics2D g) {
		AttributedString as = null;
		title = ToSBC(title);
		int fullLen = (width - contentPadding * 2) / titleFontSize;// 一行的最多容量
		int titleLen = title.length();
		if (titleLen > fullLen) {
			String s = title;
			int writeLen = (s.length() + fullLen - 1) / fullLen;// 可写入行数
			String string;
			int sum = 0;
			for (int i = 0; i < writeLen - 1; i++) {
				int begin = i * fullLen;
				int end = begin + fullLen;
				string = s.substring(begin, end);// TODO
				int sl = string.length();// 实际每行写入字数
				as = new AttributedString(string);
				as.addAttribute(TextAttribute.FONT, font);
				g.drawString(as.getIterator(), width / 2 - sl / 2
						* titleFontSize, pointIndex
						+ (titleFontSize + secttSize / 2) * (i + 1));// i+1
																		// 去除二段重行
			}
			string = s.substring((writeLen - 1) * fullLen);
			as = new AttributedString(string);
			as.addAttribute(TextAttribute.FONT, font);
			g.drawString(as.getIterator(), width / 2 - string.length() / 2
					* titleFontSize, pointIndex
					+ (titleFontSize + secttSize / 2) * writeLen);// 最后一行
			sum += (titleFontSize + secttSize) * writeLen;
			setPointIndex(sum);
		} else {
			as = new AttributedString(title);
			as.addAttribute(TextAttribute.FONT, font);
			g.drawString(as.getIterator(), width / 2 - titleLen / 2
					* titleFontSize, setPointIndex(titleFontSize + secttSize));

		}
		pointOnTitle = pointIndex;
	}

	/**
	 * 写入落款
	 * 
	 * 从后面往前写
	 * 
	 * @param width
	 * @param wsString
	 *            内容
	 * @param g
	 * @throws Exception
	 */
	public void drawLuoKuan(int width, String[] wsString, Font font,
			Graphics2D g) throws Exception {
		AttributedString as = null;
		int padding = 2;
		int fontsize = font.getSize();
		int fullLen = (width - contentPadding * 2) / fontsize;// 一行的最多容量
		for (int i = 0; i < wsString.length; i++) {
			wsString[i] = ToSBC(wsString[i]);
			if (wsString[i].length() > fullLen) {
				throw new Exception("落款长度过长");
			}
			as = new AttributedString(wsString[i]);
			as.addAttribute(TextAttribute.FONT, font);
			if (wsString[0].length() > wsString[1].length()) {
				if (i == 0) {
					g.drawString(as.getIterator(),
							(fullLen - wsString[0].length() + padding)
									* fontsize, setPointIndex(fontsize
									+ secttSize));
					setPointIndex(-(secttSize / 2));
				} else {
					g.drawString(
							as.getIterator(),
							(fullLen
									- wsString[1].length()
									+ ((wsString[1].length() - wsString[0]
											.length()) / 2) + padding)
									* fontsize, setPointIndex(fontsize
									+ secttSize));
				}
			} else if (wsString[0].length() < wsString[1].length()) {
				if (i == 0) {
					g.drawString(
							as.getIterator(),
							(fullLen
									- wsString[0].length()
									+ ((wsString[0].length() - wsString[1]
											.length()) / 2) + padding)
									* fontsize, setPointIndex(fontsize
									+ secttSize));
					setPointIndex(-(secttSize / 2));
				} else {
					g.drawString(as.getIterator(),
							(fullLen - wsString[1].length() + padding)
									* fontsize, setPointIndex(fontsize
									+ secttSize));
				}
			}else {
				g.drawString(as.getIterator(),
						(fullLen - wsString[0].length() + padding)
								* fontsize, setPointIndex(fontsize
								+ secttSize));
				setPointIndex(-(secttSize / 2));
			}
		}

	}

	/**
	 * 文本边距为1个字符,首行缩进2个字符
	 * 
	 * 写入段落 内容区 一个字的像素为SMALLSIZE
	 * 
	 * @param width
	 *            图片宽度
	 * @param height
	 *            图片高度
	 * @param content
	 * @param g
	 */
	public void drawContent(int width, String content, Graphics2D g) {
		content = ToSBC(content);
		int fullFontLen = (width - contentPadding * 2) / contentFontSize;// 满行写入
																			// 可写长度(字数)
		String duanshou;
		int writeLen;
		int sum = 0;
		if (content.length() < fullFontLen - 2) {
			duanshou = content;
			writeLen = 1;
			g.drawString(duanshou, contentPadding + 2 * contentFontSize,
					setPointIndex(2 * secttSize));
		} else {
			duanshou = content.substring(0, fullFontLen - 2);// 段首 缩进两个字
			writeLen = (content.substring(duanshou.length() + 1).length()
					+ fullFontLen - 1)
					/ fullFontLen; // 可写入行数 不含段首行

			// 写入段首 段的开始 2*secttSize 段分割行
			g.drawString(duanshou, contentPadding + 2 * contentFontSize,
					setPointIndex(2 * secttSize));
			// 除去段首的内容区
			String str = content.substring(duanshou.length());
			// 写入内容
			String string;
			for (int i = 0; i < writeLen - 1; i++) {
				int begin = i * fullFontLen;
				int end = begin + fullFontLen;
				string = str.substring(begin, end);// TODO
				g.drawString(string, contentPadding, pointIndex + secttSize
						+ secttSize * i);
			}
			string = str.substring((writeLen - 1) * fullFontLen);
			g.drawString(string, contentPadding, pointIndex + secttSize
					+ secttSize * (writeLen - 1));// 最后一行d
			sum += ((secttSize) * (writeLen));// 段落之间的间隙
			setPointIndex(sum);
		}

	}

	/**
	 * 是否存在下一页
	 * 
	 * @param point
	 * @param height
	 * @return
	 */
	public boolean hasNextPage(int height) {
		if (pointIndex > (height - 2 * secttSize)) {
			// 存在下一页新页开始
			pointIndex = 0;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 写入内容时是否产生分页 TODO 第一段就超出页 除第一段之后的超页
	 * 
	 * @param height
	 *            高度
	 * @param width
	 *            宽度
	 * @param testContext
	 * @return map<页码,内容>
	 */
	private Map<Integer, String> getPageStrings(int width, int height,
			String title, String testContext) {
		title = ToSBC(title);
		int titleFullLen = (width - contentPadding * 2) / titleFontSize;// 一行标题的最多容量
		int titleWriteLen = (title.length() + titleFullLen - 1) / titleFullLen;// 标题占有行
		int titleHeight = titleWriteLen * (titleFontSize + secttSize);// 标题高度

		int fullFontLen = (width - contentPadding * 2) / contentFontSize;// 满行写入可写长度(字数)

		int contentHeight = getDuanLuoHeight(fullFontLen, titleHeight, height,
				testContext);

		// int contentHeight = getContents(testContext).length * 2 *
		// secttSize;// 满区内容段落间距总高度

		int bgTotalRows = (height - titleHeight - contentHeight) / secttSize
				- 3;// 除去落款,背景可书写总行数

		int vTotalRows = (testContext.length() + fullFontLen - 1) / fullFontLen;// 实际内容所需行数

		// TDOD
		int fullWord = bgTotalRows * fullFontLen;// 满屏写入内容字数
		if (map == null) {
			map = new HashMap<Integer, String>();
		}
		if (vTotalRows < bgTotalRows) {
			map.put(indexPage, testContext);
		} else {
			int count = 0;

			int pageCount = (vTotalRows + bgTotalRows - 1) / bgTotalRows;// 需要总页数
			String string;
			for (int i = count; i < pageCount; i++) {
				if (i == pageCount - 1) {
					string = testContext.substring(i * fullWord);// 最后一页
				} else {
					string = testContext.substring(i * fullWord, (i + 1)
							* fullWord);
				}
				// System.out.println("当页内容:\n"+string);
				map.put(indexPage, string);
				indexPage++;

			}
		}
		System.out.println("总页数" + map.size());
		return map;
	}

	// 每页段落总间隙
	// 如果是第一页 写入 如果是其他的 算满屏额
	private int getDuanLuoHeight(int fullFontLen, int titleHeight, int height,
			String testContext) {
		int bgTotalRows = (height - titleHeight) / secttSize - 4;// 满页可写入行数
		int fullWord = bgTotalRows * fullFontLen;// 满屏写入内容字数
		int wlen = testContext.length();
		if (wlen < fullWord) {
			return getContents(testContext).length * 2 * secttSize;
		} else {
			return getContents(testContext.substring(0, fullWord)).length * 2
					* secttSize;
		}
	}

	/**
	 * 字符串处理
	 */
	private String[] getContents(String str) {
		while (str.startsWith("\r\n")) {
			str = str.substring(2);
		}
		String[] a = str.split("\\s{1,}");
		return a.length == 0 ? null : a;
	}

	/**
	 * 字符串处理
	 * 
	 * @param str
	 * @return
	 * @deprecated
	 */
	private String[] getContent(String str) {

		String string = str.replace("\r\n", "");
		string = string.replace("<p>", "{");
		string = string.replace("</p>", "}");
		List<String> list = new ArrayList<String>();
		while (string.indexOf("{") > -1) {
			int start = string.indexOf("{") + 1;
			int end = string.indexOf("}");
			String st = string.substring(start, end);
			list.add(st);
			string = string.substring(end + 1);
		}
		for (int i = 0; i < list.size(); i++) {
			if ("".equals(list.get(i)) || list.get(i) == null) {
				list.remove(i);
			}
		}
		String[] a = list.toArray(new String[0]);
		return a.length == 0 ? null : a;
	}

	// 半角转全角:
	public static String ToSBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	/**
	 * @param args
	 * @throws IOException
	 *             test
	 * 
	 */

	/*public static void main(String[] args) throws IOException {
		ImageWUtil iUtil = new ImageWUtil();
		iUtil.setBgFile(new File("D:/testbook/bg.jpg"));
		iUtil.setColor(Color.WHITE);
		iUtil.setTitleFontSize(60);
		iUtil.setContentFontSize(45);
		iUtil.setContentPadding(70);
		iUtil.setSecttSize(70);
		String d = "";
		FileInputStream fInputStream = new FileInputStream(new File(
				"D:/testbook/testbook.txt"));
		byte[] by2 = new byte[5 * 1024];

		int temp = fInputStream.read(by2);

		d = new String(by2, 0, temp);

		// System.out.println(d);
		fInputStream.close();
		String t = "编程改革";
		String lk1 = "卡卡卡办公厅发";
		String lk2 = "二零一二年世界的风行 谨在此";
		try {
			iUtil.compound(t, d, new String[] { lk1, lk2 });
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 * String
		 * test="\r\n\r\n\r\n\r\n\r\nasasa\r\n\r\nsasa\r\n\r\nsdasda\r\n\r\n";
		 * String s[] =iUtil.getContents(test); System.out.println(s.length);
		 * for (String string : s) { System.out.println(string); }
		 
	}
*/
}
eclipse 快捷 eclipse
Ctrl+1 快速修复(最经典的快捷键,就不用多说了)
Ctrl+D: 删除当前行 
Ctrl+Alt+↓ 复制当前行到下一行(复制增加)
Ctrl+Alt+↑ 复制当前行到上一行(复制增加)
Alt+↓ 当前行和下面一行交互位置(特别实用,可以省去先剪切,再粘贴了)
Alt+↑ 当前行和上面一行交互位置(同上)
Alt+← 前一个编辑的页面
Alt+→ 下一个编辑的页面(当然是针对上面那条来说了)
Alt+Enter 显示当前选择资源(工程,or 文件 or文件)的属性
Shift+Enter 在当前行的下一行插入空行(这时鼠标可以在当前行的任一位置,不一定是最后)
Shift+Ctrl+Enter 在当前行插入空行(原理同上条)
Ctrl+Q 定位到最后编辑的地方
Ctrl+L 定位在某行 (对于程序超过100的人就有福音了)
Ctrl+M 最大化当前的Edit或View (再按则反之)
Ctrl+/ 注释当前行,再按则取消注释
Ctrl+O 快速显示 OutLine
Ctrl+T 快速显示当前类的继承结构
Ctrl+W 关闭当前Editer
Ctrl+K 参照选中的Word快速定位到下一个
Ctrl+E 快速显示当前Editer的下拉列表(如果当前页面没有显示的用黑体表示)
Ctrl+/(小键盘) 折叠当前类中的所有代码
Ctrl+×(小键盘) 展开当前类中的所有代码
Ctrl+Space 代码助手完成一些代码的插入(但一般和输入法有冲突,可以修改输入法的热键,也可以暂用Alt+/来代替)
Ctrl+Shift+E 显示管理当前打开的所有的View的管理器(可以选择关闭,激活等操作)
Ctrl+J 正向增量查找(按下Ctrl+J后,你所输入的每个字母编辑器都提供快速匹配定位到某个单词,如果没有,则在stutes line中显示没有找到了,查一个单词时,特别实用,这个功能Idea两年前就有了)
Ctrl+Shift+J 反向增量查找(和上条相同,只不过是从后往前查)
Ctrl+Shift+F4 关闭所有打开的Editer
Ctrl+Shift+X 把当前选中的文本全部变味小写
Ctrl+Shift+Y 把当前选中的文本全部变为小写
Ctrl+Shift+F 格式化当前代码
Ctrl+Shift+P 定位到对于的匹配符(譬如{}) (从前面定位后面时,光标要在匹配符里面,后面到前面,则反之)

下面的快捷键是重构里面常用的,本人就自己喜欢且常用的整理一下(注:一般重构的快捷键都是Alt+Shift开头的了)
Alt+Shift+R 重命名 (是我自己最爱用的一个了,尤其是变量和类的Rename,比手工方法能节省很多劳动力)
Alt+Shift+M 抽取方法 (这是重构里面最常用的方法之一了,尤其是对一大堆泥团代码有用)
Alt+Shift+C 修改函数结构(比较实用,有N个函数调用了这个方法,修改一次搞定)
Alt+Shift+L 抽取本地变量( 可以直接把一些魔法数字和字符串抽取成一个变量,尤其是多处调用的时候)
Alt+Shift+F 把Class中的local变量变为field变量 (比较实用的功能)
Alt+Shift+I 合并变量(可能这样说有点不妥Inline)
Alt+Shift+V 移动函数和变量(不怎么常用)
Alt+Shift+Z 重构的后悔药(Undo)

编辑
作用域 功能 快捷键 
全局 查找并替换 Ctrl+F 
文本编辑器 查找上一个 Ctrl+Shift+K 
文本编辑器 查找下一个 Ctrl+K 
全局 撤销 Ctrl+Z 
全局 复制 Ctrl+C 
全局 恢复上一个选择 Alt+Shift+↓ 
全局 剪切 Ctrl+X 
全局 快速修正 Ctrl1+1 
全局 内容辅助 Alt+/ 
全局 全部选中 Ctrl+A 
全局 删除 Delete 
全局 上下文信息 Alt+?
Alt+Shift+?
Ctrl+Shift+Space 
Java编辑器 显示工具提示描述 F2 
Java编辑器 选择封装元素 Alt+Shift+↑ 
Java编辑器 选择上一个元素 Alt+Shift+← 
Java编辑器 选择下一个元素 Alt+Shift+→ 
文本编辑器 增量查找 Ctrl+J 
文本编辑器 增量逆向查找 Ctrl+Shift+J 
全局 粘贴 Ctrl+V 
全局 重做 Ctrl+Y 

 
查看
作用域 功能 快捷键 
全局 放大 Ctrl+= 
全局 缩小 Ctrl+- 

 
窗口
作用域 功能 快捷键 
全局 激活编辑器 F12 
全局 切换编辑器 Ctrl+Shift+W 
全局 上一个编辑器 Ctrl+Shift+F6 
全局 上一个视图 Ctrl+Shift+F7 
全局 上一个透视图 Ctrl+Shift+F8 
全局 下一个编辑器 Ctrl+F6 
全局 下一个视图 Ctrl+F7 
全局 下一个透视图 Ctrl+F8 
文本编辑器 显示标尺上下文菜单 Ctrl+W 
全局 显示视图菜单 Ctrl+F10 
全局 显示系统菜单 Alt+- 

 
导航
作用域 功能 快捷键 
Java编辑器 打开结构 Ctrl+F3 
全局 打开类型 Ctrl+Shift+T 
全局 打开类型层次结构 F4 
全局 打开声明 F3 
全局 打开外部javadoc Shift+F2 
全局 打开资源 Ctrl+Shift+R 
全局 后退历史记录 Alt+← 
全局 前进历史记录 Alt+→ 
全局 上一个 Ctrl+, 
全局 下一个 Ctrl+. 
Java编辑器 显示大纲 Ctrl+O 
全局 在层次结构中打开类型 Ctrl+Shift+H 
全局 转至匹配的括号 Ctrl+Shift+P 
全局 转至上一个编辑位置 Ctrl+Q 
Java编辑器 转至上一个成员 Ctrl+Shift+↑ 
Java编辑器 转至下一个成员 Ctrl+Shift+↓ 
文本编辑器 转至行 Ctrl+L 

 
搜索
作用域 功能 快捷键 
全局 出现在文件中 Ctrl+Shift+U 
全局 打开搜索对话框 Ctrl+H 
全局 工作区中的声明 Ctrl+G 
全局 工作区中的引用 Ctrl+Shift+G 

 
文本编辑
作用域 功能 快捷键 
文本编辑器 改写切换 Insert 
文本编辑器 上滚行 Ctrl+↑ 
文本编辑器 下滚行 Ctrl+↓ 

 
文件
作用域 功能 快捷键 
全局 保存 Ctrl+X 
Ctrl+S 
全局 打印 Ctrl+P 
全局 关闭 Ctrl+F4 
全局 全部保存 Ctrl+Shift+S 
全局 全部关闭 Ctrl+Shift+F4 
全局 属性 Alt+Enter 
全局 新建 Ctrl+N 

 
项目
作用域 功能 快捷键 
全局 全部构建 Ctrl+B 

 
源代码
作用域 功能 快捷键 
Java编辑器 格式化 Ctrl+Shift+F 
Java编辑器 取消注释 Ctrl+\ 
Java编辑器 注释 Ctrl+/ 
Java编辑器 添加导入 Ctrl+Shift+M 
Java编辑器 组织导入 Ctrl+Shift+O 
Java编辑器 使用try/catch块来包围 未设置,太常用了,所以在这里列出,建议自己设置。
也可以使用Ctrl+1自动修正。 

 
运行
作用域 功能 快捷键 
全局 单步返回 F7 
全局 单步跳过 F6 
全局 单步跳入 F5 
全局 单步跳入选择 Ctrl+F5 
全局 调试上次启动 F11 
全局 继续 F8 
全局 使用过滤器单步执行 Shift+F5 
全局 添加/去除断点 Ctrl+Shift+B 
全局 显示 Ctrl+D 
全局 运行上次启动 Ctrl+F11 
全局 运行至行 Ctrl+R 
全局 执行 Ctrl+U 

 
重构
作用域 功能 快捷键 
全局 撤销重构 Alt+Shift+Z 
全局 抽取方法 Alt+Shift+M 
全局 抽取局部变量 Alt+Shift+L 
全局 内联 Alt+Shift+I 
全局 移动 Alt+Shift+V 
全局 重命名 Alt+Shift+R 
全局 重做 Alt+Shift+Y 
sqlserver 查询数据表 字段类型 sqlserver http://www.path8.net/tn/archives/773
方法一
sp_columns   表名

方法 二
SELECT DISTINCT sysobjects.name, syscolumns.colid,syscolumns.name, systypes.name, syscolumns.prec, syscolumns.scale
FROM syscolumns, sysobjects, systypes
WHERE sysobjects.id = syscolumns.id AND systypes.type = syscolumns.type AND ((sysobjects.type='u'))

在应用SQL Server的基于客户机/服务器体系结构的信息系统开发中,
有时需 要将后台SQL Server上的某一数据库的表结构都打印出来,
以便于开发人员查阅及最终文档的形成。SQL Server本身提供了一个系统存储过程 (SP_COLUMNS),
可以完成对单个表结构的查询,只要在SQL Server的ISQL-W工具中键入SP_COLUMNS “表名”,
并执行即 可得到结果集。但该方法有许多不足之处,其主要缺点是:
1) 只能对单表进行操作,当需要查询一个数据库中所有的表时,需要多次执行SP_COLUMNS ,因此显得非常繁琐。
2) 查询结果集中包含了许多不必要的信息。
下面我们创建一个存储过程来完成对某一个数据库中所有表结构的查询。
在创建一个数据库的同时,系统会自动建立一些系统表,限于篇幅的缘故我们在这里只介绍与应用实例有关的三个系统表(SYSOBJECTS,SYSCOLUMNS,SYSTYPES)及其相关的字段。
表SYSOBJECTS为数据库内创建的每个对象(约束,规则,表,视图,触发器等)创建一条记录。
该表相关字段的含义如下:
SYSOBJECTS.name 对象名,如:表名,视图名。
SYSOBJECTS.id 对象id。
SYSOBJECTS.type 对象类型(p存储过程,v视图,s系统表,u用户表)。
表SYSCOLUMNS 为每个表、视图中的每个列和每个存储过程的每个参数创建一条记录。
该表相关字段的含义如下:(此处的列系指数据库中每个表、视图中的列)
SYSCOLUMNS. id 该列所属的表的id,可与SYSOBJECTS.id相关联
SYSCOLUMNS.colid 列id,表示该列是表或视图的第几列。
SYSCOLUMNS.type 物理存储类型,可与SYSTYPES.type相关联。
SYSCOLUMNS.length 数据的物理长度。
SYSCOLUMNS.name 列名字,即字段名。
SYSCOLUMNS .Pre 列的精度级。
SYSCOLUMNS .Scale 列的标度级。
表SYSTYPES 为每个系统和每个用户提供的数据类型创建一条记录,如果它们存在,给定域和默认值,描述系统提供的数据类型的行不可更改。
该表相关字段的含义如下:
SYSTYPES.name 数据类型的名字。
SYSTYPES.type 物理存储数据类型。
在SQL SERVER的企业管理器(SQL ENTERPRISE MANAGER)中,选定某一数据库,创建存储过程print_dbstructure。
源代码如下:
if exists (select * from sysobjects where id = object_id('dbo. print_dbstructure
') and sysstat & 0xf = 4) 存储过程
drop procedure dbo. print_dbstructure

GO
CREATE PROCEDURE print_dbstructure

AS
SELECT DISTINCT sysobjects.name, syscolumns.colid,
syscolumns.name, systypes.name, syscolumns.prec, syscolumns.scale
FROM syscolumns, sysobjects, systypes
WHERE sysobjects.id = syscolumns.id AND systypes.type = syscolumns.type AND ((sysobjects.type='u'))

GO

首先判断是否存在一个名为print_dbstructure的存储过程,如果存在,就摘除它,否则,定义SQL语句建立新的存储过程。从三个系统表中选出满足条件的记录(即该数据库中保存在系统表中的用户表信息)。
执行时,在ISQL_W工具中,选定print_dbstructure所在的数据库,执行该存储过程,即可得到结果集(即该数据库中用户表的结构信息)。
java算法 java 一道java面试题
	boolean isPalindrome(String src){
		char[] cs=src.toCharArray();
		int k=cs.length;
		if(k==1)
			return false;
		for(int i=0;i<=(k)/2;i++){
			k--;
			if((cs[i]^cs[k])!=0&&i<k){
				return false;
			}
		}
		return true;
	}
	boolean isAnagram(String strA,String strB){
		char[] csA=strA.toCharArray();
		char[] csB=strB.toCharArray();
		if(csA.length!=csB.length)
			return false;
		int result=0;
		for(int i=0;i<csA.length;i++){
			result^=(csA[i]^csB[i]);
		}
		return result==0;
	}
一道面试题 java
package com.qustion;

import java.util.Arrays;

public class TestPalindrome {

	/**
	 * @param args
	 * @author fule
	 * @time 2012/03/19
	 *

	// 判断  s的某种anagram是palindrome
	public int isAnagramOfPalindrome(String str) {
		char[] ch = splitString(str);
		if (str != null) {
			int[] sata = totalSee(ch);
			if (sata[1] > 1) {
				return 0;
			} else {
				if (sata[0] % 2 == 0||sata[1]==1) {
					return 1;
				} else {
					return 0;
				}
			}
		} else {
			return 0;
		}
	}

	// 拆分成字符数组 返回排好序的字符数组 为之后的遍历查找 赋值做准备
	public char[] splitString(String str) {
		int len = str.length();
		char[] ch = new char[len];
		for (int i = 0; i < len; i++) {
			ch[i] = str.charAt(i);
		}
		for (int i = 0; i < ch.length - 1; i++) {
			int minPos = i;// 记录最小的位置
			for (int j = i + 1; j < ch.length; j++) {
				if (ch[j] < ch[minPos]) {
					minPos = j;
					char temp = ch[minPos];
					ch[minPos] = ch[i];
					ch[i] = temp;
				}
			}
		}
		return ch;
	}

	// 统计相同的字母将它设值为一 统计相同字母出现的
	public int[] totalSee(char[] ch) {
		int len = ch.length;
		int resultCountSame = 0;// 计算相同字母出现的总得次数
		int countNoSame = 0;// 独立字母的总个数
		int countSame = 1;//每一次查找 获得的相同字母总次数之和 不包括开头的哪一位
		int[] a = new int[2];// 统计相同字母的总个数 和 独立字母的总个数
		for (int i = 0; i < len; i+=countSame) {
			for (int j = i + 1; j < len; j++) {
				if (ch[j] !='1') {
					if (ch[i] == ch[j]) {
						countSame++;
						ch[j] = '1';// 计算完之后 为了统计别 的字母 将值1作为标志

					} else {
							continue;
					}
				}
			}ch[i] ='1';//这里是开始计算的首字母
		}

		for(int i = 0;i<len;i++){
			if(ch[i]=='1'){
				resultCountSame++;
			}else{
				countNoSame++;
			}
		}
		a[0] = resultCountSame;
		a[1] = countNoSame;
		return a;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*
		 * String str = "aasasasaaa"; TestPalindrome te = new TestPalindrome();
		 * System.out.println(Arrays.toString(te.splitString(str)));
		 * System.out.println(Arrays.toString(str.split("a")));
		 */
		TestPalindrome te = new TestPalindrome();
		String testStr = "kayak";
		int result = te.isAnagramOfPalindrome(testStr);
		System.out.println(result);
	}

}
Tomcat配置详解 jsp http://www.iteye.com/topic/178672
目录结构
G:\Workspace\MyeclipseWk\.metadata\.plugins\com.genuitec.eclipse.easie.tomcat.myeclipse\tomcat
--conf  tomcat配置目录
--work  项目翻译成的java代码和class文件
--webapps 项目目录
--temp 临时文件

1 - Tomcat Server的组成部分 
1.1 - Server 
A Server element represents the entire Catalina servlet container. (Singleton) 
1.2 - Service 
A Service element represents the combination of one or more Connector components that share a single Engine 
Service是这样一个集合:它由一个或者多个Connector组成,以及一个Engine,负责处理所有Connector所获得的客户请求 
1.3 - Connector 
一个Connector将在某个指定端口上侦听客户请求,并将获得的请求交给Engine来处理,从Engine处获得回应并返回客户 
TOMCAT有两个典型的Connector,一个直接侦听来自browser的http请求,一个侦听来自其它WebServer的请求 
Coyote Http/1.1 Connector 在端口8080处侦听来自客户browser的http请求 
Coyote JK2 Connector 在端口8009处侦听来自其它WebServer(Apache)的servlet/jsp代理请求 
1.4 - Engine 
The Engine element represents the entire request processing machinery associated with a particular Service 
It receives and processes all requests from one or more Connectors 
and returns the completed response to the Connector for ultimate transmission back to the client 
Engine下可以配置多个虚拟主机Virtual Host,每个虚拟主机都有一个域名 
当Engine获得一个请求时,它把该请求匹配到某个Host上,然后把该请求交给该Host来处理 
Engine有一个默认虚拟主机,当请求无法匹配到任何一个Host上的时候,将交给该默认Host来处理 
1.5 - Host 
代表一个Virtual Host,虚拟主机,每个虚拟主机和某个网络域名Domain Name相匹配 
每个虚拟主机下都可以部署(deploy)一个或者多个Web App,每个Web App对应于一个Context,有一个Context path 
当Host获得一个请求时,将把该请求匹配到某个Context上,然后把该请求交给该Context来处理 
匹配的方法是“最长匹配”,所以一个path==""的Context将成为该Host的默认Context 
所有无法和其它Context的路径名匹配的请求都将最终和该默认Context匹配 
1.6 - Context 
一个Context对应于一个Web Application,一个Web Application由一个或者多个Servlet组成 
Context在创建的时候将根据配置文件$CATALINA_HOME/conf/web.xml和$WEBAPP_HOME/WEB-INF/web.xml载入Servlet类 
当Context获得请求时,将在自己的映射表(mapping table)中寻找相匹配的Servlet类 
如果找到,则执行该类,获得请求的回应,并返回 
2 - Tomcat Server的结构图 

3 - 配置文件$CATALINA_HOME/conf/server.xml的说明 
该文件描述了如何启动Tomcat Server 


<!-- 启动Server 
     在端口8005处等待关闭命令 
     如果接受到"SHUTDOWN"字符串则关闭服务器 
     --> 

<Server port="8005" shutdown="SHUTDOWN" debug="0"> 


  <!-- Listener ??? 
       目前没有看到这里 
       --> 

  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" debug="0"/> 
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" debug="0"/> 


  <!-- Global JNDI resources ??? 
       目前没有看到这里,先略去 
       --> 

  <GlobalNamingResources> 
    ... ... ... ... 
  </GlobalNamingResources> 


  <!-- Tomcat的Standalone Service 
       Service是一组Connector的集合 
       它们共用一个Engine来处理所有Connector收到的请求 
       --> 

  <Service name="Tomcat-Standalone"> 


    <!-- Coyote HTTP/1.1 Connector 
         className : 该Connector的实现类是org.apache.coyote.tomcat4.CoyoteConnector 
         port : 在端口号8080处侦听来自客户browser的HTTP1.1请求 
         minProcessors : 该Connector先创建5个线程等待客户请求,每个请求由一个线程负责 
         maxProcessors : 当现有的线程不够服务客户请求时,若线程总数不足75个,则创建新线程来处理请求 
         acceptCount : 当现有线程已经达到最大数75时,为客户请求排队 
                       当队列中请求数超过100时,后来的请求返回Connection refused错误 
         redirectport : 当客户请求是https时,把该请求转发到端口8443去 
         其它属性略 
         --> 

    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector" 
               port="8080" 
               minProcessors="5" maxProcessors="75" acceptCount="100" 
               enableLookups="true" 
               redirectPort="8443" 
               debug="0" 
               connectionTimeout="20000" 
               useURIValidationHack="false" 
               disableUploadTimeout="true" /> 


    <!-- Engine用来处理Connector收到的Http请求 
         它将匹配请求和自己的虚拟主机,并把请求转交给对应的Host来处理 
         默认虚拟主机是localhost 
         --> 

    <Engine name="Standalone" defaultHost="localhost" debug="0"> 
    

      <!-- 日志类,目前没有看到,略去先 --> 

      <Logger className="org.apache.catalina.logger.FileLogger" .../> 

      <!-- Realm,目前没有看到,略去先 --> 

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm" .../> 


      <!-- 虚拟主机localhost 
           appBase : 该虚拟主机的根目录是webapps/ 
           它将匹配请求和自己的Context的路径,并把请求转交给对应的Context来处理 
           --> 

      <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true"> 
      

        <!-- 日志类,目前没有看到,略去先 --> 

        <Logger className="org.apache.catalina.logger.FileLogger" .../> 
      

        <!-- Context,对应于一个Web App 
             path : 该Context的路径名是"",故该Context是该Host的默认Context 
             docBase : 该Context的根目录是webapps/mycontext/ 
             --> 

        <Context path="" docBase="mycontext" debug="0"/> 
        

        <!-- 另外一个Context,路径名是/wsota --> 

        <Context path="/wsota" docBase="wsotaProject" debug="0"/> 
             
        
      </Host> 
      
    </Engine> 

  </Service> 

</Server> 


<!-----------------------------------------------------------------------------------------------> 

4 - Context的部署配置文件web.xml的说明 
一个Context对应于一个Web App,每个Web App是由一个或者多个servlet组成的 
当一个Web App被初始化的时候,它将用自己的ClassLoader对象载入“部署配置文件web.xml”中定义的每个servlet类 
它首先载入在$CATALINA_HOME/conf/web.xml中部署的servlet类 
然后载入在自己的Web App根目录下的WEB-INF/web.xml中部署的servlet类 
web.xml文件有两部分:servlet类定义和servlet映射定义 
每个被载入的servlet类都有一个名字,且被填入该Context的映射表(mapping table)中,和某种URL PATTERN对应 
当该Context获得请求时,将查询mapping table,找到被请求的servlet,并执行以获得请求回应 
分析一下所有的Context共享的web.xml文件,在其中定义的servlet被所有的Web App载入 

<!-----------------------------------------------------------------------------------------------> 


<web-app> 


  <!-- 概述: 
       该文件是所有的WEB APP共用的部署配置文件, 
       每当一个WEB APP被DEPLOY,该文件都将先被处理,然后才是WEB APP自己的/WEB-INF/web.xml 
       --> 



  <!--  +-------------------------+  --> 
  <!--  |    servlet类定义部分    |  --> 
  <!--  +-------------------------+  --> 

  

  <!-- DefaultServlet 
       当用户的HTTP请求无法匹配任何一个servlet的时候,该servlet被执行 
       URL PATTERN MAPPING : / 
       --> 

    <servlet> 
        <servlet-name>default</servlet-name> 
        <servlet-class> 
          org.apache.catalina.servlets.DefaultServlet 
        </servlet-class> 
        <init-param> 
            <param-name>debug</param-name> 
            <param-value>0</param-value> 
        </init-param> 
        <init-param> 
            <param-name>listings</param-name> 
            <param-value>true</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 


  <!-- InvokerServlet 
       处理一个WEB APP中的匿名servlet 
       当一个servlet被编写并编译放入/WEB-INF/classes/中,却没有在/WEB-INF/web.xml中定义的时候 
       该servlet被调用,把匿名servlet映射成/servlet/ClassName的形式 
       URL PATTERN MAPPING : /servlet/* 
       --> 

    <servlet> 
        <servlet-name>invoker</servlet-name> 
        <servlet-class> 
          org.apache.catalina.servlets.InvokerServlet 
        </servlet-class> 
        <init-param> 
            <param-name>debug</param-name> 
            <param-value>0</param-value> 
        </init-param> 
        <load-on-startup>2</load-on-startup> 
    </servlet> 


  <!-- JspServlet 
       当请求的是一个JSP页面的时候(*.jsp)该servlet被调用 
       它是一个JSP编译器,将请求的JSP页面编译成为servlet再执行 
       URL PATTERN MAPPING : *.jsp 
       --> 

    <servlet> 
        <servlet-name>jsp</servlet-name> 
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> 
        <init-param> 
            <param-name>logVerbosityLevel</param-name> 
            <param-value>WARNING</param-value> 
        </init-param> 
        <load-on-startup>3</load-on-startup> 
    </servlet> 



  <!--  +---------------------------+  --> 
  <!--  |    servlet映射定义部分    |  --> 
  <!--  +---------------------------+  --> 

    
    <servlet-mapping> 
        <servlet-name>default</servlet-name> 
        <url-pattern>/</url-pattern> 
    </servlet-mapping> 

    <servlet-mapping> 
        <servlet-name>invoker</servlet-name> 
        <url-pattern>/servlet/*</url-pattern> 
    </servlet-mapping> 

    <servlet-mapping> 
        <servlet-name>jsp</servlet-name> 
        <url-pattern>*.jsp</url-pattern> 
    </servlet-mapping> 


  <!--  +------------------------+  --> 
  <!--  |    其它部分,略去先    |  --> 
  <!--  +------------------------+  --> 

    ... ... ... ... 

</web-app> 


<!-----------------------------------------------------------------------------------------------> 

5 - Tomcat Server处理一个http请求的过程 
假设来自客户的请求为: 
http://localhost:8080/wsota/wsota_index.jsp 
1) 请求被发送到本机端口8080,被在那里侦听的Coyote HTTP/1.1 Connector获得 
2) Connector把该请求交给它所在的Service的Engine来处理,并等待来自Engine的回应 
3) Engine获得请求localhost/wsota/wsota_index.jsp,匹配它所拥有的所有虚拟主机Host 
4) Engine匹配到名为localhost的Host(即使匹配不到也把请求交给该Host处理,因为该Host被定义为该Engine的默认主机) 
5) localhost Host获得请求/wsota/wsota_index.jsp,匹配它所拥有的所有Context 
6) Host匹配到路径为/wsota的Context(如果匹配不到就把该请求交给路径名为""的Context去处理) 
7) path="/wsota"的Context获得请求/wsota_index.jsp,在它的mapping table中寻找对应的servlet 
8) Context匹配到URL PATTERN为*.jsp的servlet,对应于JspServlet类 
9) 构造HttpServletRequest对象和HttpServletResponse对象,作为参数调用JspServlet的doGet或doPost方法 
10)Context把执行完了之后的HttpServletResponse对象返回给Host 
11)Host把HttpServletResponse对象返回给Engine 
12)Engine把HttpServletResponse对象返回给Connector 
13)Connector把HttpServletResponse对象返回给客户browser 

一、Tomcat背景 
  自从JSP发布之后,推出了各式各样的JSP引擎。Apache Group在完成GNUJSP1.0的开发以后,开始考虑在SUN的JSWDK基础上开发一个可以直接提供Web服务的JSP服务器,当然同时也支持Servlet, 这样Tomcat就诞生了。Tomcat是jakarta项目中的一个重要的子项目,其被JavaWorld杂志的编辑选为2001年度最具创新的java产品,同时它又是sun公司官方推荐的servlet和jsp容器,因此其越来越多的受到软件公司和开发人员的喜爱。servlet和jsp的最新规范都可以在tomcat的新版本中得到实现。其次,Tomcat是完全免费的软件,任何人都可以从互联网上自由地下载。Tomcat与Apache的组合相当完美。 

二、Tomcat目录 
tomcat 
|---bin Tomcat:存放启动和关闭tomcat脚本; 
|---conf Tomcat:存放不同的配置文件(server.xml和web.xml); 
|---doc:存放Tomcat文档; 
|---lib/japser/common:存放Tomcat运行需要的库文件(JARS); 
|---logs:存放Tomcat执行时的LOG文件; 
|---src:存放Tomcat的源代码; 
|---webapps:Tomcat的主要Web发布目录(包括应用程序示例);
		|--WEB-INF文件夹,不对外开放的目录结构。此处的页面不能直接通过地址栏访问,可通过跳转或是欢迎页面来访问。
|---work:存放jsp编译后产生的class文件;



三、Tomcat类加载 
    Bootstrap($JAVA_HOME/jre/lib/ext/*.jar) 
System($CLASSPATH/*.class和指定的jar) 
Common($CATALINA_HOME/common 下的classes,lib,endores三个子目录) 
Catalina ($CATALINA_HOME/server/下的classes和lib目录仅对Tomcat可见) 
&Shared($CATALINA_HOME/shared/下的classes和lib目录以及$CATALINA_HOME/lib目录)仅对Web应用程序可见,对Tomcat不可见WebApp($WEBAPP/Web-INF/*仅对该WEB应用可见classes/*.class lib/*.jar) 


加载类和资源的顺序为: 
1、/Web-INF/classes 
2、/Web-INF/lib/*.jar 
3、Bootstrap 
4、System 
5、$CATALINA_HOME/common/classes 
6、$CATALINA_HOME/common/endores/*.jar 
7、$CATALINA_HOME/common/lib/*.jar 
8、$CATALINA_HOME/shared/classes 
9、$CATALINA_HOME/shared/lib/*.jar 

四、server.xml配置简介: 
下面讲述这个文件中的基本配置信息,更具体的配置信息请参考tomcat的文档: 
    server: 
          1、port 指定一个端口,这个端口负责监听关闭tomcat的请求 
          2、shutdown 指定向端口发送的命令字符串 
    service: 
          1、name 指定service的名字 
    Connector (表示客户端和service之间的连接): 
          1、port 指定服务器端要创建的端口号,并在这个断口监听来自客户端的请求 
          2、minProcessors 服务器启动时创建的处理请求的线程数 
          3、maxProcessors 最大可以创建的处理请求的线程数 
          4、enableLookups 如果为true,则可以通过调用request.getRemoteHost()进行DNS查 
询来得到远程客户端的实际主机名,若为false则不进行DNS查询,而是返回其ip 
地址 
          5、redirectPort 指定服务器正在处理http请求时收到了一个SSL传输请求后重定向的 
端口号 
          6、acceptCount 指定当所有可以使用的处理请求的线程数都被使用时,可以放到处理 
队列中的请求数,超过这个数的请求将不予处理 
          7、connectionTimeout 指定超时的时间数(以毫秒为单位) 
    Engine (表示指定service中的请求处理机,接收和处理来自Connector的请求): 
          1、defaultHost 指定缺省的处理请求的主机名,它至少与其中的一个host元素的name 
属性值是一样的 
    Context (表示一个web应用程序): 
          1、docBase 应用程序的路径或者是WAR文件存放的路径 
          2、path 表示此web应用程序的url的前缀,这样请求的url为 
http://localhost:8080/path/**** 
          3、reloadable 这个属性非常重要,如果为true,则tomcat会自动检测应用程序的 
/WEB-INF/lib 和/WEB-INF/classes目录的变化,自动装载新的应用程序,我们可 
以在不重起tomcat的情况下改变应用程序 
    host (表示一个虚拟主机): 
          1、name 指定主机名 
          2、appBase 应用程序基本目录,即存放应用程序的目录 
          3、unpackWARs 如果为true,则tomcat会自动将WAR文件解压,否则不解压,直接 
从WAR文件中运行应用程序 
    Logger (表示日志,调试和错误信息): 
          1、className 指定logger使用的类名,此类必须实现org.apache.catalina.Logger 接口 
          2、prefix 指定log文件的前缀 
          3、suffix 指定log文件的后缀 
          4、timestamp 如果为true,则log文件名中要加入时间,如下 
例:localhost_log.2001-10-04.txt 
   Realm (表示存放用户名,密码及role的数据库): 
          1、className 指定Realm使用的类名,此类必须实现org.apache.catalina.Realm接口 
   Valve (功能与Logger差不多,其prefix和suffix属性解释和Logger 中的一样): 
          1、className 指定Valve使用的类名,如用org.apache.catalina.valves.AccessLogValve 
类可以记录应用程序的访问信息 
    directory(指定log文件存放的位置): 
    1、pattern 有两个值,common方式记录远程主机名或ip地址,用户名,日期,第一行 
请求的字符串,HTTP响应代码,发送的字节数。combined方式比common方式记 
录的值更多 

五、web.xml配置简介: 
1、默认(欢迎)文件的设置 
 在tomcat4\conf\web.xml中,<welcome-file-list>与IIS中的默认文件意思相同。 如果配置多个,按顺序执行首页,知道找打为止,前面的页面没有也不会报错。
 <welcome-file-list> 
 <welcome-file>index.html</welcome-file> 
 <welcome-file>index.htm</welcome-file> 
 <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 

2、报错文件的设置 
<error-page> 
<error-code>404</error-code> 
<location>/notFileFound.jsp</location> 
</error-page> 
<error-page> 
<exception-type>java.lang.NullPointerException</exception-type> 
<location>/null.jsp</location> 
</error-page> 
如果某文件资源没有找到,服务器要报404错误,按上述配置则会调用\webapps\ROOT\notFileFound.jsp。 
如果执行的某个JSP文件产生NullPointException ,则会调用\webapps\ROOT\null.jsp 

3、会话超时的设置 
设置session 的过期时间,单位是分钟; 
<session-config> 
<session-timeout>30</session-timeout> 
</session-config> 

4、过滤器的设置 
<filter> 
<filter-name>FilterSource</filter-name> 
<filter-class>project4. FilterSource </filter-class> 
</filter> 
<filter-mapping> 
<filter-name>FilterSource</filter-name> 
<url-pattern>/WwwServlet</url-pattern> 
(<url-pattern>/haha/*</url-pattern>) 
</filter-mapping> 

过滤: 
1) 身份验证的过滤Authentication Filters 
2) 日志和审核的过滤Logging and Auditing Filters 
3) 图片转化的过滤Image conversion Filters 
4) 数据压缩的过滤Data compression Filters 
5) 加密过滤Encryption Filters 
6) Tokenizing Filters 
7) 资源访问事件触发的过滤Filters that trigger resource access events XSL/T 过滤XSL/T filters 
9) 内容类型的过滤Mime-type chain Filter 注意监听器的顺序,如:先安全过滤,然后资源, 
然后内容类型等,这个顺序可以自己定。 

六、管理 
    1、用户配置 
      在进行具体Tomcat管理之前,先给tomcat添加一个用户,使这个用户有权限来进行管理。 
      打开conf目录下的tomcat-users.xml文件,在相应的位置添加下面一行: 
    <user name="user" password="user" roles="standard,manager"/> 
    然后重起tomcat,在浏览器中输入http://localhost:8080/manager/,会弹出对话框,输入上面的用户 
名和密码即可。 

    2、应用程序列表 
      在浏览器中输入http://localhost:8080/manager/list,浏览器将会显示如下的信息: 
    OK - Listed applications for virtual host localhost 
    /ex:running:1 
    /examples:running:1 
    /webdav:running:0 
    /tomcat-docs:running:0 
    /manager:running:0 
    /:running:0 
     上面显示的信息分别为:应用程序的路径、当前状态、连接这个程序的session数 

   3、重新装载应用程序 
      在浏览器中输入 http://localhost:8080/manager/reload?path=/examples,浏览器显示如下: 
    OK - Reloaded application at context path /examples    
这表示example应用程序装载成功,如果我们将server.xml的Context元素的reloadable属性设为true,则没必要利用这种方式重新装载应用程序,因为tomcat会自动装载。 

4、显示session信息 
    在浏览器中输入http://localhost:8080/manager/sessions?path=/examples,浏览器显示如下: 
    OK - Session information for application at context path /examples Default maximum session inactive 
interval 30 minutes 

5、启动和关闭应用程序 
   在浏览器中输入http://localhost:8080/manager/start?path=/examples和 
http://localhost:8080/manager/stop?path=/examples分别启动和关闭examples应用程序。 
html框架 html
<!--****************************-->
<!--       使用框架实例         -->
<!--****************************-->
<HTML>
 <HEAD>
   <TITLE>使用框架实例</TITLE>
 </HEAD>
<FRAMESET rows="60,*">
  <FRAME  src="top.html">  
  <FRAMESET cols="25%,*">
     <FRAME  src="left.html">
     <FRAME  src="right1.html">
  </FRAMESET>
</FRAMESET>
</HTML>




<!--****************************-->
<!--      左下侧框架实例        -->
<!--****************************-->
<HTML>
 <HEAD>
   <TITLE>左下侧框架实例</TITLE>
 </HEAD>

 <BODY>
  <BR>第2章 HTML语言<BR>
  <P>2.1HTML基础知识</P>
  2.2HTML语言入门
</BODY>
</HTML>




<!--****************************-->
<!--    右下侧框架一实例        -->
<!--****************************-->
<HTML>
 <HEAD>
   <TITLE>右下侧框架一实例</TITLE>
 </HEAD>

 <BODY>
    <p>
	<FONT color="#FF0000" size="+2">
	    HTML语言是网页制作的基础,是初学者必学的内容。
	</FONT>
	</p>
  </BODY>
</HTML>







<!--****************************-->
<!--    右下侧框架二实例        -->
<!--****************************-->
<HTML>
 <HEAD>
   <TITLE>右下侧框架二实例</TITLE>
 </HEAD>

 <BODY>
    <p>
	<FONT  color="#0000CC" size="+2">
	    通过阅读优秀网页的HTML代码,可以学习别人设计网页的方法和技巧。
	</FONT>
	</p>
  </BODY>
</HTML>





<!--****************************-->
<!--       上侧框架实例         -->
<!--****************************-->
<HTML>
 <HEAD>
   <TITLE>上侧框架实例</TITLE>
 </HEAD>

 <BODY>
  <H2><CENTER>HTML开发商业网站</CENTER></H2>
 </BODY>
</HTML>
js-简单选好器 javascript
<html>
	<head>
		<title>
		随机数
		</title>
		<script language="javascript">
			var flag=true;//当前为开始就为true
			function rand(){
				var arr = new Array();
				if(flag){
					for(i=0;i<10;i++){
						arr[i]=(Math.random()*9).toFixed(0);
						//toFixed精度
					}
					document.getElementById("jc").innerHTML = arr;
					setTimeout("rand()",100);
				}
			}
			function result(){
				var index = document.getElementById("btn").value;
				if(index=="开始"){
					flag=true;
					document.getElementById("btn").value="结束";
					rand();
				}else{
					document.getElementById("btn").value="开始";
					flag=false;
				}
			}
		//	<script language="javascript" src="rand.js" />
		</script>
	</head>
	<body>
		<form>
			奖池:<textarea rows="10" cols="20" name="jc" id="jc"></textarea><br/>
			<input type="button" id="btn" value="开始" onclick="result()">
		</form>
	</body>
</html>
Global site tag (gtag.js) - Google Analytics