搞懂java中的synchronized关键字

实际上,我关于java的基础知识的90%以上都来自Thinking in Java。对于其中的synchronized关键字,当时就是浏览一下,大概知道意思,也没有细看。后来一直没有用过这个关键字。昨天看Thinking in Patterns with Java中的Observer模式,看了其中的Observable类的源码,发现里面几乎所有的方法都用了synchronized关键字(不是全部),其中个别用了synchronized(this){}的区块。于是,我发觉有必要好好理解一下这个关键字了。

我再次看了侯捷译的Thinking in Java第二版中文版,得到有关synchronized的如下信息:

1、synchronized关键字的作用域有二种:

1)是某个对象实例内,synchronized aMethod(){}可以防止多个线程同时访问这个对象的synchronized方法(如果一个对象有多个synchronized方法,只要一个线程访问了其中的一个synchronized方法,其它线程不能同时访问这个对象中任何一个synchronized方法)。这时,不同的对象实例的synchronized方法是不相干扰的。也就是说,其它线程照样可以同时访问相同类的另一个对象实例中的synchronized方法;

2)是某个类的范围,synchronized static aStaticMethod{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。

2、除了方法前用synchronized关键字,synchronized关键字还可以用于方法中的某个区块中,表示只对这个区块的资源实行互斥访问。用法是: synchronized(this){/*区块*/},它的作用域是当前对象;

3、synchronized关键字是不能继承的,也就是说,基类的方法synchronized f(){} 在继承类中并不自动是synchronized f(){},而是变成了f(){}。继承类需要你显式的指定它的某个方法为synchronized方法;

4、疑问:

我知道了有static区块(其中的加载时机好像也不清楚,需要学习一下,原来看Thinking in Java好像是说: static区块加载的时机是类的一个对象实例创建或类的一个static方法被访问,但是我今天早上看了javaeye.com上面的一个关于“<static块到底什么时候执行?-eway -JavaEye技术社区>”的文章后又有点迷糊了:),也许,需要认真学习一下JVM的内在机制才是理解这类问题最根本的途径),也有synchronized区块,那么,有synchronized static 区块吗?意思是问:有没有一个类作用域内的synchronized区块?

 

浏览了一下《JAVA游戏编程》

前两天,我到新华书店浏览了一本Java游戏编程,一直想把其中的所得记下来。不过直到今天才动手。

这本书是外国人写的。主要是以Java为载体,谈游戏编程的基本技术。

如:多线程、人工智能、碰撞、B树什么的,还有贴图,纹理,等等。这些都是游戏编程一些比较基本的东西。除了这些技术性的内容,还讲了怎样用你的游戏挣钱:或者自己把它包装成一个产品,销售给大家,又提到了销售反馈;或者作为一个找一份好工作的资本:)

从我感觉,这本书把多线程放在了开头,说明多线程在游戏编程中是很重要的。

另外,这本书还让我知道了一些J2se1.5(J2se5.0)的特性。

如:

模板,在一个List中可以控制放入的对象;

改进的for循环,主要用于类似set的容器类中;

枚举类型;

实际,现在J2se6.0都出来了。不过,我一直都还用的J2se1.4。

在这本书中,作者还对Java在游戏编程中未来需要改进的东西作了一些描述。

在我的感觉中,游戏设计是一门综合性的技术,是各种学科的东西都要用到的尖端产品。游戏设计应该是一项很有挑战性的工作,而且,能够把游戏编程做好的人都是“人中精英”吧。

说起来,我参加工作后,对编程感兴趣还是来自于一台学习机上的Gbasic,我在上面兴致勃勃的用程序画一些有各种参数改变的立方体,做一些小的游戏角色碰到子弹就消失的东西。很有成就感。于是,就自考计算机,学编程到现在,不过都是业余兴趣而已。

jsp 中的301重定向帖子(转帖)

这位用的环境和需求和我的差不多,好像可以试一试。今天我作的重定向有的检测网站返回301,有的返回500

今天再把下面帖子的方法试试。

