eclipse: workspace出错导致无法启用的解决

 eclipse  eclipse: workspace出错导致无法启用的解决已关闭评论
3月 222016
 

启动eclipse选择workspace后, 启动失败,提示查看.log文件。

可以试验下面的方法

1. 可以试下这个方法:workspace\.metadata\.plugins\org.eclipse.core.resources\目录下有一个.snap文件,把它删除掉,顺利的话,eclipse就可以用该workspace启动了,启动后,把所有project给clean一下


2. 首先进入workspace的.metadata/.plugins/org.eclipse.core.resources/.projects文件夹中,你会发现一些项目的文件;
然后估计一下哪个项目出错(一般情况下是eclipse异常关闭时正在使用的项目),进入项目对应的文件;再后找到里面有个叫.SNAP的文件,把它删除掉。最后重新启动eclipse,问题应该会解决


Good Luck!

在eclipse中使用pydev插件进行远程调试python

 eclipse, python  在eclipse中使用pydev插件进行远程调试python已关闭评论
2月 172016
 

介绍下在eclipse中使用pydev插件进行远程调试,供参考。

先看下官网的资料,后面有测试总结:

Remote Debugger

In PyDev you can debug a remote program (a file that is not launched from within Eclipse).

The steps to debug an external program are:

  • Start the remote debugger server
  • Go to the debug perspective
  • Start the external program with the file ‘pydevd.py’ in its pythonpath
  • Call pydevd.settrace()

Let’s see a simple ‘step-by-step’ example on how this works:

1. Start the remote debugger server: To start the remote debugger server, you have to click the green button pointed by ‘1’ in the image below. After doing that, it will show a message in the console (indicated by ‘2’) to confirm that the server is listening for incoming connections.

Note: Those buttons should be present at the debug perspective and they can be enabled in other perspectives through Window > Customize perspective > Command groups availability > PyDev debug.

Image: Remote Debugger Server

2. Go to the debug perspective: This is needed because it has no actual ‘signal’ that it reached a breakpoint when doing remote debugging. So, if you already have it open, just cycle to it with Ctrl+F8. Otherwise, go to the menu: window > Open Perspective > Other > Debug.

Note that there should appear a process named ‘Debug Server’ in the debug view (see ‘1’ in the image below).

Image: Debug perspective

3. Make sure pydevd.py is in your pythonpath: This file is included in the org.python.pydev plugin. So, you’ll have to add it to the pythonpath. It’s exact location will depend upon the eclipse location and the plugin version, being something like:

eclipse/plugins/org.python.pydev_x.x.x/pysrc/pydevd.py

(so, the container folder must be in your pythonpath). If you choose to execute it from another machine, you need to copy all the files within that folder to the target machine in order to be able to debug it (if the target machine does not have the same paths as the client machine, the file pydevd_file_utils.py must be edited to properly translate the paths from one machine to the other – see comments on that file).

4. Call pydevd.settrace(): Now that the pydevd.py module is already on your pythonpath, you can use the template provided: ‘pydevd’ to make the call: import pydevd;pydevd.settrace(). When that call is reached, it will automatically suspend the execution and show the debugger.

Image: pydevd.settrace called

Important Notes

NOTE 1: the settrace() function can have an optional parameter to specify the host where the remote debugger is listening. E.g.:pydevd.settrace(‘10.0.0.1’)

NOTE 2: the settrace() function can have optional parameters to specify that all the messages printed to stdout or stderr should be passed to the server to show. E.g.: pydevd.settrace(stdoutToServer=True, stderrToServer=True)

NOTE 3: You can have the running program in one machine and PyDev on another machine, but if the paths are not exactly the same, some adjustments have to be done in the target machine:

Aside from passing the files in eclipse/plugins/org.python.pydev_x.x.x/pysrc to your target machine, the file pydevd_file_utils.py must be edited to make the path translations from the client machine to the server machine and vice-versa. See the comments on that file for detailed instructions on setting the path translations.

我在看完上面的资料后还是很疑惑,感觉没说清楚。 经过使用测试后总结下经验,使用中大家需注意以下四题:

1.  eclipse端是debug服务端 , 即端口的监听端, 也就是说远端要调试的python代码文件是作为客户端连接eclipse端的端口(如:默认端口 5678), 切记!!我在这里吃了大亏

2.  在eclipse插件plugins目录查找到pydevd.py文件后,将文件所在的整个个文件夹copy到需要调试的机器的python文件的site-packages目录下,并保证可以访问到pydevd.py(我使用了在site-packages目录下建立pysrc.pth文件指定路径方式),可参考文章最后的url。

3.  如果远程调试,一般python代码的路径在eclipse端与远程机器上的路径是不一样的,一定记住修改pydevd_file_utils.py中的PATHS_FROM_ECLIPSE_TO_PYTHON值,修改具体值可以看下文件中关于这个变量的注释,而且注释中还有举例说明。

4.  在需要调试的代码中使用下面代码:

        import pydevd
        pydevd.settrace(‘eclipse端服务器地址‘, port=端口5678, stdoutToServer=True, stderrToServer=True)

官网参考: http://www.pydev.org/manual_adv_remote_debugger.html

其它参考:http://blog.csdn.net/tantexian/article/details/47003385

eclipse无法启动的各种解决方法

 eclipse  eclipse无法启动的各种解决方法已关闭评论
2月 162016
 

当选择完workspace之后,eclipse开始加载启动,在这个阶段经常出现闪退出的情况,这主要有两个原因:

原因一、eclipse.ini的配置问题:

可能配置的内存太小,或者系统本身内存不够了,比如我的就配置成这样:

-Xms128m -Xmx512m -XX:PermSize=256m -XX:MaxPermSize=512m -Dorg.eclipse.swt.browser.DefaultType=mozilla

具体配置方法和参数说明网上很多,不再赘述。

 

原因二、之前错误的关闭,workspace的问题:

这个问题比较棘手,因为很难找到问题出再哪,可能之前的操作有误,可能某个插件BUG,等等。

最狠的解决方法是删除workspace/.metadata/目录,也就是把这个workspace从eclipse的记忆中删除,缺点是要重新加载每一个项目…

网上很流行的一个方法是:

$ rm YOUR_PROJECT_DIR/.metadata/.plugins/org.eclipse.core.resources/.snap

但是我没成功。

我用的这个方法成功了:

复制代码
0, 进入workspace/.metadata/.plugins/目录 1. Rename org.eclipse.core.resources to org.eclipse.core.resources_old. 2. Start eclipse 3. Close eclipse 4. Delete org.eclipse.core.resources 5. Rename org.eclipse.core.resources_old back to org.eclipse.core.resources 6. Star eclipse
复制代码

