??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲国产成人精品女人久久久,精品自拍视频在线观看,亚洲国产尤物http://www.aygfsteel.com/pear/category/14801.htmlzh-cnTue, 27 Feb 2007 17:48:20 GMTTue, 27 Feb 2007 17:48:20 GMT60Reports made easy with JasperReportsQ{Q?/title><link>http://www.aygfsteel.com/pear/archive/2006/11/01/78398.html</link><dc:creator>pear</dc:creator><author>pear</author><pubDate>Wed, 01 Nov 2006 00:49:00 GMT</pubDate><guid>http://www.aygfsteel.com/pear/archive/2006/11/01/78398.html</guid><wfw:comment>http://www.aygfsteel.com/pear/comments/78398.html</wfw:comment><comments>http://www.aygfsteel.com/pear/archive/2006/11/01/78398.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/pear/comments/commentRss/78398.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/pear/services/trackbacks/78398.html</trackback:ping><description><![CDATA[ <h1 align="center">Reports made easy with JasperReports</h1> <h3 align="center">The open source JasperReports uses XML templates for your reporting needs</h3> <p> </p> <!--<blockquote><strong>Summary</strong><br>--> <blockquote> <strong>Summary</strong> <br />JasperReports, a popular, full-featured open source report-generating library, uses XML report templates to generate reports you can display on the screen, send to a printer, or save as a PDF document. In this inaugural <strong>Open Source Profile</strong> column, Erik Swenson introduces the JasperReports library and explains how to integrate JasperReports into your applications. (<em>900 words;</em><strong>September 20, 2002</strong>) </blockquote> <p align="center"> <!--</blockquote>--> <a target="Feedback"> <strong>By Erik Swenson</strong> </a> <!-- START BIG AD (336x280) jw-articles-336x280.txt --> <!-- END BIG AD (336x280) --> </p> <p> <span id="intelliTXT"> <img height="29" alt="G" src="http://www.javaworld.com/javaworld/abcs/G.gif" width="21" onload="var image=new Image();image.src=this.src;if(image.width>0 && image.height>0){if(image.width>=510){this.width=510;this.height=image.height*510/image.width;}}" align="left" />enerating reports is a common, if not always glamorous, task for programmers. In the past, report generation has largely been the domain of large commercial products such as Crystal Reports. Today, the <a class="iAs" style="COLOR: darkgreen; BORDER-BOTTOM: darkgreen 1px solid; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline" target="_blank">open source</a> JasperReports report generating library gives <a class="iAs" style="COLOR: darkgreen; BORDER-BOTTOM: darkgreen 1px solid; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline" target="_blank">Java</a> developers a viable alternative to commercial software. <p>JasperReports provides the necessary features to generate dynamic reports, including data retrieval using JDBC (Java Database <a class="iAs" style="COLOR: darkgreen; BORDER-BOTTOM: darkgreen 1px solid; BACKGROUND-COLOR: transparent; TEXT-DECORATION: underline" target="_blank">Connectivity</a>), as well as support for parameters, expressions, variables, and groups. JasperReports also includes advanced features, such as custom data sources, scriptlets, and subreports. All in all, JasperReports combines good features, maturity, community participation, and, best of all, it's free. </p><p>This article kicks off <em>JavaWorld'</em>s new <strong>Open Source Profile</strong> column dedicated to Java-based open source tools and components. Look for upcoming articles spotlighting the Echo Web application framework and ObJectRelationalBridge, an object/relational mapping tool. Feel free to send me your suggestions for future articles. </p><p><strong>Note:</strong> The documentation and code featured in this article are based on JasperReports version 0.3.3. </p><p><font size="+1"><strong>Report design</strong></font><br />In JasperReports, you design reports using XML report templates. For example, the following XML file is a template for a report with a title, two columns of data, and page numbers: </p><p><code><p><?xml version="1.0" encoding="UTF-8"?><br /><!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" <br />"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"><br /><jasperReport name="BasicReport" ><br />  <parameter name="Title" class="java.lang.String"/><br />  <queryString><![CDATA[select name, cost from product]]></queryString><br />  <field name="NAME" class="java.lang.String"/><br />  <field name="COST" class="java.lang.Double"/><br />  <title><br />    <band height="50"><br />      <textField><br />        <reportElement x="0" y="0" width="200" height="50" />       <br />        <textFieldExpression class="java.lang.String">$P{Title}</textFieldExpression><br />      </textField><br />    </band><br />  </title><br />  <pageHeader><br />    <band><br />    </band><br />  </pageHeader><br />  <columnHeader><br />    <band height="20"><br />      <staticText><br />        <reportElement x="180" y="0" width="180" height="20"/><br />        <textElement><br />          <font isUnderline="true"/><br />        </textElement><br />        <text><![CDATA[NAME]]></text><br />      </staticText><br />      <staticText><br />        <reportElement x="360" y="0" width="180" height="20"/><br />        <textElement><br />          <font isUnderline="true"/><br />        </textElement><br />        <text><![CDATA[COST]]></text><br />      </staticText><br />    </band><br />  </columnHeader><br />  <detail><br />    <band height="20"><br />      <textField><br />        <reportElement x="180" y="0" width="180" height="20"/> </p><p>  <br />        <textFieldExpression class="java.lang.String"><![CDATA[$F{NAME}]]></textFieldExpression><br />      </textField><br />      <textField pattern="0.00"><br />        <reportElement x="360" y="0" width="180" height="20"/> </p><p>  <br />        <textFieldExpression class="java.lang.Double"><![CDATA[$F{COST}]]></textFieldExpression><br />      </textField><br />    </band><br />  </detail><br />  <columnFooter><br />    <band><br />    </band><br />  </columnFooter><br />  <pageFooter><br />    <band height="15"><br />      <staticText><br />        <reportElement x="0" y="0" width="40" height="15"/><br />        <textElement/><br />        <text><![CDATA[Page:]]></text><br />      </staticText><br />      <textField><br />        <reportElement x="40" y="0" width="100" height="15"/><br />        <textElement/><br />        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression><br />      </textField><br />    </band><br />  </pageFooter><br />  <summary><br />    <band><br />    </band><br />  </summary><br /></jasperReport><br /></p></code></p><p>The template's beginning includes any parameters passed into the report, the query that retrieves the data for the report, and the fields displayed in the report. The template's remainder divides into six report sections: </p><p></p><ul><p></p><li><code><font face="新宋?>title</font></code></li><li><code><font face="新宋?>pageHeader</font></code></li><li><code><font face="新宋?>columnHeader</font></code></li><li><code><font face="新宋?>detail</font></code></li><li><code><font face="新宋?>columnFooter</font></code></li><li><code><font face="新宋?>pageFooter</font></code></li><li><code><font face="新宋?>summary</font></code><p> </p></li></ul><p>Each report section, called a <em>band</em>, is given a <code><font face="新宋?>height</font></code>. Each band can include multiple <code><font face="新宋?>staticText</font></code> and <code><font face="新宋?>textField</font></code> elements, which are given a position, size, and value. Report parameters, fields, and variables are referenced using <code><font face="新宋?>P${name}</font></code>, <code><font face="新宋?>F${name}</font></code>, and <code><font face="新宋?>V${name}</font></code>, respectively. </p><p>For example, the following lines in the page footer section create a <code><font face="新宋?>textField</font></code> containing the current page number. The page number's value is set to the variable <code><font face="新宋?>PAGE_NUMBER</font></code>, defined internally by JasperReports and available to all reports: </p><p><code><p><textField><br />  <reportElement x="40" y="0" width="100" height="15"/><br />  <textElement/><br />  <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression><br /></textField><br /></p></code></p><p>The above template represents a basic, yet functional, report. A thorough JasperReports XML-template description is beyond the scope of this article, but I've included numerous links in <a >Resources</a> to tools that will help you edit and create your own report templates. Next, let's see how to use JasperReports in your Java applications. </p><p><font size="+1"><strong>Use JasperReports</strong></font><br />To begin using JasperReports, you first must understand what objects JasperReports uses to represent the reporting process as it progresses from report design to report generation: </p><p></p><ul><p></p><li><code><strong><font face="新宋?>JasperDesign</font></strong></code>: Represents a report's definition. In most cases, you create a <code><font face="新宋?>JasperDesign</font></code> from an XML report template, though you can also create it programmatically. <p> </p></li><li><code><strong><font face="新宋?>JasperReport</font></strong></code>: Represents a compiled <code><font face="新宋?>JasperDesign</font></code>. The compilation process verifies the report design and compiles the design into a <code><font face="新宋?>JasperReport</font></code> object. <p> </p></li><li><code><strong><font face="新宋?>JasperPrint</font></strong></code>: Represents a generated report. You create a <code><font face="新宋?>JasperPrint</font></code> from a <code><font face="新宋?>JasperReport</font></code> through the fill process in which a report is populated with data from a data source. <p> </p></li></ul><p>The JasperReports API's flexibility lets you load <code><font face="新宋?>JasperDesign</font></code>, <code><font face="新宋?>JasperReport</font></code>, and <code><font face="新宋?>JasperPrint</font></code> objects from a file or a stream, and also lets you create these objects programmatically. You can print reports to a printer, an image, or a PDF file. The JasperReports library includes a facade class, <code><font face="新宋?>dori.jasper.engine.JasperManager</font></code>, with methods that facilitate loading, compiling, filling, and printing reports. The following code illustrates a <code><font face="新宋?>JasperManager</font></code>: </p><p><code><p>// First, load JasperDesign from XML and compile it into JasperReport<br />JasperDesign jasperDesign = JasperManager.loadXmlDesign("BasicReport.xml");<br />JasperReport jasperReport = JasperManager.compileReport(jasperDesign);<br /><br />// Second, create a map of parameters to pass to the report.<br />Map parameters = new HashMap();<br />parameters.put("ReportTitle", "Basic JasperReport");<br />parameters.put("MaxSalary", new Double(25000.00));<br /><br />// Third, get a database connection<br />Connection conn = Database.getConnection(); <br /><br />// Fourth, create JasperPrint using fillReport() method<br />JasperPrint jasperPrint = JasperManager.fillReport(jasperReport, <br />   parameters, conn);<br /><br />// You can use JasperPrint to create PDF<br />JasperManager.printReportToPdfFile(jasperPrint, "BasicReport.pdf");<br /><br />// Or to view report in the JasperViewer<br />JasperViewer.viewReport(jasperPrint);<br /></p></code></p><p>The code example above shows how to perform some common tasks using JasperReports. In a real-world application, you'd find it impractical to load and compile the <code><font face="新宋?>JasperDesign</font></code> every time you wanted to generate a report. Since report designs are largely static, in most cases, you'd precompile your <code><font face="新宋?>JasperDesign</font></code> files to increase speed. You can also increase a large report's speed by generating and saving <code><font face="新宋?>JasperPrint</font></code> objects as part of a nightly batch process. </p><p>That's all you need to get started; download JasperReports and you'll be up and running in no time. </p><p><font size="+1"><strong>Reports the easy way</strong></font><br />In this article, you learned how the open source JasperReports can aid your Java reporting needs. If you are building a reporting application or looking to add reporting capability to an existing application, look at JasperReports. Visit the JasperReports <a >homepage</a> for more information and download the latest version. <img height="12" src="http://www.devworld.com/microsites/javaworld/javaworld/icons/jw-dingbat.gif" width="22" onload="var image=new Image();image.src=this.src;if(image.width>0 && image.height>0){if(image.width>=510){this.width=510;this.height=image.height*510/image.width;}}" /></p></span> </p> <img src ="http://www.aygfsteel.com/pear/aggbug/78398.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/pear/" target="_blank">pear</a> 2006-11-01 08:49 <a href="http://www.aygfsteel.com/pear/archive/2006/11/01/78398.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>实用的java问题http://www.aygfsteel.com/pear/archive/2006/09/14/69738.htmlpearpearThu, 14 Sep 2006 11:25:00 GMThttp://www.aygfsteel.com/pear/archive/2006/09/14/69738.htmlhttp://www.aygfsteel.com/pear/comments/69738.htmlhttp://www.aygfsteel.com/pear/archive/2006/09/14/69738.html#Feedback0http://www.aygfsteel.com/pear/comments/commentRss/69738.htmlhttp://www.aygfsteel.com/pear/services/trackbacks/69738.htmlhttp://www.matrix.org.cn/thread.shtml?topicId=46027&forumId=14