转帖:(转自:http://www.caucho.com/support/resin-interest/0510/0009.html

**************************************************************************************************************************

Re: 301 redirect

 · This message: [ Message body ] [ More options ]

 · Related messages: [ Next message ] [ Previous message ] [ In reply to ]

From: Thomas Moorer <thomas.moorer@xxx.com>

Date: Sat Oct 22 2005 - 04:44:52 PDT

Hi All,

Never mind ? I figured it out. I?ll post the solution in case anyone else

needs it later.

Old jsp redirecting to new location.

 try {

     response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

     response.setHeader( "Location", "/buy-a-business/index.jsp" );

     response.setHeader( "Connection", "close" );

     return;

 } catch (Exception e) {}

Proof in log file. Highlighted in red.

[2005/10/22 07:37:53 - INFO] 127.0.0.1 : /buyers/index.jsp loaded in 2.292

seconds.

[2005/10/22 07:37:53.060] [www-2005.sunbeltnetwork.com, 11] HTTP/1.1 301

Moved Permanently

[2005/10/22 07:37:53.066] [www-2005.sunbeltnetwork.com, 11] Location:

/buy-a-business/index.jsp

[2005/10/22 07:37:53.067] [www-2005.sunbeltnetwork.com, 11] Connection:

close

[2005/10/22 07:37:53.067] [www-2005.sunbeltnetwork.com, 11] Content-Type:

text/html

[2005/10/22 07:37:53.068] [www-2005.sunbeltnetwork.com, 11]

Transfer-Encoding: chunked

[2005/10/22 07:37:53.085] [www-2005.sunbeltnetwork.com, 11] keepalive

[2005/10/22 07:37:53.086] [www-2005.sunbeltnetwork.com, 11] read timeout

[2005/10/22 07:37:53.091] closing connection

TcpConnection[id=resin-tcp-connection-www-tcm.sunbeltnetwork.com:80-23,socke

t=JniSocketImpl$12218796[41838600],port=Port[www-tcm.sunbeltnetwork.com:80]]

, total=10

[2005/10/22 07:37:53.109] starting connection

TcpConnection[id=resin-tcp-connection-www-tcm.sunbeltnetwork.com:80-39,socke

t=JniSocketImpl$8441961[41834504],port=Port[www-tcm.sunbeltnetwork.com:80]],

total=10

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] GET

/buy-a-business/index.jsp HTTP/1.1

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Accept: */*

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Accept-Language:

en

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Accept-Encoding:

gzip, deflate

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Cookie:

ANONID=LZ3ZE1CY4LERDFSYCSORMMHP47JRP7APWTWIB5C9; JSESSIONID=JmHyfpl_hX57gXgy

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] User-Agent:

Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412.7 (KHTML, like

Gecko) Safari/412.5

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Connection:

keep-alive

[2005/10/22 07:37:53.110] [www-2005.sunbeltnetwork.com, 19] Host:

www-tcm.sunbeltnetwork.com

[2005/10/22 07:37:53.120] [www-2005.sunbeltnetwork.com, 19] HTTP/1.1 200 OK

[2005/10/22 07:37:53.120] [www-2005.sunbeltnetwork.com, 19] Content-Type:

text/html

[2005/10/22 07:37:53.120] [www-2005.sunbeltnetwork.com, 19]

Transfer-Encoding: chunked

[2005/10/22 07:37:53.121] [19] chunk: 1424

[2005/10/22 07:37:53.122] [19] chunk: 3813

[2005/10/22 07:37:53.123] [19] chunk: 2526

[2005/10/22 07:37:53.148] [19] chunk: 2078

[2005/10/22 07:37:53 - INFO] 127.0.0.1 : /buy-a-business/index.jsp loaded in

0.037 seconds.

Thomas

--

Thomas C. Moorer, Jr. ~ IT Manager

103 Church Street

Mount Pleasant, SC 29464

Sunbelt Business Advisors Network, LLC

http://www.sunbeltnetwork.com

From: Thomas Moorer <thomas.moorer@xxx.com>

Reply-To: "resin-interest@xxx.com" <resin-interest@xxx.com>

Date: Fri, 21 Oct 2005 18:01:25 -0400

To: "resin-interest@xxx.com" <resin-interest@xxx.com>

Conversation: 301 redirect

Subject: Re: 301 redirect

Yong,

Thanks for the reply...

I believe it would be better to do the 301 (Moved Permanently) than the

rewrite. I want the Search Engines to know I have renamed my pages (but not

reduce my page ranking - hopefully they will give be a better page rank over

time) (I know this is a lot of marketing talk in a techie forum, but I am

trying to solve essentially a marketing problem with technology). Anyhoo...

There wasn't a matching function in the HttpServletRedirect class for your

suggestion, so I am trying to come up with a comparable solution (see mine

below). I believe this should work correctly. I mean, it obviously will

redirect to the new page - that works.

I am attmepting to redirect from /buyers/index.jsp to /buy-a-business.jsp.

The code below is in /buyers/index.jsp

 try {

     response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

     response.sendRedirect("/buy-a-business/index.jsp");

     return;

 } catch (Exception e) {}

My remaining question still pertains to the Status code. I have full logging

on and I'm not seeing a 301 Status code being returned... Below is a snippet

from the log file. It seems to from a 302 to a 200 code highlighted in red

(if you?ve got an html client).

[2005/10/21 17:57:04.842] starting connection

TcpConnection[id=resin-tcp-connection-www-tcm.sunbeltnetwork.com:80-25,socke

t=JniSocketImpl$15241174[125306376],port=Port[www-tcm.sunbeltnetwork.com:80]

], total=10

[2005/10/21 17:57:04.842] [www-2005.sunbeltnetwork.com, 12] GET

/buyers/index.jsp HTTP/1.1

[2005/10/21 17:57:04.842] [www-2005.sunbeltnetwork.com, 12] Accept: */*

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] Accept-Language:

en

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] Accept-Encoding:

gzip, deflate

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] Cookie:

ANONID=LZ3ZE1CY4LERDFSYCSORMMHP47JRP7APWTWIB5C9; JSESSIONID=CzyD9BkGE3-3Awbt

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] User-Agent:

Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412.7 (KHTML, like

Gecko) Safari/412.5

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] Connection:

keep-alive

[2005/10/21 17:57:04.843] [www-2005.sunbeltnetwork.com, 12] Host:

www-tcm.sunbeltnetwork.com

[2005/10/21 17:57:04.846] [www-2005.sunbeltnetwork.com, 12] HTTP/1.1 302

Found

[2005/10/21 17:57:04.846] [www-2005.sunbeltnetwork.com, 12] Location:

http://www-tcm.sunbeltnetwork.com/buy-a-business/index.jsp

[2005/10/21 17:57:04.846] [www-2005.sunbeltnetwork.com, 12] Content-Type:

text/html

[2005/10/21 17:57:04.846] [www-2005.sunbeltnetwork.com, 12] Content-Length:

96

[2005/10/21 17:57:04.846] [12] chunk: 96

[2005/10/21 17:57:04 - INFO] 127.0.0.1 : /buyers/index.jsp loaded in 0.026

seconds.

[2005/10/21 17:57:04.872] [www-2005.sunbeltnetwork.com, 12] keepalive

[2005/10/21 17:57:04.872] [www-2005.sunbeltnetwork.com, 12] read timeout

[2005/10/21 17:57:04.872] closing connection

TcpConnection[id=resin-tcp-connection-www-tcm.sunbeltnetwork.com:80-25,socke

t=JniSocketImpl$15241174[125306376],port=Port[www-tcm.sunbeltnetwork.com:80]

], total=10

[2005/10/21 17:57:04.873] starting connection

TcpConnection[id=resin-tcp-connection-www-tcm.sunbeltnetwork.com:80-25,socke

t=JniSocketImpl$15241174[125306376],port=Port[www-tcm.sunbeltnetwork.com:80]

], total=10

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] GET