这个方法相对完美,不用重新加载任何项目,推荐!

转自:http://www.cnblogs.com/coding-way/archive/2012/10/17/2727481.html

MAT 之 Incoming and Outgoing References

 eclipse  MAT 之 Incoming and Outgoing References已关闭评论
3月 162015
 

虽然是英文,但对理解MAT有帮助,贴出来

Eclipse MAT: Understand Incoming and Outgoing References

In [1], we have shown how to use OQL to query String instances starting with a specified substring (i.e., our objects of interest) from a heap dump.[7,8] To determine who is creating these objects, or find out what the purpose of some structures are, an object’s incoming and outgoing references become handy.

In this article, we will examine the following topics:
  • What are incoming references or outgoing references of an object?

Then look at two topics related to incoming references:

  • Path To GC Roots
  • Immediate Dominators

Outgoing References

Using the following OQL statement, we have identified total 7 entries (see Figure above) as our objects of interest:

SELECT * FROM java.lang.String WHERE toString().startsWith(“http://xmlns.oracle.com/apps/fnd/applcore/log/service/types”)

After expanding the first entry, it shows two outgoing references:

  1. a reference to the Class instance for the String object
  2. a reference to an array of char values

Outgoing References show the actual contents of the instances, helping to find out their purpose. In our Stringinstance, it holds two references. The memory overhead of this String instance is shown in two values: [3]

  • Shallow Heap
  • Retained Heap
These sizes of String instances depends on the internal implementation of the JVM. Read [2,4] for more details.

Incoming References

To get incoming references of the first entry, choose List Objects with Incoming References from the context menu.



Now a tree structure is displayed, showing all instances with all incoming references (note the different icon highlighted in red). These references have kept the object alive and prevented it from being garbage collected.

Immediate Dominators

Similarly, from the context menu, you can display immediate dominators of the first entry (see Figure below). AnObject X is said to dominate an Object Y if every path from the GC Root to Y must pass through X. So, immediate dominators is a very effective way to find out who is keeping a set of objects alive. For example, the immediate dominators of our first entry (note that we have used “java.*|com.sun..*” as our filter) is:

  • oracle.j2ee.ws.server.deployment.WebServiceEndpoint



Path To GC Roots

From context menu, you can also show “Path to GC Roots” of the first entry (see Figure below). Path to GC Rootsshows the path to GC roots which should be found for a given object. As you can expect, its immediate dominatorsmust also be on this path. Note that, when you display Path to GC Roots, you can specify which fields of certain classes to be ignored when finding paths. For example, we have specified that paths through Weak or Soft Referencereferents to be excluded.

Live Data Set

Now we know

  • oracle.j2ee.ws.server.deployment.WebServiceEndpoint

is keeping our String instance alive. Instead of viewing Path to GC Roots, it is easier to see it the other way around. So, we have chosen to display the outgoing references of WebServiceEndpoint instance (see Figure below). As you can see, our String instance is displayed as the leaf node of the tree structure.

References

  1. Eclipse MAT: Querying Heap Objects Using OQL (Xml and More)
  2. Java memory usage of simple data structure
  3. Shallow vs. Retained Heap
  4. Create and Understand Java Heapdumps (Act 4)
  5. Diagnosing Java.lang.OutOfMemoryError (Xml and More)
  6. I Bet You Have a Memory Leak in Your Application by Nikita Salnikov-Tarnovski
    • Classloader leak is the most common leak in web applications
  7. How to analyze heap dumps
    • Leak can be induced
      • Per call (or a class of objects)
      • Per object 
  8. Diagnosing Heap Stress in HotSpot (Xml and More)

eclipse中调试 python代码时出现错误提示:“SyntaxError: Non-ASCII character 'xe6' in file…", 解决方法

 eclipse, python  eclipse中调试 python代码时出现错误提示:“SyntaxError: Non-ASCII character 'xe6' in file…", 解决方法已关闭评论
7月 312014
 

eclipse中调试 python代码时出现错误提示:“SyntaxError: Non-ASCII character ‘xe6’ in file…”, 解决方法如下:

在.py文件的最上面添加下面一行:

# -*- coding: utf-8 -*-


搞定!

Eclipse中10个最有用的快捷键组合

 eclipse  Eclipse中10个最有用的快捷键组合已关闭评论
5月 142014
 

Eclipse中10个最有用的快捷键组合 ,分享。

一个Eclipse骨灰级开发者总结了他认为最有用但又不太为人所知的快捷键组合。通过这些组合可以更加容易的浏览源代码,使得整体的开发效率和质量得到提升。

    1. ctrl+shift+r:打开资源

    这可能是所有快捷键组合中最省时间的了。这组快捷键可以让你打开你的工作区中任何一个文件,而你只需要按下文件名或mask名中的前几个字母,比如applic*.xml。美中不足的是这组快捷键并非在所有视图下都能用。


【转】eclipse快捷键 10个最有用的快捷键

2. ctrl+o:快速outline

    如果想要查看当前类的方法或某个特定方法,但又不想把代码拉上拉下,也不想使用查找功能的话,就用ctrl+o吧。它可以列出当前类中的所有方法及属性,你只需输入你想要查询的方法名,点击enter就能够直接跳转至你想去的位置。


【转】eclipse快捷键 10个最有用的快捷键

3. ctrl+e:快速转换编辑器

    这组快捷键将帮助你在打开的编辑器之间浏览。使用ctrl+page down或ctrl+page up可以浏览前后的选项卡,但是在很多文件打开的状态下,ctrl+e会更加有效率。


eclipse快捷键 10个最有用的快捷键

4. ctrl+2,L:为本地变量赋值

    开发过程中,我常常先编写方法,如Calendar.getInstance(),然后通过ctrl+2快捷键将方法的计算结果赋值于一个本地变量之上。 这样我节省了输入类名,变量名以及导入声明的时间。Ctrl+F的效果类似,不过效果是把方法的计算结果赋值于类中的域。

    5. alt+shift+r:重命名

    重命名属性及方法在几年前还是个很麻烦的事,需要大量使用搜索及替换,以至于代码变得零零散散的。今天的Java IDE提供源码处理功能,Eclipse也是一样。现在,变量和方法的重命名变得十分简单,你会习惯于在每次出现更好替代名称的时候都做一次重命名。要使 用这个功能,将鼠标移动至属性名或方法名上,按下alt+shift+r,输入新名称并点击回车。就此完成。如果你重命名的是类中的一个属性,你可以点击alt+shift+r两次,这会呼叫出源码处理对话框,可以实现get及set方法的自动重命名。

    6. alt+shift+l以及alt+shift+m:提取本地变量及方法

    源码处理还包括从大块的代码中提取变量和方法的功能。比如,要从一个string创建一个常量,那么就选定文本并按下alt+shift+l即可。如果同 一个string在同一类中的别处出现,它会被自动替换。方法提取也是个非常方便的功能。将大方法分解成较小的、充分定义的方法会极大的减少复杂度,并提 升代码的可测试性。

    7. shift+enter及ctrl+shift+enter

    Shift+enter在当前行之下创建一个空白行,与光标是否在行末无关。Ctrl+shift+enter则在当前行之前插入空白行。

    8. Alt+方向键

    这也是个节省时间的法宝。这个组合将当前行的内容往上或下移动。在try/catch部分,这个快捷方式尤其好使。

    9. ctrl+m

    大显示屏幕能够提高工作效率是大家都知道的。Ctrl+m是编辑器窗口最大化的快捷键。

    10. ctrl+.及ctrl+1:下一个错误及快速修改

    ctrl+.将光标移动至当前文件中的下一个报错处或警告处。这组快捷键我一般与ctrl+1一并使用,即修改建议的快捷键。新版Eclipse的修改建 议做的很不错,可以帮你解决很多问题,如方法中的缺失参数,throw/catch exception,未执行的方法等等。


eclipse快捷键 10个最有用的快捷键

更多快捷键组合可在Eclipse按下ctrl+shift+L查看。

转自:http://www.open-open.com/bbs/view/1320934157953

eclipse 远程调试 jetty/tomcat

 eclipse, MAVEN, tomcat  eclipse 远程调试 jetty/tomcat已关闭评论
3月 142014
 

A:

1.在eclipse的run configurations中创建一个maven build,选择好Maven工程,在Goals一栏中输入jetty:run。然后进入“jre”Tab,在vm arguments一栏中输入-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

2.打开debug configuration,创建一个remote java application,在host中输入服务器地址,一般就本机localhost。在port一栏中输入上面配置中端口号8000。这样,当服务器启动后,就可以进行远程debug了。这种debug方式的好外是可以在debug依赖的jar包,并在上面设置断点。(前提是你已经获得了jar包的源代码)

 

B:

如果是Tomcat,只需要在tomcat/bin/的catalina.bat文件的开头加入下面的设置即可:

SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000

然后在eclipse新建一个remote debug,端口填入8000即可。

eclipse 快捷键失效恢复

 eclipse  eclipse 快捷键失效恢复已关闭评论
12月 092013
 

可从以下3步检查恢复:

1. 系统设置中键盘中的快捷键是否有冲突,有冲突修改对应的键即可。

2. eclipse中菜单 window -> preferences, 点左侧general->keys检查对应的key是否有冲突

3.  在当前有问题的视图下, 点菜单 window-> reset perspective… , 弹出菜单后点是,恢复为默认快捷键。

看java代码利器 —— relo升级版 architexa

 eclipse, java  看java代码利器 —— relo升级版 architexa已关闭评论
10月 162013
 

Relo是一个帮助开发人员研究大型代码库的好工具,目前已更名为architexa,是个eclipse的插件, 用来看代码感觉非常棒,和大家分享下!

官网:

http://www.architexa.com/

使用文档:

http://www.architexa.com/user-guide/Documenting

 

Creating a Layered Diagram

Architexa lets you create Layered Diagrams easily. Diagrams can be created from multiple places such as the package explorer, can be viewed in an Eclipse view or an editor, and can be updated easily by exploring around or just linking them to editor selections.

Starting from the package explorer

  1. Right click on a project or package.
  2. Select 'Open in Diagram' -> 'Layered Diagram'
  3. The diagram will display the package or project and automatically open it to show its contents.
LayerFromPckgExplorer.png

Creating a blank diagram in a new editor

  1. In the toolbar, click the small drop down arrow on the right side 'Open a new diagram editor' New editor.png button.
  2. Select 'New Layered Diagram'
  3. Once you have a new editor drag in packages or classes from the package explorer to see how they interact.

Creating a blank diagram in a view

  1. Go to "Window > Show View" and select the option "Other…"
  2. Select "Layered Diagram" in the "Architexa" folder.
  3. You will now have a Layered diagram in a view which you can move, resize, or drag to a separate screen.
  4. Once you have a new view drag in packages or classes from the package explorer to see how they interact.

Using a linked view/editor to create a diagram

Follow the directions starting form step 2 here: Document while you work by creating a diagram in the background

 

More

For more help on opening diagrams see Opening Diagrams

How Layered Diagrams Work

Layered diagrams automatically organize your code into a hierarchy of layers based on the package structure.

  • Items are organized in layers, with items towards the top of the diagram depend on those below. (When dependency cycles are found, Architexa uses sophisticated analyses to make a best guess).
  • The size of packages indicates how many items they contain relative to other packages.
  • The size of dependency arrows shows the strength of the dependency. If two packages have many more dependencies between them than other packages their connection will be much thicker.
  • Items are nested based on directory/package nesting with each level of depth being represented by a different color.
  • Mousing over a package or class highlights which items depend on or are depended on by others.

    • Items highlighted in white depend on the item being moused over
    • The moused over item depends on any items with a dark gray highlighting.
    • Items with the same light gray color as the moused over item indicate that there is a cycle here.

 

Layered-explanation.png

Exploring a Layered Diagram

Layered diagrams are great to quickly understand the high level concepts of a codebase. It quickly provide you keen insights in your code architecture, package dependencies and obvious design patterns. Following are simple things you can do to make your diagram work wether your motive is to understand the code or document it for others.

Opening a package

To open a package and view its contents simply double click on it. For packages containing 20+ classes this may take a few moments.

Moving and Layering

  • You can drag packages and classes to new places within the diagram.
  • Dragging an item onto a blank spot in a layer will add it to that location in the layer, even if it is between two items
  • Dragging it on top of a package will open the package and add it inside
  • Dragging it between two layers will add it to a new layer in that location
  • Items dragged to a different depth within the tree structure will show the full path in their name

    • Clicking the parts of this name will add parent folders
  • Moving items will not affect the organization of your actual code.

Adding a member

In the bottom right of any class or package that is not currently showing all its children, is a button labeled 'Members' Clicking this button will allow you to add any un-shown children to the diagram individually.

LayerAddMembers.png

Adding a dependent / dependee

  1. Click on a class or package
  2. If there are any dependencies to other items an up / down arrow will show above/below the selected item
  3. Clicking an arrow will allow you to show any items not already in the diagram that depend on (up) or are depended on (down)
LayerNavAid.png

Focusing on a specific package

If you have explored a diagram and now wish to focus your attention on a specific portion you can use the Focus command

  1. Right click on the package you would like to focus on
  2. Select 'Focus' from the context menu
  3. This will remove everything else in the diagram and open the package if it is not already open
LayerFocus.png

Breaking a package

If there are items in a package that you wish to see in relation to the parent package you will need to use the 'Break' command.

  1. Right click on the package you would like to focus on
  2. Select 'Break' from the context menu
  3. This will remove the selected package but leave its children as children of the parent package.
  4. The images below show the animation package before and after the break

Animation package before break

Animation package after break

 

Deleting an element

To delete any package, class, or layer simply click on it to select it and hit the delete key on your keyboard. You can also delete by right clicking on the selected item and clicking on the delete option in the context menu.

Changing how dependency arrows are shown

If you would like to see all the dependency arrows concurrently,

  • Right click and select 'Downward Arrows' -> 'Show Always'

If you would like to prevent dependency arrows from showing on mouseover,

  • Right click and select 'Downward Arrows' -> 'Show Never'

If you would like to see cycles,

  • Right click and select 'Upward Arrows' -> 'Show Always'
LayerArrowDir.png

Relayering

If you have moved elements in a layered diagram and would like the Architexa algorithm to re-adjust a specific package simply right click on the parent package and select 'Re-Layer'. This would re-order the package to the original layout.

Documenting with a Layered Diagram

Layered diagrams can be tricky to document with since they are so interactive. We have added a couple of nifty features to make this aspect easier.

  • If you are creating a diagram to show the dependencies of a specific class or package, share the diagram while the class or package is selected and all shown dependency arrows will be shown in the created diagram.
  • You can also select multiple items by holding ctrl and clicking on them. This will allow you to share a diagram and show dependencies of more than one item.
  • Selecting an open package will show all the dependencies going into and out of that package. This is a good way to give a better understanding of what the contents of a package are used for.
  • You can choose to show a single connection always:

    1. Click on a dependency between two items.
    2. Click the small 'Pin' button to save the connection.
    3. The connection will now show as a dotted/dashed line and be visible no matter which items you mouse over.

Layered Diagram Tasks

 

Creating a Class Diagram

Architexa lets you create Class Diagrams easily. Diagrams can be created from multiple places such as the package explorer, from the Java editor or can be viewed in an Eclipse view. The diagrams can be updated easily and are good for documenting code.

Starting from the code

  1. Right click inside the code. (Click on the method name in the class to display a method)
  2. Select 'Open in Diagram' -> 'Class Diagram' to display in the diagram.
ClassFromCode.png

Starting from the package explorer

  1. Right click on one or more classes/methods or a single package.
  2. Select 'Open in Diagram' -> 'Class Diagram'
  3. If you selected a package the diagram will show any classes within that package and automatically add any inheritance relationships between them.
  4. If you selected a class(s)/method(s) the diagram will show it with its appropriate parents
ClassFromPckgExplorer.png

Creating a blank diagram in a new editor

  1. In the toolbar, click the small drop down arrow on the right side 'Open a new diagram editor' New editor.png button.
  2. Select 'New Class Diagram'
  3. Once you have a new editor drag in packages, classes, or methods/fields from the package explorer to see how they interact.

Creating a blank diagram in a view

  1. Go to "Window > Show View" and select the option "Other…"
  2. Select "Class Diagram" in the "Architexa" folder.
  3. You will now have a class diagram in a view which you can move, resize, or drag to a separate screen.
  4. Once you have a new view drag in packages, classes, or methods/fields from the package explorer to see how they interact.

Using a linked view/editor to create a diagram

Follow the directions starting form step 2 here: Document while you work by creating a diagram in the background

More

For more help on opening diagrams see Opening Diagrams

Exploring a Class Diagram

Class diagrams are best for showing how the classes of your project interact. You can easily see both inheritance relationships and method calls at the same time.

Moving items

You can move any element in a class diagram by clicking it and dragging it to where you want it. Each type of item (package, class, field/method) can be moved in a unique way.

  • Moving a package moves all its children as well.
  • Moving a class outside of its package will cause the package to expand in order to accommodate it. Similarly moving classes in a package closer together will cause the package to shrink around them.
  • fields, methods, and nested classes can not be moved outside their parent class. However their order within the class can be changed by dragging them.

Deleting items

To delete a package, class, or method/field simply click on it and then click the 'X' button in the top right or hit the delete key on the keyboard. Caution: deleting an element will also delete it's children. (Deleting does not remove the actual code, but just removes the item from the current diagram)

Adding members

  1. Selecting a class or method will cause a 'Members' button to appear in the bottom right corner of the selected element. You can click this button to see a list of items that can be added; classes for packages, and members, fields, and nested classes for classes.
  2. Selecting an item in the list will add it to the diagram and also add appropriate relationships
ClassAddMembers.png

Adding hierarchy relationships

Selecting a class that extends another class or implements an interface will result in an up arrow button showing at the top of the class. Similarly if an interface or class is selected within your diagram, you will see a downward arrow button.

  1. Select a class or interface
  2. Click an upward or downward button
  3. Select an item from the list to add to the diagram or add all the items by clicking 'Show All'
ClassAddHeir.png

Adding caller/callee

  1. Select a method in your diagram. If one does not yet exist you can add it by dragging it from the package explorer or using the 'Members' button
  2. If this method is called by other methods in your code you will see a left pointing arrow button on the left side.
  3. If this method calls other methods in your code you will see a right pointing arrow button on the right side.
  4. Clicking one of these buttons will allow you to add calling / called methods individually.
  5. You can also click 'Show All' to show all methods calling/called
ClassCallersCallees.png

Advanced Commands

We provide some built in advanced commands to make some common tasks easier. To access advanced commands, right click on an item in the diagram and select the appropriate command from the context menu.

  • Hide Package removes the selected package
  • Show Supertype Hierarchy will add all classes/interfaces that this class extends/implements to the diagram, up to the Object Level.
  • Show Subtype Hierarchy will add all classes that are extending this class and any classes extending them.
  • Show Referencing Types + Methods will add any methods or fields that contain references to the selected class
  • Show Containing Package will add the parent package back if it has been removed with the 'Hide Package' command

Documenting with a Class Diagram

A class diagram is a versatile tool for documenting your codebase. For best practices see:

Class Diagram Tasks

 

Creating a Sequence Diagram

Along with Class and Layered diagrams Architexa also lets you easily create Sequence Diagrams. Diagrams can be created from multiple places such as the package explorer, from the Java editor or can be viewed in an Eclipse view. The diagrams can be updated easily and are good for understanding the details of your code and document complex parts.

Starting from the code

  1. Right click inside the code. (Click on the method name in the class to display a method)
  2. Select 'Open in Diagram' -> 'Sequence Diagram' to display in the diagram.
SeqFromCode.png

Starting from the package explorer

  1. Right click on a class or method.
  2. Select 'Open in Diagram' -> 'Sequence Diagram' to display the class in the diagram.
SeqFromPckgExplorer.png

Creating a blank diagram in a new editor

  1. In the toolbar, click the small drop down arrow on the right side 'Open a new diagram editor' New editor.png button.
  2. Select 'New Sequence Diagram'.
  3. Once you have a new editor drag in classes or methods from the package explorer to see how they interact.

Creating a blank diagram in a view

  1. Go to "Window > Show View" and select the option "Other…"
  2. Select "Sequence Diagram" in the "Architexa" folder.
  3. You will now have a Sequence diagram in a view which you can move, resize, or drag to a separate screen.
  4. Once you have a new view drag in packages or classes from the package explorer to see how they interact.

Using a linked view/editor to create a diagram

Follow the directions starting from step 2 here: Document while you work by creating a diagram in the background

More

For more help on opening diagrams see Opening Diagrams

Exploring and Building a Sequence Diagram

Sequence diagrams are great to understand nitty gritty details of your code and especially beneficial when looking at complex parts of your code. They let you add specific details to your diagrams like method calls, overrides and also let you easily remove items which are not relevant.

Adding Methods

In order to add methods to a sequence diagram containing the parent class, follow these steps:

  1. Select a class shown in the diagram.
  2. A button will show up below the class name showing the number of members(Methods/Fields/Inner classes) present and not already added to the diagram.
  3. Click on the button and select the method to add.
SeqAddMembers.png

Adding Calls a Method Makes

To add calls to a diagram containing a method follow these steps:

  1. Select a method.
  2. If a call is made from the method which is already not present in the diagram a 'Calls made' arrow (top right corner pointing outward) will show up.
  3. Click on the arrow and add the call you want to the diagram from the list shown.
SeqAddCalls.png

Adding Callers to a Method

  1. Select a method.
  2. If a call is made to this method which is already not present in the diagram a 'Calls made to' arrow (top left corner pointing inward) will show up.
  3. Click on the arrow and add the call you want to the diagram from the list shown.
SeqBackCalls.png

Adding Override/Overridden Methods

If this method overrides a method in a different class, take the following steps to add the parent class and it's method.

  1. Select a method.
  2. If a overriding/implement method is present which is not present in the diagram an 'Overriden By' arrow (bottom left corner pointing upward) will show up.
  3. If this method is an override to another method not present in the diagram an 'Overrides' arrow (top right corner pointing upward) will show up.
  4. Click on the arrow and add the call you want to the diagram from the list shown.

Show Overrides

Show overriden

Documenting with Sequence diagrams

Sequence diagrams are a good way to document complicated control flows in your codebase. Read more here.

Sequence Diagrams Tasks

Grouping of Classes

Sometimes we might need to group intermediary calls in a diagram. This can be done by simply dragging a class(es) and dropping over another class. These classes will then be grouped together and result in the grouped class(color changed to brown). You can ungroup by right clicking and selecting ungroup from the menu or by simply double clicking on the grouped class.

Ease Code Reviews

Tasks/Have easier code reviews by understanding changes with diagrams

Simplify Debugging

Tasks/Debug easily by using diagrams to see control flow

Analyze Logic

Tasks/Analyze logic (and ensure all cases are handled effectively)

Eclipse升级后导入老版本插件

 eclipse  Eclipse升级后导入老版本插件已关闭评论
9月 182013
 
  1. 启动 eclipse.
  2. 菜单 File => import … => Install => From existing Installation, 点确定, 弹出对话框, 浏览选择老版本eclipse的目录, 就会列出所有曾经安装在原eclipse上可以导入的插件.
  3. 选择好要导入的插件, 点击 Finish, 即可.
  4. 导入完成后, 按提示重启 eclipse, 成功.

在eclipse远程调试jetty(maven构建)

 eclipse, MAVEN  在eclipse远程调试jetty(maven构建)已关闭评论
9月 042013
 

1.在eclipse的run configurations中创建一个maven build,选择好Maven工程,在Goals一栏中输入jetty:run。然后进入“jre”Tab,在vm arguments一栏中输入-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

2.打开debug configuration,创建一个remote java application,在host中输入服务器地址,一般就本机localhost。在port一栏中输入上面配置中端口号8000。这样,当服务器启动后,就可以进行远程debug了。这种debug方式的好外是可以在debug依赖的jar包,并在上面设置断点。(前提是你已经获得了jar包的源代码)

 

如果是Tomcat,只需要在tomcat/bin/的catalina.bat文件的开头加入下面的设置即可:

SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000

然后在eclipse新建一个remote debug,端口填入8000即可。

 

转自: http://blog.csdn.net/bluishglc/article/details/5824812

使用Eclipse构建Maven的SpringMVC项目

 eclipse, MAVEN  使用Eclipse构建Maven的SpringMVC项目已关闭评论
8月 302013
 

首先Eclipse需要安装Maven的插件,地址:http://m2eclipse.sonatype.org/sites/m2e。

        用MyEclipse安装Maven插件,建出的Maven项目有些问题。一是,发布tomcat的时候resources总是不会被发布到tomcat下;二是,把WEB-INF下的classes改到target下的classes,但是不知道为什么MyEclipse要么仍然在WEB-INF下生成class。要么真不在WEB-INF生成classes了但是发布tomcat的时候,class文件一个都不会给你发布过去,超级郁闷。但是使用Eclipse构建Maven项目后,使用MyEclipse打开就没问题了。

        用maven的好处:我感觉最主要就是自动下载jar包和它所依赖的包,这样可以保证了多人开发时jar版本不同的问题。再就是文件结构清晰,java文件,资源文件,测试文件都分的很清楚。

        将介绍两种方法:一,直接建立Maven项目方法;二、建立Dynamic Web project转成Maven项目方法。

一、直接建立Maven项目方法

1、建立Maven项目

        接下来使用Eclipse的maven构建一个web项目,以构建SpringMVC项目为例:

1.1 选择建立Maven Project

选择File -> New -> Other,在New窗口中选择 Maven -> Maven Project。点击newxt。


 

 

1.2 选择项目路径

Use default Workspace location默认工作空间。


 

 

1.3 选择项目类型

在Artifact Id中选择maven-archetype-webapp


 

 

1.4 输入Group ID和 Artifact ID,以及Package

Group ID一般写大项目名称。Artifact ID是子项目名称。

例如Spring的web包,Group ID:org.springframework,artifactId:spring-web。

Package是默认给你建一个包,不写也可以。


 

 

1.5 刚建立好后的文件结构如下图


 

如果这里显示的内容多,一般是Filters设置的问题。或perspective为JavaEE模式,改成Java模式就可以了。

 

 

2、配置Maven项目

接下来就需要更改好多配置了。

 

2.1 添加Source文件夹

接下来需要添加src/main/java,src/test/java ,src/test/resources三个文件夹。右键项目根目录点击New -> Source Folder,

建出这三个文件夹。注意不是建普通的Folder,而是Source Folder。



 

 

2.2 更改class路径

右键项目,Java Build Path -> Source

下面应该有4个文件夹。src/main/java,src/main/resources,src/test/java ,src/test/resources。

 

双击每个文件夹的Output folder,选择路径。

src/main/java,src/main/resources,选择target/classes;

src/test/java ,src/test/resources, 选择target/test-classes;

 

选上Allow output folders for source folders.

 

 

在此处还要更改:

更改文件夹显示的顺序:点击Order and Export。

更改JDK版本:在Libraries双击JRE System Library,要1.6版本。


 

2.3 把项目变成Dynamic Web项目

 

2.3.1 右键项目,选择Project Facets,点击Convert to faceted from


 

2.3.2 配置Project Facets

 

更改Dynamic Web Module的Version为2.5。(3.0为Java7的)。

如果提示错误,可能需要在Java Compiler设置Compiler compliance level 为1.6。或者需要在此窗口的Java的Version改成1.6。


 

 

2.3.3 配置 Modify Faceted Project

点击Further configuration available…,弹出Modify Faceted Project窗口

此处是设置web.xml文件的路径,我们输入src/main/webapp。

Generate web.xml deployment descriptor自动生成web.xml文件,可选可不选。

 

 

2.4 设置部署程序集(Web Deployment Assembly)

 

上面步骤设置完成后,点击OK,Properties窗口会关闭,在右键项目打开此窗口。在左侧列表中会出现一个Deployment Assembly,点击进去后,如下图:


 

 

此处列表是,部署项目时,文件发布的路径。

1,我们删除test的两项,因为test是测试使用,并不需要部署。

2,设置将Maven的jar包发布到lib下。

Add -> Java Build Path Entries -> Maven Dependencies -> Finish

设置完成效果图


 

 

 

 

 

3、向maven项目中添加jar包

maven可以管理项目依赖的jar包,通过groupID、artifactId以及版本号可以唯一确定一个jar包。这样可以防止老式Web项目中WEB-INF/lib下jar包不一致的问题。并且maven还会自动下载添加进的jar包所依赖的jar包。

 

3.1 在pom.xml中添加所需要的jar包

使用Maven POM editor打开项目中的pom.xml文件,选择Dependencies,在Dependencies栏目点击Add进行,首先弹出一个搜索按钮,例如输入spring-web,就会自动搜索关于spring-web相关的jar包,我们选择3.0.5版本的spring。将spring包全部添加进来。需要添加的其他jar包有:junit、jstl。或者点击pom.xml直接编辑pom.xml文件。这样可以直接copy过来dependencies内容。


 

 

3.2设置jar包的scope

 

当添加进入一个jar包后,有一些属性需要设置,最重要的就是scope,它有以下几种取值:

1.         compile,缺省值,适用于所有阶段,会随着项目一起发布。

2.         provided,类似compile,期望JDK、容器或使用者会提供这个依赖。如servlet.jar。

3.         runtime,只在运行时使用,如JDBC驱动,适用运行和测试阶段。

4.         test,只在测试时使用,用于编译和运行测试代码。不会随项目发布。

5.         system,类似provided,需要显式提供包含依赖的jar,Maven不会在 Repository中查找它。

 

 

通常SpringMVC项目所需要配置scope的jar包如下图:


 

有的时候发现servlet-api还是被打包到lib下面了,此时肯定会报错。就需要把maven插件中的WTP也安装一下。

Eclipse在线安装路径:http://m2eclipse.sonatype.org/sites/m2e-extras。选择for Eclipse WTP。


 

 

 

4、构建SpringMVC框架

 

4.1 编辑web.xml文件

 

需要添加log4j,字符过滤,Spring 的dispatcher等。

webx.xml代码如下:

 

Xml代码  收藏代码

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"   
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.                              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
  6.          version="2.5" >  
  7.       
  8.     <!– 区分项目名称,防止默认重名 –>  
  9.     <context-param>  
  10.         <param-name>webAppRootKey</param-name>  
  11.         <param-value>maven.example.root</param-value>  
  12.     </context-param>  
  13.   
  14.     <!– Spring的log4j监听器 –>  
  15.     <listener>  
  16.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  17.     </listener>  
  18.   
  19.     <!– 字符集 过滤器  –>  
  20.     <filter>  
  21.         <filter-name>CharacterEncodingFilter</filter-name>  
  22.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  23.         <init-param>  
  24.             <param-name>encoding</param-name>  
  25.             <param-value>UTF-8</param-value>  
  26.         </init-param>  
  27.         <init-param>  
  28.             <param-name>forceEncoding</param-name>  
  29.             <param-value>true</param-value>  
  30.         </init-param>  
  31.     </filter>  
  32.     <filter-mapping>  
  33.         <filter-name>CharacterEncodingFilter</filter-name>  
  34.         <url-pattern>/*</url-pattern>  
  35.     </filter-mapping>  
  36.   
  37.     <!– Spring view分发器 –>  
  38.     <servlet>  
  39.         <servlet-name>dispatcher</servlet-name>  
  40.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  41.         <init-param>  
  42.             <param-name>contextConfigLocation</param-name>  
  43.             <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>  
  44.         </init-param>  
  45.         <load-on-startup>1</load-on-startup>  
  46.     </servlet>  
  47.     <servlet-mapping>  
  48.         <servlet-name>dispatcher</servlet-name>  
  49.         <url-pattern>*.do</url-pattern>  
  50.     </servlet-mapping>  
  51.   
  52. </web-app>  

 

 

4.2 编写Spring配置文件dispatcher-servlet.xml

 

如要添加MVC驱动、注解检测、视图解析等。dispatcher-servlet.xml代码如下:

 

Xml代码  收藏代码

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.        xmlns:aop="http://www.springframework.org/schema/aop"   
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        xmlns:mvc="http://www.springframework.org/schema/mvc"   
  6.        xmlns:tx="http://www.springframework.org/schema/tx"   
  7.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  8.        xsi:schemaLocation="http://www.springframework.org/schema/aop   
  9.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  10.         http://www.springframework.org/schema/beans   
  11.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  12.         http://www.springframework.org/schema/context   
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.         http://www.springframework.org/schema/mvc   
  15.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  16.         http://www.springframework.org/schema/tx   
  17.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  18.   
  19.     <mvc:annotation-driven />  
  20.     <context:component-scan base-package="liming.maven.example" />  
  21.   
  22.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  23.         <property name="prefix" value="/WEB-INF/views/" />  
  24.         <property name="suffix" value=".jsp" />  
  25.     </bean>  
  26.   
  27. </beans>  

 

 

 

 

4.3 编写一个Controller层测试类

 

编写一个SpringMVC的Controller层测试类。此类只有一个方法做地址映射,并向页面传递一个数据。代码如下:

 

Java代码  收藏代码

  1. package liming.maven.example.view;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.ui.Model;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6.   
  7. @Controller  
  8. public class GeneralController {  
  9.   
  10.     @RequestMapping(value="index.do")  
  11.     public void index_jsp(Model model){  
  12.         model.addAttribute("liming", "黎明你好");  
  13.         System.out.println("index.jsp");  
  14.     }  
  15. }  

 

 

 

 

4.4 编写index.jsp页面

首先在src/main/webapp/WEB-INF下建文件夹views。此处和dispatcher-servlet.xml配置文件中的prefix属性路径要一样。

在views下建index.jsp文件

我们使用jstl获取Controlleradd的数据。

Jsp页面代码如下:

 

Html代码  收藏代码

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5.     <head>  
  6.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7.         <title>Insert title here</title>  
  8.     </head>  
  9.       
  10.     <body>  
  11.         <c:out value="${liming}"></c:out>  
  12.     </body>  
  13. </html>  

 

 

 

 

5,发布到tomcat

这个就没啥说的了。

Eclipse下Tomcat常用设置:http://limingnihao.iteye.com/admin/blogs/825394

 

 

6,测试

访问地址:http://localhost:8080/liming.maven.example/index.do

访问的结果来个截图:


 

 

二、建立Dynamic Web project转成Maven项目方法

7、第二种方法DynamicWeb项目转成Mavan

7.1 新建Dynamic Web Project

依次选择选择File -> New -> Other。在New窗口中选择Web下的Dynamic Web Project。点击next。


 

7.2 配置项目信息

7.2.1 输入项目信息

首先输入项目名称。

Target runtime 一般选择使用什么容器,tomcat之类的。可以先不选。

Dynamic web module version。就是版本号。选择2.5(3.0是Java7的)。

Configuration 是选择容易的配置。如果Target runtime选择了tomcat。这里对应也是选择tomcat。

Next。


7.2.2 配置source和output的folder

此窗口输入需要建立的Source folders。和默认output folder。

这个我们的Source folders等建立完项目后在添加。

output folder可以顺手改成target/classes。


 

7.2.3 配置web.xml文件的路径


 

 

7.3 转成maven项目

Dynamic web项目建立完后,首先将其转成maven项目。

右键此项目,选择maven -> Enable Dependency Management。弹出的窗口,直接finish就可以了。


 

7.4 其他配置

接下来的配置工作就和前面的基本一样了。

请参考上面。

2.1添加Source文件夹

2.2更改class路径。

2.3.3 配置 Modify Faceted Project

2.4 设置部署程序集(Web Deployment Assembly)

 

接着就是构建SpringMVC框架,发布到tomcat,测试。

 

转自:http://limingnihao.iteye.com/blog/830409

 Posted by at 下午6:26  Tagged with:

eclipse 远程调试tomcat项目

 eclipse, java, tomcat  eclipse 远程调试tomcat项目已关闭评论
8月 202013
 

转自:http://fly-hyp.iteye.com/blog/909173

第一步、配置tomcat 

一、在windows系统中: 

打开%CATALINE_HOME%/bin下的文件catalina.bat,加入下面这行: 

set CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8787 



其中address=8787是没被使用的端口号。连接方式有两种,为dt_shmem和dt_socket,分别表示本机调试和远程调试。 



二、在非windows系统中: 

还需要把% CATALINE_HOME %/bin/startup.sh中的最后一行exec "$PRGDIR"/"$EXECUTABLE" start "[email protected]" 中的start改成jpda start。由于默认的端口是8000,所以如果8000端口已有他用的话,还需在catalina.sh文件中设置:JPDA_ADDRESS=8787。 

输入命令startup.sh或者catalina.sh jpda start就可启动tomcat。 

 

第二步、配置eclipse 

在Eclipse中选择RunDebug,在弹出的对话框中右击Remote Java Application新建一个远程调试项,如下如所示: 

在 “Name”输入框中输入远程调试的名称,

在“Project”中选择要调试的项目,

选择Connect Type :Standard (socket attach)

在“Host”中输入需要远程调试项目的IP,也就是tomcat所在的IP,在“Port”中输入设置的端口号,比如上面设置的8787,点击“Apply”即可。 

WebSocket开发实践(eclipse + tomcat7)

 eclipse, tomcat  WebSocket开发实践(eclipse + tomcat7)已关闭评论
8月 162013
 

转自:http://express.ruanko.com/ruanko-express_56/tech-overnight2.html

本文演示如何使用Eclipse和Tomcat开发一个简单的WebSocket聊天室程序。

一、开发环境:

  1. JDK1.6
  2. Eclipse Java EE IDE for Web Developers,本文使用的是:Indigo Release。
  3. Tomcat 7.0.27开始支持WebSocket服务,本文使用的是:Tomcat 7.0.34。

二、配置Eclipse中的Tomcat7服务器运行环境

如果在此之前已经进行过服务器的配置,则可以跳过此步骤。

1.在菜单中选择:Window→Preferences→Server→Runtime Environment。

2.点击Add新增Tomcat7运行环境

3.选择Tomcat7的安装路径

4.新建一个Tomcat7服务器

在菜单中选择New→Other→Server→Server,在新建服务器窗口中填写服务器名称,并指定服务器运行环境。

三、创建Web项目

1.在菜单中选择File→New→Project在新建项目向导中选择Dynamic Web Project。

2.输入项目名称,例如:webchat,在Target runtime中选择之前所配置的Tomcat7运行环境。该步骤之后的源码路径设置和web模块设置都可以使用默认设置,直接点击“Finish”即可。

四、编写项目代码

项目创建成功后,首先生成servlet类,具体操作方法如下:

1.在项目上点击右键,在快捷菜单中选择New→Servlet。

2.填写servlet的所在的包和类名,需要注意的是,在Supperclass中需要选择org.apache.catalina.websocket.WebSocketServlet作为servlet的父类。

3.点击“Next”之后,Servlet创建向导会提示该Servlet中需要包含哪些方法,这里可以去掉默认方法的复选框,在WebSocketServlet中不需要实现doGet和doPost方法。

WebSocketServlet代码清单:

package websocket.chat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

@WebServlet("/ChatWebSocketServlet")
public class ChatWebSocketServlet extends WebSocketServlet {
    private static final long serialVersionUID = 1L;
    private static final String GUEST_PREFIX = "Guest";
    //用于自动生成连接ID
    private final AtomicInteger connectionIds = new AtomicInteger(0);
    //用于保存所有连接Inbound的集合
    private final Set<ChatMessageInbound> connections =
            new CopyOnWriteArraySet<ChatMessageInbound>();
    //生成新的连接Inbound,WebSocketServlet必须实现该方法
    @Override
    protected StreamInbound createWebSocketInbound(String subProtocol,
            HttpServletRequest request) {
        return new ChatMessageInbound(connectionIds.incrementAndGet());
    }
    //聊天消息处理类
    private final class ChatMessageInbound extends MessageInbound {
        private final String nickname;
        private ChatMessageInbound(int id) {
            this.nickname = GUEST_PREFIX + id;
        }
        //创建新的连接时触发
        @Override
        protected void onOpen(WsOutbound outbound) {
            connections.add(this);
            String message = String.format("* %s %s",
                    nickname, "has joined.");
            broadcast(message);
        }
        //关闭连接时触发
        @Override
        protected void onClose(int status) {
            connections.remove(this);
            String message = String.format("* %s %s",
                    nickname, "has disconnected.");
            broadcast(message);
        }
        //发送二进制消息时触发
        @Override
        protected void onBinaryMessage(ByteBuffer message) throws IOException {
            throw new UnsupportedOperationException(
                    "Binary message not supported.");
        }
        //发送文本消息时触发
        @Override
        protected void onTextMessage(CharBuffer message) throws IOException {
            // Never trust the client
            String filteredMessage = String.format("%s: %s",
                    nickname, message.toString());
            broadcast(filteredMessage);
        }
        //该方法向所有活动连接发送文本信息
        private void broadcast(String message) {
            for (ChatMessageInbound connection : connections) {
                try {
                    CharBuffer buffer = CharBuffer.wrap(message);
                    connection.getWsOutbound().writeTextMessage(buffer);
                } catch (IOException ignore) {
                }
            }
        }
    }
}

在WebContent中新建一个html页面,如:chat.html,页面代码清单:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
    <style type="text/css">
        input#chat {
            width: 410px
        }
        #console-container {
            width: 400px;
        }
        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }
        #console p {
            padding: 0;
            margin: 0;
        }
    </style>
    <script type="text/javascript">
        var Chat = {};
        Chat.socket = null;
        Chat.connect = (function(host) {
            if ('WebSocket' in window) {
                Chat.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
                Chat.socket = new MozWebSocket(host);
            } else {
                Console.log('Error: WebSocket is not supported by this browser.');
                return;
            }
			//建立连接触发事件
            Chat.socket.onopen = function () {
                Console.log('Info: WebSocket connection opened.');
                document.getElementById('chat').onkeydown = function(event) {
                    if (event.keyCode == 13) {
                        Chat.sendMessage();
                    }
                };
            };
			//关闭连接触发事件
            Chat.socket.onclose = function () {
                document.getElementById('chat').onkeydown = null;
                Console.log('Info: WebSocket closed.');
            };
			//接收消息触发事件
            Chat.socket.onmessage = function (message) {
                Console.log(message.data);
            };
        });
		//初始化聊天对象方法,注意URL中的项目名称和Servlet名称
        Chat.initialize = function() {
            if (window.location.protocol == 'http:') {
                Chat.connect('ws://' + window.location.host + '/webchat/ChatWebSocketServlet');
            } else {
                Chat.connect('wss://' + window.location.host + '/webchat/ChatWebSocketServlet');
            }
        };
		//发送聊天信息方法
        Chat.sendMessage = (function() {
            var message = document.getElementById('chat').value;
            if (message != '') {
                Chat.socket.send(message);
                document.getElementById('chat').value = '';
            }
        });
        var Console = {};
		//显示消息记录
        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });
        Chat.initialize();
    </script>
</head>
<body>
<div>
    <p>
        <input type="text" placeholder="type and press enter to chat" id="chat">
    </p>
    <div id="console-container">
        <div id="console"></div>
    </div>
</div>
</body>
</html>

代码完成后进行编译并部署到Tomcat7服务器:

启动服务后,打开支持HTML5的浏览器,如Chrome,Firefox(版本6以上)等,输入项目的访问地址:http://localhost:8080/webchat/chat.html。

连接成功时,能够看到页面输出的消息:Info: WebSocket connection opened.以及服务器发送的欢迎词:* Guest1 has joined.接下来可以在其他窗口中打开相同的链接,在其中一个窗口中的输入框内输入消息,按回车键后,其他所有窗口中都会看到从这个窗口发送的消息。一个简单的Web聊天室功能就完成了。

MyEclipse下开发WebSocket应用的注意事项:

由于MyEclipse下的默认部署方式与Eclipse有所区别,并且较低版本的MyEclipse不支持Tomcat7环境下的开发,因此,需要手动将Tomcat7的服务器运行环境添加到项目的构建路径中。

  1. 在项目上点击右键,选择:Build Path→Configure Build Path;
  2. 点击Add Library→Server Runtime;
  3. 选择之前配置好的Tomcat7运行时环境。

但是在MyEclipse的默认部署方式下,部署时会将Tomcat7中的jar包全部部署到WEB-INF/lib文件夹下,这样的话会与Tomcat7/lib中的包发生冲突,因此,还需要配置服务器的部署策略:

  1. 在项目上点击右键,选择Properties;
  2. 弹出窗口中选择MyEclipse→Web;
  3. 在Deployment选项卡中,去掉JARs from User Libraries前面的复选框。

这样就不会将服务器运行时环境下的jar包发布到服务器中,避免与服务器下的lib发生冲突,使程序能够正常运行。