1. 问:(x)在JAVA与JSP中要调用一个LINUX上的脚本E序,或WINDOWS上的脚本E序,该怎么写?
{:(x)System.getRuntime().exec("bash < aaa.sh");

2. 问:(x)java中用什么表C双引号
{:(x)"""

3. 问:(x)如何在JSPE序里另起一个线E?
{:(x)
JSP本n是独立U程q行而不象CGI都是独立q程.
一?
Thread t = new Thread("你的对象");
t.start();可以了.
要求你这个对象要实现runnable接口或承thread.

4. 问:(x)jsp如何获得客户端的IP地址Q?br />{:(x)
request.getRemoteAddr()
看看各个webserver的API文档说明Q一般都有自带的Qresin和tomcat都有

5. 问:(x)E序l止与输出终?br />{:(x)
E序中止:return;
输出中止out.close();q一句相当于ASP的response.end

6. 问:(x)jsp中如何得C늚URLQ?br />{:(x)request.getHeader("referer");

7. 问:(x)提交|页的网过期功能是怎么做的Q?br />{:(x)response.setHader("Expires","0");

8. 问:(x)在JSP|页中如何知道自已打开的页面的名称
{:(x)
request.getRequestURI() ;//文g?br />request.getRequestURL() ;//全部QRQ?br />
9. 问:(x)提交表单后验证没有通过Q返回提交页面,如何使原提交面中的数据保留Q?br />{:(x)javascript的go(-1)可以把上늚表单内容重新昄出来,但password域没?br />
10. 问:(x)如何取得http的头信息Q?br />{:(x)request.getHader(headerName);

11. 问:(x)&&?amp;的区别?
{:(x)
&&是短路的与操作,也就是当C个条件是false的时候,W二个条件不用执?br />&相反Q两个条件L执行?br />
12. 问:(x)?以正弦曲U的一个周期显C出?br />{:(x)
public void paint(Graphics g)
{
for(int i=0;i<200;i++)
g.drawString("*",i,(int)(Math.sin(i)*20)+50);
}
}

13. 问:(x)点数相乘后l果不精如100.0 * 0.6 l果{于 60.0004
{:(x)
q不叫错?float和double是这样实现的.如果要精计,java提供了一个strictfp,它的计算遵@IEEE 754标准.而普通的float和double?br />
由地q_点格式或硬件提供的额外_ֺ或表C围?br />
14. 问:(x)如何获得当前用的cursors的位|?
{:(x)
int row = rs.getRow()是当前指针行数,q有isFrist();isBeforeFist();isLast();isAfterLast();可以试是不是在Ҏ(gu)名所说的位置

15. 问:(x)表单成功提交了,点后退昄|页q期
{:(x)
?lt;head></head>里面加以下代?br /><META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
或者在表单中加上
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
%>

16. 问:(x)接口的简单理?br />{:(x)接口Z规范,比如我在接口中定义了一个方?
getData()
q是用来从不同的数据库中取数据的,是JDBC的实现对于用?我不要知道每U数据库是如何做?但我知道如何它们要实现这个接口就一定有

q个Ҏ(gu)可以供我调用.q样SUN把q个接口l各个数据库开发商,让他们自己实? 但ؓ(f)什么不用承而用接口?因ؓ(f)l承只能从一个你c?br />
l承,而接口可以实现多?是说我实现的子cL多个规定好的接口中的功能. q只是简单的理解,{你深入理解抽象的时候就知道抽象到抽?br />
cLZ么还要再抽象到接?

17. 问:(x)怎样~写一个取消按钮(怎样q回上一个页面,象工h的后退按钮Q?
{:(x)
javascript把每ơ浏览过的location都压C一个栈?q个栈就是history,然后你如果要回到W几个页面它?yu)做几次POP操作,把最后POP出来

的那个LOCATIONl你. q就是JAVASCRIPT在实现history.go(-x)的原?

18. 问:(x)什么是回调Q?br />{:(x)
单说,回调用不是让你去监听谁做完了什么事,而是谁做完了什么事报告给? q就是回调用的思想.例子太多?AWT的事?SWING事g模型

都是q样? q有多线E中,如果要控制线E数,不能L查询每个U程是否l束,要在每个U程l束时让U程自己告诉ȝE我l束?你可?br />
开新的U程?

19. 问:(x)要介l一下compareToҎ(gu)
{:(x)
compareToҎ(gu)是Comparable 接口必需实现的方?只要实现Comparable

可以用Arrays.srot()排序p实现Runnable接口的runpThread()一?

20. 问:(x)如何可以从别的Web服务器检索页, 然后把检索到的网늚HTML代码储存在一个变量中q回q来
{:(x)q是一个简单的WEB ROBOT实现,用URLcdC|页中抓内容,然后自己写一个分析程序从中找出新的URL,不断递归下去p?

21. 问:(x)applet中如何获得键盘的输入
{:(x)application的System.in是当前系l的标准输入,applet因ؓ(f)安全的原因不可能d当前pȝ(客户?的标准输?只能从它的ROOTlg?br />
事g?比如键盘事g中取得键?

22. 问:(x)怎样计算代码执行所p的时_(d)
{:(x)
代码开始取旉Q结束后取时_(d)相减
long t1 = System.currentTimeMillis();
///////////////// your code
long t2 = System.currentTimeMillis() ;
long time = t2-t1;

23. 问:(x)如何获在E序中获得一个文件的ContentTypeQ?br />{:(x)
URL u = new URL("file:///aaa.txt");
URLConnection uc = u.openConnection();
String s = uc.getContentType();

24. 问:(x)q接池的使用是徏立很多连接池Q还是一个连接池里用多个q接Q?br />{:(x)
只有在对象源不同的情况下才会(x)发生多个池化,如果你只q一l一个数据源,永远不要用多个连l池. 所以连l池的初始化一定要做成静态的,?br />
且应该在构造对象之?也就是只有在cLOAD的时?别的时候不应该有Q何生成新的连l池的时候?br />
25. 问:(x)JavaMail要怎么安装Q?br />{:(x)下蝲两个包,一个是javamail包,另一个是jaf包。下载完直接把这两个包不解压加到CLASSPATH?br />
26. 问:(x)怎样把地址栏里的地址锁定Q?br />{:(x)把你的服务器的可讉K目录索引选项关闭p?M服务器都有一个conf文g,里面都有q个选项?br />
27. 问:(x)在JAVA中怎么取得环境变量啊。比如:(x) TEMP = CQTEMP Q?br />{:(x)String sss = System.getProperty(key)

28. 问:(x)怎样实现四舍五入Q保留小数点后两位小敎ͼ
{:(x)
import java.text.*;
...
NumberFormat nf=NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
nf.format(numb);

29. 问:(x)Applet和form如何通信Q?br />{:(x)
取得的参C到param里面
<%
String xxx = request.getParameter("xxx");
%>
<applet>
<param value="<%=xxx%>">
</applet>


30. 问:(x)java-plug-in是什么?
{:(x)Java Runtime Environment的插件。用来运行javaE序。不需要什么特别的讄。等于你的机器里面有了jvm?br />
31. 问:(x)WEB上面怎么栯接上一个EXCEL表格Q?br />{:(x)
定义面得contentType="application/vnd.ms-excel"Q让面以excel得Ş式打开。同样也可以以word得Ş式打开Qapplication/msword?br />
32. 问:(x)怎样才能避免textarea字数限制Q?br />{:(x)是用了FORM的默认方法的~故,如果什么也不写默认是GET改用Post卛_Q在Form中定义mothod="post"?br />
33. 问:(x)Z么加?lt;%@page contentType="text/html;charset=gb2312" %>插入数据库的中文Q依然是qQ?br />{:(x)
q要从环境看,能显C明你的JSP引擎没有问题,但写入数据库时你的JDBC能不能处理中?同一公司不同版本的JDBC都有支持中文和不支持?br />
文的情况,RESIN自带的MYSQL JDBC׃支持,MM的就支持,q有你的数据库类型是否支持中?CHAR的一般支?但是否用binary存储双字节码

34. 问:(x)对于JFrameQhide()Qshow()与setVisibel()有什么区别吗Q?br />{:(x)
setVisible()从Componentl承q来Q而hide(),show()从Window里面l承q来?br />Makes the Window visible. If the Window and/or its owner are not yet displa yable, both are made displayable. The Window will

be validated prior to being made visible. If t he Window is already visible, this will bring the Window to the front. 区别?br />
q?br />36. 问:(x)sendRedirectZ么不可以转到mms协议的地址的?response.sendRedirect("mms://missiah.adsldns.org:9394");
{:(x)javaq_目前实现的protocol中ƈ没有mms,你可以取pȝ属性java.protocol.handler.pkgs看看它的g有没有mms,所以如果要想重定向

到mms://hostq样和URL,只有生成客户端的JAVASCRIPT让它来重定向

37. 问:(x)JTable中怎样定义各个Columns和W(xu)idth和怎样讄表格的内定w做靠x居中Q?br />{:(x)
TableColumn tc = table.getColumn("Name");//取得列名?Name"的列Handle
int currentWidth = tc.getPreferredWidth(); //取得该列当前的宽?br />tc.setPreferredWidth(200); //讄当前列宽
tc.setMaxWidth(200); //讄该列最大宽?br />tc.setMinWidth(50); //讄该列最宽?br />
38. 问:(x)Ҏ(gu)作是否可用于select语句Q?br />{:(x)Ҏ(gu)作其实是指成批理更新的操?l对不可能用于select操作?br />
39. 问:(x)Z么jsp路径太深文g名太长就无法d文gQ?br />{:(x)path不能过255长度,不然找不到?q是作业pȝ的事?br />
40. 问:(x)如何让页面不保留~存Q?br />{:(x)
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
%>

41. 问:(x)我的applet code 中用到jbutton 时就出错是否׃ie不支持swing package 请问应怎么办?
{:(x)JBUTTON是SWING基本包啊,只要把jdk/jre/lib/rt.jar攑֜classpathp?不要加蝲M别的库?br />
42. 问:(x)不知道java是否支持midi格式Q如果支持,应该怎么把wave格式转换成midi格式Q?br />{:(x)目前q不?可以看一下JMF三个版中对MIDI的格式支持是read only,而W(xu)AVE是read/write,MIDI只能播放,不能生成?br />
43. 问:(x)在jsp里面防止用户直接输入urlq去面Q应该怎么做呢Q?br />{:(x)
一是从web服务器控?Ҏ(gu)一目录的所有访问要通过验证.
二是在要讉K的页面中加入控制.q个一般用session,也可以用h状态码实现

44. 问:(x)
例如后台有一计算应用E序Q此E序q算h很慢Q可持箋几分钟到几小Ӟq不,主要是能ȀzdQ,客户d提交后,服务器对?br />
务进行检无误后向服务器后台程序发送信息,q将其激zR要求如下:(x)
1Q首先将后台E序Ȁz,让它执行此Q务(比如Q前台将计算的C代码提交上后Q后台程序程序能马上调用Qƈ其q行Q?br />2Q要在前台JSP面中显C行过E信息(׃q行旉长,希望让客L(fng)到运行过E中产生的信息)如何完成Q?br />
{:(x)
zL可以?q行一个shell让它去运行后台就?但不可能取出q行信息,因ؓ(f)HTTP的超旉制不可能永远{你后台q行?而且信息如果要动?br />
实时推出来就得用SERVER PUSH技术?br />
45. 问:(x)数据库是datetime ?Q插入当前时间到数据库?
{:(x)
java.sql.Date sqlDate = new java.sql.Date();
PreparedStatement pstmt = conn.prepareStatement("insert into foo(time) values(?)");
pstmt.setDate(1,sqlDate);
pstmt.executeUpdate();

46. 问:(x)怎样L字符串前后的I格?br />{:(x)String.trim()

47. 问:(x)session怎样存取intcd的变量?
{:(x)
session.setAttribute("int", i+"");
int i = Integer.parseInt(session.getAttribute("int"));

48. 问:(x)在javascript中如何输出的floatcd的数据保留两位小数?br />{:(x)Math.round(aaaaa*100)/100?br />
49. 问:(x)在beanU如何调用session
{:(x)
你可把session对象作ؓ(f)一个参Clbean
在BEAN中定义HttpServletRequest request;HttpSession session;
然后
session = request.getSession(false);
false为如果session为空,不徏立新的session
session作ؓ(f)参数传入.其实只要request传入可?br />
50. 问:(x)如何把txt或word文g按原格式昄在jsp面或servlet上?
{:(x)
其实一个非常简单的解决Ҏ(gu)是在服务器的MIME中指点定TEXT和W(xu)ORD的解释方?然后用JSP或SERVLET生成它就行了,客户端就?x)自动调用?br />
应程序打开你的文档?br />如果是希望按原格式的昄在页面上Q而不是调用其他程序打开那么你可以试试用WEBDEV协议,可以说这是MS的一个亮?它是在WEB方式下打开

文,和共享一?完全W合的要求?br />
51. 问:(x)object的cloneҎ(gu)Z么不能直接调用?
{:(x)
q个Ҏ(gu)在object中是protected
Z么要把这个方法定义ؓ(f)protected,q是一个折?它的目的是想知道你这个方法在Object里只是一个标?而不是一个实?比如

public class Object
{
.............
protected Object clone()
{}
}

所以直接承的clone()Ҏ(gu)q不能做M?你要使用q个Ҏ(gu)p重蝲q个Ҏ(gu)q放宽访问权限ؓ(f)public,或实现cloneable接口. 但它没法

q样告诉你它没有真的实现,只好用protected Ҏ(gu)加以警示

52. 问:(x)一个页面中如何h另外一个页面?
{:(x)
要求是这些面必L兌,一是它们都有一个共同的层?也就是说是一个内的分面,当然可以是Q意,帧内再分帧也可以,另一个可

能是当前H口弹出的窗?如果没有联系,那就不可能用一个页面刷新另一个页? 帧内只要一U一U引用就行了.

比如在左帧中一个页面中写top.right.location.reload();那么名ؓ(f)right的右帧中的页面就?x)刷? 弹出的一?用open时的名称h子窗?

子窗口用openerhȝ?br />
53. 问:(x)如何在jsp中怎么样向客户端写cookiesQ?br />{:(x)
Cookie coo = new Cookie(name, value);
HttpServletResponse.addCookie(name);

54. 问:(x)Z么jTextField1.setText("aaabbb");jTextField2.setText("AAABBB"); 得到的字体宽度不一P
{:(x)是说如果不是指定ؓ(f){宽字体,每个字体的宽度都是不一L(fng).因此JAVA中用FontMetrics cL取字W宽度?br />
55. 问:(x)String kk=application/octet-stream; name="G:/SMBCrack.exe";如何得到SMBCrack.exeQ?br />{:(x)
q应该是解析上传时候的二进制流得到的这一行里面格式是固定的,取到name="后面的字W串Q然后把";L。然后取最后一?后面的所有字

W组成一个新字符串就行了?br />
56. 问:(x)如何传值ƈ不刷新页面?
{:(x)
弹出一个页面进行值的选择或者输入,ok后用将gl原H口Q用javascript关闭打开的窗口即可:(x)
window.close();opener.focus();

57. 问:(x)有一个字W串Q?EF0C114EA4"Q如何变为a[0] = 0xEF a[1] = 0x0C a[2] = 0x11 a[3] = 0x4E a[4] = 0xA4Q?br />{:(x)
String str="EF0C114EA4F";
out.print(str+"<br>");
int l=str.length()/2+str.length()%2,j=0,k=0;
String[] a=new String[l];
for(int i=0;i<l;i++){
if(str.length()-j==1)
k=str.length();
else
k=j+2;
a="0x"+str.substring(j,k);
out.print("a["+Integer.toString(i)+"]="+a+"<br>");
j+=2;
}

58. 问:(x)怎样一个int转换成一个四字节的byte数组Q?br />{:(x)
int x = 1234567;
byte[] b = new byte[4];
for(int i=0;i<b.length;i++)
{
b = (x >>( i*8)) & 0xFF;
}

59. 问:(x)indexOf()的用需要注意什么?
{:(x)参数是指从第几位Q?Q?Q?Q?..Q开始搜索,而返回值是指搜索到的位|(0Q?Q?Q?.......Q注意是从零v的?br />
60. 问:(x)在Java应用E序中如何动态的d一个按钮?
{:(x)
q里涉及(qing)一个组仉l的问题,lg要先于panel被显CZ处存?如果一panel已经昄?那么加在上面你能看到?但如果在同一个panel?

先有button A,假如按下它加了butt on B,q时你如果整个panel重给,那么A本n要重l?它的事g监听没有了,当然也就加不成B?所以如

果要先有另一个panel,当按A时把B加在q个panel上ƈ重绘q个paenl,其实更好的方法是先把B加在panel?同一个也?把它setVisiable(flas

e),按A时设?true?br />
61. 问:(x)book mybook=new book(bookid);book是servlet,出错?br />{:(x)
book是servlet,能book mybook=new book(bookid);
说明自己实现了servlet容器?不然,servlet能让你自己去调用? servlet如果调用其实和EJBq?%的区别都没有,它们都是自己l承或实C些接

?在这些父cL接口中实C如果和容?打交?的方?然后容器调用q些Ҏ(gu)来管理它,让它生成实例,池化,钝化,销?再生{?所以这?br />
写是错误的?br />
62. 问:(x)l定一个字W串5*(5+9)/7怎样计算出结果?
{:(x)
可有两种Ҏ(gu)
1。用堆栈完成
2。最单的Ҏ(gu)Q不用编E,如果有Q何一个数据库的化Q用select (5*(5+9)/7) from oneTable

63. 问:(x)如何实现递交表单内容的加密解密?
{:(x)
如果你用IE目前只能用SSL协议,q一层不要你考虑,否则只你用你自己的工具加密传?接收后再解密?至于如何加解,如果要和公认的系l结

?q通用的MD5,RAS{公开法,如果你只是自׃自己?你随便按你的x把数据加上一些东?取回来按规则减掉q些东西,我敢保证?br />
你自己没有Q何h能知道解密方?

64. 问:(x)Z么Integer.parseInt("+1");?x)抛出NumberFormatException的异常?
{:(x)因ؓ(f)"+"q行在JAVA中被重蝲.pȝ无法定你用的是术加还是字W??br />q一点可以在JAVASCRIPT中更好地理解:
<form name="t"><input name=s value=1234></form>
var a = document.t.s.value+1;
q时a = 12345,因ؓ(f)document.t.s.value作ؓ(f)字符?但var a = document.t.s.value-1;
a 是1233,因ؓ(f)pȝ知道-q算肯定是算术运?所以把document.t.s.value转换成数?


65. 问:(x)hashCode() 有什么用Z么有时候需要覆盖Object里的hashcode()Ҏ(gu)Q?br />{:(x)q就是这个对象的w䆾证啊,要不如何区分哪个对象?br />
66. 问:(x)怎样在tomcat中实C个定时执行的东东Q?br />{:(x)
在应用程序启动时自动q行。servlet2.3中定义了ServletListener,监听Servlet Con text的启动或则关闭(可在配置文g中配|)Q启动时

触发一个守护程序的q行(可以实现java.util.Timer或则 javax.swing.Timer).

67. 问:(x)E序可以输出自己吗?
{:(x)孔d(zhn)论q个非常有名的法?是说Q何程序都不可能输?

68. 问:(x)能够把字W{化成ASCII码?比如?A 转化?65Q?br />{:(x)
int a='A';
out.println(a);

69. 问:(x)如何区分输入的文字中的全角与半角Q?br />{:(x)׃不能分L出全角和半角字符的值有什么规?只好把全角符L(fng)丑և来了.

70. 问:(x)用户注册后的自动发信E序该怎么做?
{:(x)
q种发信E序不考虑性能,因ؓ(f)不可?U就有一个h注册,我们说的考虑性能的发信程序是指上百万信在队列里要不停发送的那种,象你q个

随便怎么写一个程序都?没有必要用JAVAMAIL.只要指定一个发信的服务器然后用cocketq它?5口就行了.自己用SOCKETqSMTP?5口发一?br />
信就好象两个d之间送一样东?直接递过d?用JAVAMAIL,消息机制是你把q个东西从邮局寄给?img src ="http://www.aygfsteel.com/pear/aggbug/69738.html" width = "1" height = "1" />

pear 2006-09-14 19:25 发表评论
]]>
Server Push详解(转蝲)http://www.aygfsteel.com/pear/archive/2006/09/14/69737.htmlpearpearThu, 14 Sep 2006 11:16:00 GMThttp://www.aygfsteel.com/pear/archive/2006/09/14/69737.htmlhttp://www.aygfsteel.com/pear/comments/69737.htmlhttp://www.aygfsteel.com/pear/archive/2006/09/14/69737.html#Feedback0http://www.aygfsteel.com/pear/comments/commentRss/69737.htmlhttp://www.aygfsteel.com/pear/services/trackbacks/69737.html 服务器推?Server Push)

推送技术的基础思想是将览器主动查询信息改为服务器d发送信息。服务器发送一Ҏ(gu)据,览器显C些数据,同时保证与服务器的连接。当服务器需要再ơ发送一Ҏ(gu)据时Q浏览器昄数据q保持连接。以后,服务器仍然可以发送批量数据,览器l显C数据,依次cL?

客户端拉?Client Pull)

在客L(fng)拖曳技术中Q服务器发送一Ҏ(gu)据,在HTTP响应或文档头标记中插入指令,让浏览器“在5U内再次装入q些数据”或?0U内前往某URL装入数据”。当指定的时间达到时Q客L(fng)按照服务器的指C去做,或者刷新当前数据,或者调入新的数据?

其实push ?pull q两U技术手D非怸同,但目的几乎一_(d)都是Zl最l用h便的提供最C息?

在服务器推送技术中QHTTP q接一直保持着Q直到服务器知道自己已结束发送数据ƈ发送一个结束信P或者客L(fng)中断q接。而在客户端拖x术中Qƈ不保持HTTPq接Q相反,客户端被告知合时建立新连接,以及(qing)建立q接是获取什么数据?

在服务器推送中Q奇妙之处在于“multipart/mixed”格式的MIMEQ它能够使一个报文(或HTTP响应Q包含许多数据项、在客户端拖曳中Q奇妙之处在于HTTP响应头标Q或{效的HTML元素Q,它能告知客户端在指定的g时时间后执行何种动作?

服务器推送通常效率要比客户端拖x率高Q因为它不必为后l数据徏立新的连接。由于始l保持连接,即没有数据传输时也是这P因此服务器必L意分配这些TCP/IP端口Q对于TCP/IP端口数有限的服务器这是一个严重的问题?

客户端拖x率低Q因必须每次Z送数据徏立新的连接。但是它不必始终保持q接?

在实际情况中Q徏立HTTPq接通常需要花费相当多的时_(d)多达一U甚x多。因此从性能上考虑Q服务器推送对于最l用h有吸引力Q特别是对于需要经常更C息的情况下?

服务器推送相对客L(fng)拖曳的另一点优势是Q服务器推送相Ҏ(gu)较容易控制。例如,服务器每一ơ推送时都保持一个连接,但它又随时可以关闭其中的Mq接Q而不需要在服务器上讄Ҏ(gu)的算法。而客L(fng)拖曳在同L(fng)情况下要ȝ(ch)许多Q它每次要与服务器徏立连接,服务器ؓ(f)了处理将客户端拖曌求与特定的最l用户匹配等情况Q需要用相当麻?ch)的法?

如果实现服务器推送的CGIE序是用Shell脚本语言~写的,有时?x)存在一些问题。例如,客户端最l用户中断连接,ShellE序通常不能注意刎ͼq将使资源毫无用处的费掉,解决q一问题的办法是用Perl或者C来编写这cCGIE序Q以使用户中断连接时能够l束q行?


如上所qͼ在服务器推送中Q多个响应中q接始终保持Q服务器可在Q何时间发送更多的数据。一个明昄好处是服务器完全能够控制更新数据的时间和频率。另外,q种Ҏ(gu)效率高,因ؓ(f)始终保持q接。缺Ҏ(gu)保持q接状态会(x)费服务器端的资源。服务器推送还比较Ҏ(gu)中断?

接下来就大概说说服务器推送技?
服务器在响应hӞHTTP使用MIME报文格式来封装数据。通常一个HTTP响应只能包含一个数据块。但MIME有一U机制可用一个报文(或HTTP响应Q表C将多个数据块,q种机制是成ؓ(f)“multipart/mixed”的标准MIMEcd。multipart/mixed报文大体格式如下Q?
Content-type:multipart/mixed;boundary=ThisRandomString
--ThisRandomString
Content-type:text/plain
W一个对象的数据?
--ThisRandomString
Content-type:text/plain
W二个对象的数据?
--ThisRandomString--

上述报文包括两上数据块,二者的cd都是“text/plain”。最后一个“ThisRandomString”后的两条短U(--Q表C报文结束,后面没有数据?

对于服务器推送,使用一个“multipart/mixed”类型的变种--multipart/x-mixed-replace。这里,“x-”表C属于实验类型。“replace”表C每一个新数据块都?x)代替前一个数据块。也是_(d)新数据不是附加到旧数据之后,而是替代它?

下面是实际用的“multipart/x-mixed-replace”类型:(x)
Content-type:multipart/x-mixed-replace;boundary=ThisRandomString
--ThisRandomString
Content-type:text/plain
W一个对象的数据
--ThisRandomString
Content-type:text/plain
W二个(最后一个)对象的数据?
--ThisRandomString--
使用q一技术的关键是,服务器ƈ不是推送整个“multipart/x-mixed-replace”报文,而是每次发送后数据块?
HTTPq接始终保持Q因而服务器可以按自己需要的速度和频率推送新数据Q两个数据块之间览器仅需在当前窗口等候,用户甚至可以到其他窗口做别的事情Q当服务器需要发送新数据Ӟ它只是源QABC输入法没那个?&^$#Q传输管道发送数据块Q客L(fng)相应的窗口进行自我更新?

在服务器推送技术中Q“multipart/x-mixed-replace”类型的报文由唯一的边界线l成Q这些边界线分割每个数据块。每个数据块都有自己的头标,因而能够指定对象相关的内容cd和其他信息。由于“multipart/x-mixed-replace”的Ҏ(gu)是每一新数据块取代前一数据对象Q因而浏览器中L昄最新的数据对象?
“multipart/x-mixed-replace”报文没有结。也是_(d)服务器可以永q保持连接,q发送所需的数据。如果用户不再在览器窗口中昄数据,或者浏览器到服务器间的q接中间Q例如用h“STOP”按钮)Q服务器的推送才?x)中断。这是h们用服务器推送的典型方式?

当浏览器发现“Content-type”头标或到达头标l束处时Q浏览器H口中的前一个文被清除Qƈ开始显CZ一个文档。发C一个报文边界时Q就认ؓ(f)当前数据块(文Q已l结束?
MQ服务器推送的数据׃l头标(通常包括“Content-type”)、数据本w和分割W(报文边界Q三部分l成。浏览器看到分割W时Q它保持状态不变,直到下一个数据块到达?

以上概念进行用~程Ҏ(gu)实现Q就可以得到实际的服务器推送程序。例如,下面的Unix shellE序ɋ览器每5U显CZơ服务器上的q程列表Q?
#!/bin/sh
echo "HTTP/1.1 200"
echo "Content-type: multipart/x-mixed-replace;boundary=--ThisRandomString--"
echo ""
echo "--ThisRandomString--"
while true
do
echo "Content-type: text/html"
echo ""
echo "h2Processes on this machine updated every 5 seconds/h2"
echo "time:"
date
echo "p"
echo "plaintext"
ps -el
echo "--ThisRandomString--"
sleep 5
done
注意刎ͼ边界讄在sleep语句之前发送,q能够确保浏览器清除其缓冲区Qƈ昄所接收到的最新数据?
NCSA HTTPD用户在内容类型中不能使用I格Q包括边界参数。NCSA HTTPD只能不带空格字W的字符串作为内容类型。如果在内容cd行中存在I格Q冒号后面的I格除外Q,I格后的M文本都会(x)被删除?
下面的示例是正确的:(x)
Content-type: multipart/x-mixed-replace;boundary=ThisRandomString
而下例则不能正常工作Q因为它在中间有I格Q?
Content-type: multipart/x-mixed-replace; boundary=ThisRandomString
服务器推送的另一个优Ҏ(gu)它可以针对单个内联图象进行。包括图象的文可以由服务器定时或定周期q行更新。而实现这一炚w常简单:(x)只需使IMG元素的SRC属性指向推送一pd图象的URL卛_?

如果服务器推送用于单个内联图象,文中的图象׃(x)一ơ次被新推送来的图象所代替Q而文本w不需变化Q假设文档没有进行服务器推送)。这PW(xu)EB面中有限的动画可以ؓ(f)静态画面所代替?

客户端拖?

客户端拖曳的一个简单用法是使文档按固定周期自动重蝲。例如,考虑下面的HTML文Q?
<META HTTP-EQUIV="Refresh" CONTENT=1>
<TITLE>Document ONE</TITLE>
<H1>This is Document ONE!</H1>
Here's some text.<P>
如果它载入支持动态文的览器(Netscape 1.1以上QInternet Explorer和Mosaic也支持客L(fng)拖曳Q,它将每隔一U将自己重蝲一ơ?
׃META元素实际是在HTML文中模拟HTTP响应头标Q所以它能够告知览器将自n信息当作HTTP响应使用。上例中的META标记相当于:(x)
Refresh:1
q样Q实际上是HTTP头标告知览器每一U更Cơ文。如果需要g时是12U,那么是q样的指令:(x)
<META HTTP-RQUIV="Refresh" CONTENT=12>
那么它等效于Q?
Refresh:12

关于客户端的拖曳我也懒的l箋写下去,关于怎么使客L(fng)自动甌其他URL的数据话Q请使用如下Q?
<META HTTP-EQUIV="Refresh" CONTENT="12;URL=http://icools.yeah.net/">
注意的是Q此处的URL不能使用相对路径Q必d部指定?

其中旉间隔可以讄?Q这h览器在当前文档显C完毕后Q以最快的速度载入新的数据Q?/font>
 

q回
  

    IT315发表的文档,均来自于相关|站公开发表的内容,如果(zhn)认为本站发表的文章늊了?zhn)的著作权Q请?qing)时与本站取得联p,本站在W一旉内删除。如果?zhn)有好的文章也可以通过Email提供l我们,如果有问题可以在留言板提出?/font>


pear 2006-09-14 19:16 发表评论
]]>
自己~写的NIO非阻塞聊天室http://www.aygfsteel.com/pear/archive/2006/09/09/68763.htmlpearpearSat, 09 Sep 2006 13:59:00 GMThttp://www.aygfsteel.com/pear/archive/2006/09/09/68763.htmlhttp://www.aygfsteel.com/pear/comments/68763.htmlhttp://www.aygfsteel.com/pear/archive/2006/09/09/68763.html#Feedback0http://www.aygfsteel.com/pear/comments/commentRss/68763.htmlhttp://www.aygfsteel.com/pear/services/trackbacks/68763.html http://www.advjava.com/java_io/001/006.html
最q学?fn)了非阻塞IOQNIOQ,因ؓ(f)厌烦(ch)了在开发ƈ行处理时候,dIO所D的肥服务端,因ؓ(f)对于每个客户q接都要产生一个线E对此进行处理,当然你可以不q样实现Q但我的前提是开发ƈ行处理,下面是我的源码,因ؓ(f)是在dos命o(h)行测试的Q所以要是编写ؓ(f)GUI的时候,q要很多要改的东西,q也是我下个征服的对象,当然我已l迫不及(qing)待了Q下面是我花了三个晚上学?fn)ƈ~写的非d聊天室:(x)(供交学?fn)?

客户端:(x)
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.io.BufferedReader;
import java.io.*;
import java.lang.Thread;
import java.nio.charset.*;
import java.nio.charset.CharsetDecoder;

public class ChatClient{
 
 private InetSocketAddress address = new InetSocketAddress("localhost",13);
 private SocketChannel client = null;
 private String user = null;
 private String pass = null;
 private BufferedReader in = null;
 private Thread t = null;
 
 public ChatClient(){
  try{
   client = SocketChannel.open();
   System.out.println("connecting...");
  
   client.connect(address);
   System.out.println("connected with "+address.getHostName());
   client.configureBlocking(false);
  }catch(IOException ex){
   ex.printStackTrace();
   System.exit(-1);
  }
  this.start();
 }
 
 public void start(){
  this.receiveMessage();
  this.sendMessage(); 
 }
 
 public void sendMessage(){
  try{
   in = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("Input the Info then check it out on the server");
   System.out.print("Your Name:");
   user = in.readLine();
   System.out.println("Password:");
   pass = in.readLine();
  
   ByteBuffer buffer = ByteBuffer.allocate(50);
   String message= new String("LOGIN:"+user+"&"+pass);
   buffer = ByteBuffer.wrap(message.getBytes());
   while(buffer.hasRemaining()&client.write(buffer)!=-1);
   System.out.println(message+" has been send");
  
  
   buffer.flip();
   Charset charset = Charset.forName("gb2312");
   CharsetDecoder decoder = charset.newDecoder();
   CharBuffer charBuffer = decoder.decode(buffer);
   //System.out.println("receive:"+charBuffer+" length:"+charBuffer.limit());
  }catch(IOException ex){
   ex.printStackTrace();
  }
 
  this.waitFor(2000);
 
  System.out.println("WELCOME TO THE KING 'S CHAT ROOM!");
  System.out.println("Input the Info(exit is to leave out)");
  while(true){
   System.out.print(">");
 
   ByteBuffer buffer = ByteBuffer.allocate(100);
   in = new BufferedReader(new InputStreamReader(System.in));
   try{
    String read=in.readLine();
    if(read.equals("exit")){
     break;
    }  
    String message1="SENTO:"+read;
    buffer = ByteBuffer.wrap(message1.getBytes());
   // buffer.flip();
    System.out.println("before");
    while(buffer.hasRemaining()&client.write(buffer)!=-1);
   // buffer.flip();
    System.out.println(message1+" has been send");
    this.waitFor(500);
   }catch(IOException ex){
    ex.printStackTrace();
   }
  }
 
  System.out.println("Welcome to use this soft!---King");
  System.exit(-1);
 
 }
 
 public void waitFor(long time){
  try{
   Thread.sleep(time);    
  }catch(Exception ex){
   ex.printStackTrace();
  }
 }
 
 public void receiveMessage(){
  t=new ReceiveThread(client);
  t.start();
 }
 
 public static void main(String[]args){
  ChatClient cc=new ChatClient();
 
 }
 
 class ReceiveThread extends Thread{
  SocketChannel client =null;
  ByteBuffer buffer=ByteBuffer.allocate(50);
  private boolean val=true;
 
  public ReceiveThread(SocketChannel client){
   this.client = client;
  }
 
  public void run(){
   while(val){
    try{
     while (client.read(buffer) > 0){
      buffer.flip();
      String result = decode(buffer);
      System.out.println(">(back)"+result);
      buffer.flip(); 
     }
    }catch(IOException ex){
     ex.printStackTrace();
     return;
    }
  
   }
  }
 }
 
 public String decode(ByteBuffer buffer){
  Charset charset=null;
  CharsetDecoder decoder=null;
  CharBuffer charBuffer=null;
  try{
   charset= Charset.forName("gb2312");
    decoder= charset.newDecoder();
    charBuffer= decoder.decode(buffer);
   return charBuffer.toString();
  }catch(Exception ex){
   ex.printStackTrace();
   return "";
  }
 
 }
}注意Q可以多个客戯行交,E序要求输入验证信息Q但׃旉原因后台我都以合法用L(fng)予回?/p>

服务端:(x)import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.net.ServerSocket;
import java.net.InetSocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.io.IOException;
import java.util.Iterator;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.nio.charset.*;
import java.nio.*;

public class ChatServer {
 
 private int port = 13;
 private Selector selector;
 private ServerSocketChannel ssc;
 private ServerSocket server;
 private InetSocketAddress address;
 private ArrayList connectKey=new ArrayList();
 
 public ChatServer(){
  //initServer 
  try{
   ssc=ServerSocketChannel.open();
   server=ssc.socket();
   address = new InetSocketAddress(port);
   server.bind(address);
   selector=Selector.open();
   ssc.configureBlocking(false);
   ssc.register(selector,SelectionKey.OP_ACCEPT);
   System.out.println("============================================================");
   System.out.println("=                                                                                                                                        =");
   System.out.println("=                                                                                                                                        =");
   System.out.println("=                                     水底沙聊天室Qversion1.0                                                    =");
   System.out.println("=                                                                                                                                        =");
   System.out.println("=                                                                                                QQ:247095340(交流) =");
   System.out.println("============================================================");  
   System.out.println("Listening the port 13..."); 
  }catch(IOException ex){
   ex.printStackTrace();
   System.exit(-1);
  }
 }
 
 public void startServer() throws IOException{
  while(true){
   int i=selector.select();
   //System.out.print(i);
   Iterator keys = selector.selectedKeys().iterator();
  
   while(keys.hasNext()){
    SelectionKey key = (SelectionKey)keys.next();
    keys.remove();
    try{   
     if(key.isAcceptable()){
      ServerSocketChannel ssc=(ServerSocketChannel)key.channel();    
      SocketChannel channel = ssc.accept();//return null if there's no request
      System.out.println(channel+" has accepted");
      channel.configureBlocking(false);
      SelectionKey clientKey=channel.register(selector,SelectionKey.OP_READ);    
     }//else
     if(key.isWritable()){
      SocketChannel channel = (SocketChannel)key.channel();
      ByteBuffer buffer = (ByteBuffer)key.attachment();
     
      if(buffer!=null){  
       key.attach(null);//avoid the return twice
      
       //check info:the login or the message
       //buffer.flip();
       String checkBuffer = this.decode(buffer);
       System.out.println("write:"+checkBuffer);
      
       if(checkBuffer.equals("LOGIN:OK")){
        //return LOGIN:OK then add into the connectKey array!
        System.out.println("ok"+buffer);
        buffer.flip();
        //while(buffer.hasRemaining()&channel.write(buffer)!=-1);
        channel.write(buffer);
        key.interestOps(SelectionKey.OP_READ|SelectionKey.OP_WRITE);     
        connectKey.add(key);//add to the connectKey array
        System.out.println("here");
       }else if(checkBuffer.equals("LOGIN:ERROR")){
        //return LOGIN:ERROR the client should close the channel
        //warning:method:key.channel();
        //Returns the channel for which this key was created.
        // This method will continue to return the channel even after the key is cancelled.
        while(buffer.hasRemaining()&channel.write(buffer)!=-1);
        key.cancel();
       }else //if(checkBuffer.indexOf("SENTO:")!=-1){
       {
       
        //return the message to everyone
       // while(buffer.hasRemaining()&channel.write(buffer)!=-1);
       
        System.out.println("sento"+buffer);
        buffer.flip();
        channel.write(buffer);
        System.out.println("send over");
       }
      }
     }//else
     if(key.isReadable()){
      SocketChannel channel = (SocketChannel)key.channel();
      ByteBuffer buffer=ByteBuffer.allocate(50);
      System.out.println("read...");
     
      channel.read(buffer);
 
      buffer.flip();
      String checkBuffer = this.decode(buffer);
      System.out.println("read:"+checkBuffer);
    
      //while(buffer.hasRemaining()&&channel.read(buffer)!=-1);
     
      //check the buffer
      //buffer.flip();
     
      //String checkBuffer = this.decode(buffer);
     // System.out.println("read:"+checkBuffer);
     
    
      if(checkBuffer.startsWith("LOGIN:")){
       //get info of the user & pass then check for it,return feedback!
       //the format is LOGIN:user&pass
       int p1=checkBuffer.length();
       int p2=checkBuffer.indexOf("&");
      
       String user=checkBuffer.substring(6,p2);
       String pass=checkBuffer.substring(p2+1,p1);
       System.out.println(user+pass);
      
       //todo check from the database!!!
       //assume the user is legal
       ByteBuffer feedback = ByteBuffer.allocate(20);
       feedback=ByteBuffer.wrap("LOGIN:OK".getBytes());
       key.interestOps(SelectionKey.OP_WRITE);
       key.attach(feedback);     
      }else if(checkBuffer.startsWith("SENTO:")){
       String message = checkBuffer.substring(6);
       System.out.println("sentto:"+message);
       ByteBuffer buffer1 = ByteBuffer.allocate(50);
       buffer1=ByteBuffer.wrap(message.getBytes());
       Iterator it = connectKey.iterator();
       //key.interestOps(SelectionKey.OP_WRITE);
       while(it.hasNext()){
        ((SelectionKey)it.next()).attach(buffer1.duplicate());
       }
       System.out.println("here1");
       //for(int i=0;i<connectKey.add.;i++){
        //connectKey[i].attach(buffer.duplicate());
       //}
      }
     }
    }catch(IOException ex){
     key.cancel();
     //System.exit(-1);
     try{
      key.channel().close();
     }catch(IOException cex){
     }
    }
   }
  }
 }
 
 public String decode(ByteBuffer buffer){
  Charset charset=null;
  CharsetDecoder decoder=null;
  CharBuffer charBuffer=null;
  try{
   charset= Charset.forName("gb2312");
    decoder= charset.newDecoder();
    charBuffer= decoder.decode(buffer);
   return charBuffer.toString();
  }catch(Exception ex){
   ex.printStackTrace();
   return "";
  }
 
 }
 
 public static void main(String []args){
  ChatServer cs = new ChatServer();
  try{
   cs.startServer();
  }catch(IOException ex){
   ex.printStackTrace();
   System.exit(-1);
  }
 }
}注意Q假如客户强制登出服务端时候,服务器里面的d用户列表q是保存他注册的SelectionKey地址Q这是存在问题,其实解决很简单,在对通道q行写入时候,如果通道已经被关闭的话,可以用try/catch语句q行处理

上面是ȝE序Q其实之前我都是用阻塞socketd成这cd作的Q由于在用swtZ实现时候遇到很多swtU程问题Q后期我?x)以GUI界面׃nl大Ӟ当然自己也在不断学习(fn)中!King



pear 2006-09-09 21:59 发表评论
]]>
cronExpression的说?摘自http://www.opensymphony.com) http://www.aygfsteel.com/pear/archive/2006/09/03/67407.htmlpearpearSun, 03 Sep 2006 07:37:00 GMThttp://www.aygfsteel.com/pear/archive/2006/09/03/67407.htmlhttp://www.aygfsteel.com/pear/comments/67407.htmlhttp://www.aygfsteel.com/pear/archive/2006/09/03/67407.html#Feedback1http://www.aygfsteel.com/pear/comments/commentRss/67407.htmlhttp://www.aygfsteel.com/pear/services/trackbacks/67407.htmlCron expressions are comprised of 6 required fields and one optional field separated by white space. The fields respectively are described as follows:
Field Name   Allowed Values   Allowed Special Characters
Seconds   0-59   , - * /
Minutes   0-59   , - * /
Hours   0-23   , - * /
Day-of-month   1-31   , - * ? / L W C
Month   1-12 or JAN-DEC   , - * /
Day-of-Week   1-7 or SUN-SAT   , - * ? / L #
Year (Optional)   empty, 1970-2099   , - * /

The '*' character is used to specify all values. For example, "*" in the minute field means "every minute".

The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fileds, but not the other.

The '-' character is used to specify ranges For example "10-12" in the hour field means "the hours 10, 11 and 12".

The ',' character is used to specify additional values. For example "MON,WED,FRI" in the day-of-week field means "the days Monday, Wednesday, and Friday".

The '/' character is used to specify increments. For example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". Specifying '*' before the '/' is equivalent to specifying 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or off. For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to 31, and for months 1 to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus "7/6" in the month field only turns on month "7", it does NOT mean every 6th month, please note that subtlety.

The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" means "the last friday of the month". When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing results.

The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single day, not a range or list of days.

The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to "last weekday of the month".

The '#' character is allowed for the day-of-week field. This character is used to specify "the nth" XXX day of the month. For example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month.

The legal characters and the names of months and days of the week are not case sensitive.



pear 2006-09-03 15:37 发表评论
]]>
վ֩ģ壺 ٲ| | | | ɽ| | ˮ| Ǧɽ| | | ƽ˳| п| ¹| ڰ| | ʡ| | | | ӳ| ΢ɽ| | Ϫ| | | ͷ| ¦| | | | ³ƶ| | ƽ| | | | | | | | ̩|