/buy-a-business/index.jsp HTTP/1.1

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Accept: */*

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Accept-Language:

en

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Accept-Encoding:

gzip, deflate

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Cookie:

ANONID=LZ3ZE1CY4LERDFSYCSORMMHP47JRP7APWTWIB5C9; JSESSIONID=CzyD9BkGE3-3Awbt

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] User-Agent:

Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412.7 (KHTML, like

Gecko) Safari/412.5

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Connection:

keep-alive

[2005/10/21 17:57:04.873] [www-2005.sunbeltnetwork.com, 12] Host:

www-tcm.sunbeltnetwork.com

[2005/10/21 17:57:04.874] using cache: /head.jsp

[2005/10/21 17:57:04.875] [www-2005.sunbeltnetwork.com, 12] HTTP/1.1 200 OK

[2005/10/21 17:57:04.875] [www-2005.sunbeltnetwork.com, 12] Content-Type:

text/html

[2005/10/21 17:57:04.875] [www-2005.sunbeltnetwork.com, 12]

Transfer-Encoding: chunked

I don?t know if I have the status set in the right place / right sequence.

Can anyone help me out?

Thomas

--

Thomas C. Moorer, Jr. ~ IT Manager

103 Church Street

Mount Pleasant, SC 29464

Sunbelt Business Advisors Network, LLC

http://www.sunbeltnetwork.com

> From: Yong Bakos <yongb@xxx.com>

> Reply-To: "resin-interest@xxx.com" <resin-interest@xxx.com>

> Date: Mon, 17 Oct 2005 14:20:54 -0600

> To: <resin-interest@xxx.com>

> Conversation: 301 redirect

> Subject: RE: 301 redirect

>

>

> I'm a bit confused as to why you don't just use the filter or roll your

> own and use the addHeader(HttpServletResponse.SC_MOVED_PERMANENTLY,

> newPath) method in HttpServletResponse.

>

>

> -----Original Message-----

> From: owner-resin-interest@xxx.com

> [mailto:owner-resin-interest@xxx.com] On Behalf Of Thomas Moorer

> Sent: Monday, October 17, 2005 1:57 PM

> To: resin-interest@xxx.com

> Subject: Re: 301 redirect

>

> After reading my original message, I feel I need to clarify one point as

> well as ask and additional question:

>

> Clarification:

>

> I have my web.xml file configured to use the rewrite filter, but the

> scenario below is not in use. It is just an example of how I might use

> the rewrite filter to handle a directory name change.

>

> Question:

>

> When a rewrite filter actually does the move what is the underlying http

> status code that is returned? Obviously 301 is the one I would prefer...

>

> 301 Moved Permanently

> 302 Found

> 303 See Other

> 304 Not Modified

> 305 Use Proxy

> 306 (Unused)

> 307 Temporary Redirect

>

> Thomas

>

> --

>

> Thomas C. Moorer, Jr. ~ IT Manager

> 103 Church Street

> Mount Pleasant, SC 29464

> Sunbelt Business Advisors Network, LLC

> http://www.sunbeltnetwork.com

>

>

>

> ________________________________

>

> From: Thomas Moorer <thomas.moorer@xxx.com>

> Reply-To: "resin-interest@xxx.com" <resin-interest@xxx.com>

> Date: Mon, 17 Oct 2005 15:22:33 -0400

> To: "resin-interest@xxx.com" <resin-interest@xxx.com>

> Conversation: 301 redirect

> Subject: 301 redirect

>

> Hi All,

>

> I am currently using resin 3.0.12 pro on Solaris 9. I am running resin

> with the built-in web server. My question is this: I need to rename some

> files and directories for SEO purposes and I am trying to determine the

> best way to do it. Our SEO company tells me the best way from a search

> engine perspective is to do a 301 redirect. I did some Googling and

> found the following page

> http://www.tamingthebeast.net/articles3/spiders-301-redirect.htm which

> explains how to do a 301 in an Apache .htaccess page. Since I am using

> the built-in web server is this possible or must I do this another way?

>

> The only other way I can think of to do this is to use the Rewrite

> Filter (I already have this configured in my web.xml file).

>

> <filter filter-name='rewrite'

> filter-class='com.caucho.filters.RewriteFilter'>

>     <init>

>         <rewrite pattern='/buyers/([A-Z]+)'

> target='/buy-a-business/$1'/>

>     </init>

> </filter>

>

> Example:

>

> /buyers/index.jsp  rewrites to /buy-a-business/index.jsp

>

> Does anyone know if the second option will have any ill effects or

> better yet how I can do a 301 redirect using resin's built in web

> server?

>

> Thomas

>

> --

>

> Thomas C. Moorer, Jr. ~ IT Manager

> 103 Church Street

> Mount Pleasant, SC 29464

> Sunbelt Business Advisors Network, LLC

> http://www.sunbeltnetwork.com

>

>

>

>

Received on Sat 22 Oct 2005 04:44:52 -0700

 · This message: [ Message body ]

 · Next message: Emmanuel Idi: "mod_caucho.so on Mac OS X Tiger..."

 · Previous message: Thomas Moorer: "Re: 301 redirect"

 · In reply to: Thomas Moorer: "Re: 301 redirect"

 · Contemporary messages sorted: [ By Date ] [ By Thread ] [ By Subject ] [ By

    Author ] [ By messages with attachments ]

This archive was generated by hypermail 2.1.8 : Thu Sep 28 2006 - 20:18:50 PDT

Java概述,数 据 类 型,运 算 符 和 表 达式网址

一些在java中非常基础的东西,把目录贴在这里供收藏参考。

转自(http://www.sdau.edu.cn/support/html/jindex.htm

Java 语言人门

            第 一 章   Java 概 述

      § 1.1 Java 语 言 出 现 的 背 景 、 影 响 及应 用 前 景

      § 1.2 Java 的 特 点

      § 1.3 简 单 的 Java 程 序

            第 二 章   数 据 类 型

      § 2.1 数 据 类 型

      § 2.2 常 量 与 变 量

      § 2.3 整 型 数 据

      § 2.4 浮 点 型 (实 型) 数 据

      § 2.5 字 符 型 数 据

      § 2.6 布 尔 型 数 据

      § 2.7 举 例

            第 三 章   运 算 符 和 表 达式

      § 3.1 算 术 运 算 符

      § 3.2 关 系 运 算 符

      § 3.3 布 尔 逻 辑 运 算 符

      § 3.4 位 运 算 符

Java语言中的取整运算(包括截尾取整,四舍五入,凑整)�

在Java中进行取整,尤其是四舍五入取整还有点麻烦。

下面是我根据网上的一些解答整理的三种取整运算(包括截尾取整,四舍五入,凑整),类似于面向过程语言(如C和Basic)中的取整函数(不过在Java中它叫类的方法,“类名.方法名(参数)”的运算都是类的静态方法)。

其中,注释掉的那段是在网上查到的有的朋友认为正确的四舍五入的取整方法,但是经过我的实验却是不正确的四舍五入的取整方法。

TestGetInt.java 源代码


import java.math.BigDecimal;

import java.text.DecimalFormat;

public class TestGetInt{

  public static void main(String[] args){

double i=2, j=2.1, k=2.5, m=2.9;

System.out.println("舍掉小数取整:Math.floor(2)=" + (int)Math.floor(i));

System.out.println("舍掉小数取整:Math.floor(2.1)=" + (int)Math.floor(j));

System.out.println("舍掉小数取整:Math.floor(2.5)=" + (int)Math.floor(k));

System.out.println("舍掉小数取整:Math.floor(2.9)=" + (int)Math.floor(m));

                                                                               

/* 这段被注释的代码不能正确的实现四舍五入取整

System.out.println("四舍五入取整:Math.rint(2)=" + (int)Math.rint(i));

System.out.println("四舍五入取整:Math.rint(2.1)=" + (int)Math.rint(j));

System.out.println("四舍五入取整:Math.rint(2.5)=" + (int)Math.rint(k));

System.out.println("四舍五入取整:Math.rint(2.9)=" + (int)Math.rint(m));

    

System.out.println("四舍五入取整:(2)=" + new DecimalFormat("0").format(i));

System.out.println("四舍五入取整:(2.1)=" + new DecimalFormat("0").format(i));

System.out.println("四舍五入取整:(2.5)=" + new DecimalFormat("0").format(i));

System.out.println("四舍五入取整:(2.9)=" + new DecimalFormat("0").format(i));

*/

System.out.println("四舍五入取整:(2)=" + new BigDecimal("2").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(2.1)=" + new BigDecimal("2.1").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(2.5)=" + new BigDecimal("2.5").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(2.9)=" + new BigDecimal("2.9").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("凑整:Math.ceil(2)=" + (int)Math.ceil(i));

System.out.println("凑整:Math.ceil(2.1)=" + (int)Math.ceil(j));

System.out.println("凑整:Math.ceil(2.5)=" + (int)Math.ceil(k));

System.out.println("凑整:Math.ceil(2.9)=" + (int)Math.ceil(m));

System.out.println("舍掉小数取整:Math.floor(-2)=" + (int)Math.floor(-i));

System.out.println("舍掉小数取整:Math.floor(-2.1)=" + (int)Math.floor(-j));

System.out.println("舍掉小数取整:Math.floor(-2.5)=" + (int)Math.floor(-k));

System.out.println("舍掉小数取整:Math.floor(-2.9)=" + (int)Math.floor(-m));

System.out.println("四舍五入取整:(-2)=" + new BigDecimal("-2").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(-2.1)=" + new BigDecimal("-2.1").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(-2.5)=" + new BigDecimal("-2.5").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("四舍五入取整:(-2.9)=" + new BigDecimal("-2.9").setScale(0, BigDecimal.ROUND_HALF_UP));

System.out.println("凑整:Math.ceil(-2)=" + (int)Math.ceil(-i));

System.out.println("凑整:Math.ceil(-2.1)=" + (int)Math.ceil(-j));

System.out.println("凑整:Math.ceil(-2.5)=" + (int)Math.ceil(-k));

System.out.println("凑整:Math.ceil(-2.9)=" + (int)Math.ceil(-m));

    }

}

以上代码用的方法我也没有经过非常系统的学习和验证,如果哪位朋友发现问题请一定帮忙指正一下。谢谢。

java.net.ConnectException: Connection timed out: connect

今天上午10:00开始,空间换IP,中断访问数小时。我在域名控制面板中更改了dns记录,把域名指向新的IP后,大概1个多小时吧,新的域名解析就生效了。原来听说域名解析要6个小时以上才会生效,现在生效时间这么快,是现在的技术更新了,还是只是局部用户访问有效呢(比如外国用户访问时就并没有生效,也就是说全球的IP解析生效不同步)?我就不得而知了。网络方面的知识还是太少了。

空间恢复访问后,基本上是正常。但是我发现本站生成静态文件的部分不能工作了。下面这段代码执行出错:


import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

...

URL url = new URL(str);

URLConnection connection = url.openConnection();

connection.connect();

报错为:


java.net.ConnectException: Connection timed out: connect

后来,连这个状态都达在到了,报错为:


 java.net.UnknownHostException: java.learndiary.com

上网查了资料,感觉下面这个论坛的问题跟我碰到的有点相像:

http://forum.java.sun.com/thread.jspa?threadID=450114&messageID=2043150

其中最后那位朋友的回复启发了我如下:


ckelley114

Posts:1

Registered: 4/5/06

java.net.ConnectException: Connection timed out  

Apr 5, 2006 7:55 AM (reply 3 of 3)

Click to email this message

This is a remote site connection to the internet with a DSL modem and a Cisco pix fire wall. When they get this message they can still use the internet, but can not use the current application. The server is a Windows 2000. To release them they have to cycle the power to the DSL modem and Cisco pix. Can you tell me what is causing this problem?

我连猜带蒙看他的大意是:远程站点通过一个DSL modem和一个Cisco pix防火墙连接到因特网。通过因特网访问能够工作,但是当前的应用访问不能工作,会得到上面的出错信息。是windows2000服务器。解决这个问题必须使访问通过DSL modem和Cisco pix防火墙...

还有另一个地方的答案也与防火墙有关:

转自:(http://www.iexp.com/support/forums/message.cfm?message_ID=260


 

Support Forums

Forums

CFX_RawSocket

java.net.ConnectException: Connection timed out: connect. Java exception occurred in call to method

Subject:  RE: RE: RE: java.net.ConnectException: Connection timed out: connect. Java exception occurred in call to method

Date:  03/18/2004 10:01 AM

Author:  Dominic <oad74@yahoo.com >

  Reply to this message

Just want to appreciate the answer given to this problem. I had the same problem

connectiong to a server behind a firewall and changing

IP address to the machine name works.

bravo!

Dominic

------------

>Hi,

>

>

I guess you might be trying to connect to the

>

server which is behind a firewall. Generally the

>

IP address of the server will be different behind

>

firewall and outside the firewall. So instead of

>

using the IP address if you use the fully qualified

>

host name of the server while connecting, then it

>

will connect without this exception.

>

>

Murali.

>

>

>

------------

>

>------------

>

>

>

>If I implement the tag in Coldfusion and I try to call it it comes back with the error: java.net.ConnectException: Connection timed out: connect. Java exception occurred in call to method. I think this is due to the fact that my server is behind a firewall so uit can't get to the url provided. How can I define a proxy server to connect the URL provided?

的确,通过我的手工输入调用访问上面的代码能够工作。就是空间里的程序本身不能访问。

我试着把域名改为其它的辅助域名(www.learndiary.com或www.123go.org.cn,都是用301重定向到主域名java.learndiary.com的)就一切正常了。

又是一个糊里糊涂的出现问题,糊里糊涂的解决问题的例子。

这叫知其然不知其所以然。没办法,我没有能力去掌握所有的知识和细节。只要解决问题就OK了。

JSP中读文件和写文件的例子(转帖)

转自:(http://www.programfan.com/article/showarticle.asp?id=2495


 <%@ page import="java.io.*" %>

<html>

  <head>

    <title>Lion互动网络==》JSP中读文件和写文件的例子</title>

  </head>

  <body>

   <%

//写文件

String str = "WWW.LIONSKY.NET";

String filename = request.getRealPath("lionsky.txt");

java.io.File f = new java.io.File(filename);

if(!f.exists())//如果文件不存,则建立

{

  f.createNewFile();

}

try

{

  PrintWriter pw = new PrintWriter(new FileOutputStream(filename));

  pw.println(str);//写内容

  pw.close();

}

catch(IOException e)

{

  out.println(e.getMessage());

}

//读文件

java.io.FileReader fr = new java.io.FileReader(f);

char[] buffer = new char[10];

int length; //读出的字符数(一个中文为一个字符)

//读文件内容

out.write(filename+"<br>");

while((length=fr.read(buffer))!=-1)

{

  //输出

  out.write(buffer,0,length);

}

fr.close();

%>

  </body>

</html>

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( ProgramFan.Com )

在Struts Action对象中得到类似jsp页面application的ServletContext

今天需要把数据存在网站程序全局范围,需要在struts Aciton对象中得到 ServletContext对象,与jsp页面的application一样。在google中搜索到如下帖子。转帖于此:

How to get 'application' in Struts Action class? (转自:http://forum.java.sun.com/thread.jspa?threadID=609998&messageID=3346689

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

How to get 'application' in Struts Action class?  

Mar 23, 2005 7:45 PM

Click to email this message

 

Hello,

I have a question on how to get 'application' in Struts Action class.

In the jsp file, i have set an application attribute:

<%

applicaiton.setAttribute("userId", "testUser");

%>

But how to get this application attribute in Struts Action class?

So far I only know how to get session in Struts Action class by using:

(HttpServletRequest)request.getSession();

 

[Dukes Earned 1425] evnafets

Posts:7,577

Registered: 29/04/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:08 PM (reply 1 of 2)

Click to email this message

 

The "application" in a JSP page is the ServletContext object.

In a standard servlet you can use

ServletContext application = getServletConfig().getServletContext();

In a Struts Action class, just have to get hold of the servlet first

ServletContext application = getServlet().getServletConfig().getServletContext();

Cheers,

evnafets

 

[Dukes Earned 0] nonameisname

Posts:24

Registered: 8/13/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:33 PM (reply 2 of 2)

Click to email this message

 

Hi evnafets,

Thanks a lot for your help. It works.

By the way, i found that it is possible to get ServletContext in Struts in two ways:

ServletContext application = getServlet().getServletConfig().getServletContext();

or

ServletContext application = getServlet().getServletContext();

Both work fine. Any concern about the 2nd way? It does not getServletConfig() but instead it straight away getServletContext().

*********************************************************************************************************

                       转帖完毕

一个实现将JSP动态页面转为静态的方案(转帖)

最近早上的时候发现首页很难完整打开(其它页正常),搞不懂为什么白天网络繁忙的时候才有可能出现问题在早上出现。我看了网络当前用户只有我一个人,但是数据库当前又只有两个连接(加上我查询连接数据的一个共3个)。不知道是不是这时是搜索引擎们勤奋工作的结果。但老是这样下去也不是办法。

解决的办法有两个:1、缓存数据;2、页面静态化;

暂时想只把首页的数据进行尽量简单的缓存,也许根本就不叫真正意义的缓存,把首页的数据存在程序全局变量中,只有帖子提交后才更新其中的数据。

这样,当首页要取数据时就不用读数据库了。如果这样还不行的话就试试先把首页静态化。再不行的话只有问问空间提供商了。

下面是转帖的一个JSP动态页面静态化的一个方案,贴在这里备用。

***********************************************************************************************************

一个实现将动态页面转为静态的方案(转自:http://java.ccidnet.com/art/3741/20061008/915263_1.html

 

正文

************************************************************************************************************

 

1.前言

为了能深入浅出的理解这个框架的由来,我们首先来了解一下JSP解析器将我们写的JSP代码转换成的JAVA文件的内容。

下面是一个JSP文件test.jsp

<%@ page language=java contentType=text/html;charset=GB2312 %>

<%

out.write();

%>

<%= 输出%>

经过TOMCAT转换出的JAVA文件test$jsp.java内容如下:

package org.apache.jsp;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

import org.apache.jasper.runtime.*;

 

public class test$jsp extends HttpJspBase {

 

    static {

    }

    public testOutRedir$jsp( ) {

    }

 

    private static boolean _jspx_inited = false;

 

    public final void _jspx_init() throws org.apache.jasper.runtime.JspException {

    }

 

    public void _jspService(HttpServletRequest request, HttpServletResponse  response)

        throws java.io.IOException, ServletException {

 

        JspFactory _jspxFactory = null;

        PageContext pageContext = null;

        HttpSession session = null;

        ServletContext application = null;

        ServletConfig config = null;

        JspWriter out = null;

        Object page = this;

        String  _value = null;

        try {

 

            if (_jspx_inited == false) {

                synchronized (this) {

                    if (_jspx_inited == false) {

                        _jspx_init();

                        _jspx_inited = true;

                    }

                }

            }

            _jspxFactory = JspFactory.getDefaultFactory();

            response.setContentType(text/html;charset=GB2312);

            pageContext = _jspxFactory.getPageContext(this, request, response,

                            , true, 8192, true);

 

            application = pageContext.getServletContext();

            config = pageContext.getServletConfig();

            session = pageContext.getSession();

            out = pageContext.getOut();

                //为了节省篇幅,我删除了解释器添加的注释

                out.write(\r\n);

//上一句是由于<%@ page language=java  contentType=text/html;charset=GB2312 %>后面的换行产生的

                out.write();

                out.write(\r\n\r\n\r\n\r\n);

                out.print( 输出 );

                out.write(\r\n\r\n\r\n\r\n);

        } catch (Throwable t) {

            if (out != null && out.getBufferSize() != 0)

                out.clearBuffer();

            if (pageContext != null) pageContext.handlePageException(t);

        } finally {

            if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);

        }

    }

}

从上面的代码中可以清晰的看到JSP内建的几个对象(out、request、response、session、pageContext、application、config、page)是怎么产生的,懂servlet的朋友一看就能明白。

下面重点理解一下out对象,它被声明为JspWriter类型,JspWriter是一个抽象类,在包javax.servlet.jsp中可以找到它的定义。

abstract public class javax.servlet.jsp.JspWriter extends java.io.Writer{

       final public static int NO_BUFFER = 0;

       final public static int DEFAULT_BUFFER = -1;

       final public static int UNBOUNDED_BUFFER = -2;

       protected int bufferSize;

       protected Boolean autoFlush;

       protected javax.servlet.jsp.JspWriter(int arg1, boolean arg2);

     

    abstract public void newLine() throws IOException ;

    abstract public void print(boolean arg0) throws IOException ;

    abstract public void print(char arg0) throws IOException ;

    abstract public void print(int arg0) throws IOException ;

    abstract public void print(long arg0) throws IOException ;

    abstract public void print(float arg0) throws IOException ;

    abstract public void print(double arg0) throws IOException ;

    abstract public void print(char[] arg0) throws IOException ;

    abstract public void print(String arg0) throws IOException ;

    abstract public void print(Object arg0) throws IOException ;

    abstract public void println() throws IOException ;

    abstract public void println(boolean arg0) throws IOException ;

    abstract public void println(char arg0) throws IOException ;

    abstract public void println(int arg0) throws IOException ;

    abstract public void println(long arg0) throws IOException ;

    abstract public void println(float arg0) throws IOException ;

    abstract public void println(double arg0) throws IOException ;

    abstract public void println(char[] arg0) throws IOException ;

    abstract public void println(String arg0) throws IOException ;

    abtract public void println(Object arg0) throws IOException ;

    abstract public void clear() throws IOException ;

    abstract public void clearBuffer() throws IOException ;

    abstract public void flush() throws IOException ;

    abstract public void close() throws IOException ;

    public int getBufferSize() ;

    abstract public int getRemaining() ;

    public boolean isAutoFlush() ;

}

我相信当我写到这里你可能已经知道我想怎么做了。是的,来个偷天换日,继承JspWriter类,然后实现其定义的虚函数,然后把out变量替换成你自己实现的类的实例就ok了。

2.实现替换

假设

<%@ page language=java  contentType=text/html;charset=GB2312 import=jwb.util.HtmlIntoFile,jwb.util.TempSinglet,java.io.File%><%

JspWriter out_bak = out;String arg1=argument1;String filePath = /cache/根据参数生成文件名_ + arg1 + .html;//首先判断文件是否已经存在,如果不存在则执行本页面,否则跳转到静态页面就OK了File f = new File(pageContext.getServletContext().getRealPath(filePath));if(f.exists()) { out_bak.clear(); pageContext.forward(filePath); System.out.println(直接转到静态页面); return;}out = new HtmlIntoFile(pageContext.getServletContext().getRealPath(filePath));out.write();

%><%= 看吧,这就是输出被重定向到文件的实现,很简单吧^_^%><%out.close();//关闭生成的静态文件out_bak.clear();pageContext.forward(filePath);

System.out.println(执行本页面后再转到静态页面);return;%>

3.更新问题

下面就讨论一下如何更新生成静态文件,其实从上面实现中你可以看到,很简单的就是将生成的静态文件删除即可,至于什么时候删除,要看你的需求了。我能想到的几种情况如下

    *

      当用来生成页面的数据更新时

    *

      如果不需要很提供时时的数据可以定时更新

    *

      永远不更新

*********************************************************************************************************

                                                        转帖完毕