Archive for the ‘ IT ’ Category


GET Vs POST 完全指南

翻译自Think Vitamin, Carsonified’s Blog, http://carsonified.com/blog/dev/the-definitive-guide-to-get-vs-post/

规则#1:对于安全操作使用GET,对于非安全操作使用POST
1)GET请求可以被缓存(Cached)
2)GET请求可以被存在浏览器历史中
3)GET请求可以被收藏夹收藏
4)GET请求可以分发和共享
5)GET请求可以被hack

规则#2: 对于敏感的数据使用POST

规则#3: 对于很长的请求使用POST

规则#4:在AJAX环境中使用GET

IEEE Science and Engineering Graduate Research Expo

Our project SOVoIP is among those candidates, however, I will be in Macau at that day. Good luck to my partners! BTW, this might be my first paper to be published and indexed.

JMF的学习资料

JMF不是一个特别新的规范,但是在实际中使用的人较少,因此资料也不是特别的多。

ODU的一门课包括了不少JMF的介绍,其中的这套课件还是编写的很不错的。作为学习JMF的入门参考资料是很好的。http://www.cs.odu.edu/~cs778/jmflects/

如果Glassfish无法启动了

当用Netbeans部署一个项目出现状况的时候,往往尝试着重新启动Glassfish,而这个时候更有可能你会发现Glassfish无法启动了,等待了很久之后报出了如下一段错误:

The Sun Java System Application Server could not start.
More information about the cause is in the Server log file.
Possible reasons include:
- IDE timeout: refresh the server node to see if it’s running now.
- Port conflicts. (use netstat -a to detect possible port numbers already used by the operating system.)
- Incorrect server configuration (domain.xml to be corrected manually)
- Corrupted Deployed Applications preventing the server to start.(This can be seen in the server.log file. In this case, domain.xml needs to be modified).
- Invalid installation location.
See the server log for details.
BUILD FAILED (total time: 5 minutes 20 seconds)

你甚至会发现无论你如何卸载重新安装Glassfish, Netbeans,你的服务器仍然无法顺利启动。

其实问题的关键不是在这里,而是在你的domain之下。找到\domains\domain1\imq\instances\imqbroker这个文件目录下,你会发现一个lock文件。将它删除掉,Glassfish就顺利复原了。

至于原因是什么,我在GOOGLE上也没搜出个大概,先知其然而不知其所以然吧。

RESTful Web Services Developer’s Guide

Chapter 1
Introduction to RESTful Web Services and Jersey
1. What are RESTful Web Services?
RESTful - REpresentational State Transfer is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web.
Data and functionality are considered resources, and these resources are accessed using URIs (Unifomr Resource Identifiers), typically links on the web.
The REST architectural style constrains an architecture to a client-server architecture, and is designed to use a stateless communication protocol, typically HTTP. Clients and servers exchange representations of resources using a standardized interface and protocol.
RESTful web services typically map the four main HTTP methods to the operations they perform: create, retrieve, update and delete.
GET — Get a resource;    POST — Create a resource and other operations, as it has no defined semantics;    PUT — Create or update a resource;    DELETE — delete a resource

2. How does Jersey fit in?
Jersey is Sun’s production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and Java JVM. Jersey also adds additional features not specified by the JSR.

Chapter 3
Creating a RESTful resource class
Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator such as @GET, @PUT, @POST,  or @DELETE.
Resource methods are methods of a resource class annotated with a request method designator.

1. Developing RESTful web services with Jersey
Developers decorate Java programming language class files with HTTP-specific annotations to define resources and the actions that can be performed on those resources. Jersey annotations are runtime annotations, therefore, runtime reflection will generate the helper classes and artifacts for the resource, and then the collection of classes and artifacts will be built into a WAR. The resources are exposed to clients by deploying the WAR to a Java EE or web server.

@Path annotation’s value is a relative URI path. What makes JAX-RS so useful is that you can embed variables in the URIs. URI path templates are URIs with variables embedded within the URI syntax.
@GET annotation is a request method designator, along with @POST, @PUT, @DELETE, and @HEAD, that is defined by JAX-RS, and which correspond to the similarly named HTTP methods.
@Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.
@Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.

2. What are some of the annotations defined by JAX-RS?

Annotations Description
@Path The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted, for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example, you could ask for the name of a user, and pass it to the application as a variable in the URI, like this, /helloworld/{username}.
@GET The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@POST The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PUT The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@DELETE The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
@PathParam The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
@QueryParam The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
@Consumes The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
@Produces The @Produces annotation is used to specify the MIME media type of representations a resource can produce and send back to the client, for example, “text/plain”.
@Provider The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body using MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity, and which can be built using Response.ResponseBuilder.

3. The @Path annotation and URI path templates.
The @Path annotation identifies the URI path template to which the resource responds, and is specified at the class level of a resource. URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by curly braces.
@Path (”/users/{username}”)
if user entered user name as Galileo, the web service will respond to the following URL: http://example.com/users/Galileo

The @PathParam annotation may be used on the method parameter of a request method to obtain the value of the username variable.
public class UserResource{
@GET
@Produces(”text/xml”)
public String getUser(@PathParam(”username”) String userName){

}
}

By default, there is no difference between @Path value begin or not begin with a forward slash(/) and end with a forward slash(/) as well. However, Jersey has a redirection mechanism, if enabled, will perform redirection.

4. Responding to HTTP Resources
The behavior of a resource is determined by the HTTP methods (typically GET, POST, PUT, and DELETE)  to which the resource is responding.
By default, the JAX-RS runtime will automatically support the methods HEAD and OPTIONS if not explicitly implemented. For HEAD, the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). For OPTIONS, the Allow response header will be set to the set of HTTP methods support by the resources. In addition Jersey will return a WADL document describing the resource.
Method decorated with request method designators must return void, a Java programming language type, or a javax.ws.rs.core.Response object. Multiple parameters may be extracted from the URI using the PathParam or QueryParam annotations. Conversion between Java types and entity body is the responsibility of an entity provider, such as MessageBodyReader or MessageBodyWriter. Methods that need to provide additional metadata with a response should return an instance of Response. The ResponseBuilder class provides a convenient way to create a Response instance using a builder pattern. The HTTP PUT and POST methods expect an HTTP request body, so you should use a MessageBodyReader for methods that respond to PUT and POST requests.

5. Using entity providers to map HTTP response and request entity bodies.
Entity providers supply mapping services between representations and their associated Java types.
The following list contains the standard types that are supported automatically for entities. You only need to write an entity provider if you are not choosing one of the following standard types.

6. Using @Consumes and @Produces to customize requests and responses
The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client. If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If it is applied at the method level, it overrides any @Produces annotations applied at the class level.
If no methods in a resource are able to produce the MIME type in a client request, the Jersey runtime sends back an HTTP “406 Not Acceptable” error.
The value of @Produces is an array of String of MIME types.
If a resource class is capable of producing more than one MIME media type, the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically, the Accept header of the HTTP request declared what is most acceptable.

The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, from the client. If @Consumes is applied at the class level, all the response methods accept the specified MIME types by default. If @Consumes is applied at the method level, it overrides any @Consumes annotations applied at the class level.
If a resource is unable to consume the MIME type of a client request, the Jersey runtime sends back an HTTP “415 Unsupported Media Type” error.
The value of @Consumes is an array of String of acceptable MIME types.

7. Extracting Request Parameters
Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. There are six types of parameters you can extract for use in your resource class: query parameters, URI path parameters, form parameters, cookie parameters, header parameters, and matrix parameters.
Query parameters are extracted from the request URI query parameters, and are specified by using the javax.rs.QueryParam annotation in the method parameter arguments.
@QueryParam and @PathParam can only be used on the following Java types: all primitive types except char, all wrapper class of primitive types except Character, have a constructor that accepts a single String argument, any class with the static method named valueOf(String) that accpets a single String argument, any class with a constructor that takes a single String as a parameter, List<T>, Set<T>, or SortedSet<T>, where T matches the already listed criteria. Sometimes parameters may contain more than one value for the same name. If this is the case, these types may be used to obtain all values.
If @DefaultValue is not used in conjunction with @QueryOaram, and the query parameter is not present in the request, then value will be an empty collection for List, Set, or SortedSet; null for other object types; and the Java-defined default for primitive types.
URI path parametes are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. URI parameters are specified using the javax.ws.rs.PathParam annotation in the method paraeter arguments.
Form parameters extract information from a request representation that is of the MIME media type application/x-www-form-urlencoded and conforms to the encoding specified by HTML forms.
@Context can be used to obtain contextual Java types related to the request or response.

转载一篇介绍RoR上REST概念的文章

发现这篇文章很基础,但是讲的算是比较清楚。先把链接贴上来,有兴趣的大家可以去看看。尽管有点老了。看完之后,再来谈谈自己对于REST的一些想法。

http://www.letrails.cn/archives/6

Updated 16:21, 感觉自己对J2EE的理解还非常的肤浅,非常非常的肤浅。尽管今天看上去顺利地解决了改解决的问题,但是还有几个地方概念是非常模糊的。下面几点是要在接下来几天里着重解决的:

1. Annotation,这个东西尽管看上去很高级,但是实际上在很多很多的场合都是用的非常的多。但是因为我没有深入地看过Spring,对这一概念仍然是十分混淆。

2. JAXB, 无论是DOM还是SAX,都是很久远的技术,现在的流行时JAXB。要说我有多懂这个概念,谈不上。但是发现他的确是非常神奇,到了今天自己才碰上他,说明我对JAVA阵营真的是落寞很久了。

3. Ruby on Rails,记得我还在读大四的时候,这个概念已经开始炒作了。但是没有跟上去,于是现在就落伍了。但是只落伍了两年,还不算太晚。在就业之前,把这些好好地补一补吧。

SEO Strategies(1) – from “Building Findable Website”, Aaron Walter

读书时做的笔记,懒的翻译成中文了。这是第一部分,明天有时间研究一下Microformat.

1. Strictly follow the standards of W3C. You can validate your web page by the tool at: http://validator.w3c.org/.

2. Decrease the ratio of markup to content, improve the page load time and improve the communication of the information hierarchy of your page.

3. Image Replacement:

Replace the img tag which shows the logo or the most important information of this page with a <h1> tag. The content of <h1> tag will be the details introduction of the page or the logo, with indentation to place that can not display on the screen, and a background image setted to be the real image file with its name renamed to be more meaningful. This strategy can only be used once for any certain page since it is better to limit the <h1> tag into only once for a page.

4. Signals of Quality:

1) Number of inbound links to the page from reputable sources, which is the way Google does.

2) Web standards are not 100 percent gurantee of top page ranking, but important to it. Therefore pages should follow the standards as closely as possible.

5. Highly valued tags for search engines:

1) <title>, keep it concise and natural. <title> page title | organization or site name | short keyword-rich phrase </title>

2) <strong> and <en>, elevating certain part of the content’s ranking within the information hierarchy

3) <a>, title attribute inside <a> tag, and also include target keywords in the link labels. An inbound link with the same keyword in the label as your site target is extremely effective.

6. Meta:

1) keywords in <meta> is useless, while description is still important. Limit the characters in <description> between 100 to 150 which is better for search engines to display.

2) use lang for multilingual site, like <meta name=”description” lang=”en-us” content=”" /> and <meta name=”description” lang=”zh-cn” content=”" />

3) No need to use robots in tag. <meta name=”robots” content=”all” />

4) Never use refresh attribute since it might be penalized for bait-and-switch strategy.

5) Always include content-type.

6) Use <meta name=”robots” value=”noindex,nofollow” /> to prevent certain page be indexed by the search engine.

Add class=”robots-nocontent” to those tags that you wish to hide like ads.

7. Making Images Visible:

1) When the image is just used for decoration, apply it to css file as a background.

2) Always use alt attribute to give short introduction of the image

3) If alt is not long enough, use longdesc instead, which can link to a footnote to have more details.

Java查漏补缺3-Swing中的文本绑定监听

在做简单的Swing开发中,会经常遇到这样的情况,需啊监听文本框的内容的变化。比如一个最简单的例子就是如果登陆框中用户名和密码都不为空的时候,登陆按钮才被激活。

在查看事件的时候,很多人第一眼看到的就是InputMethod下面的caretPositionChanged和inputMethodTextChanged。无论从文档还是从函数名字来看,这两个函数似乎都是我们所需要实现的方法。可惜当你填满了里面的内容,DEBUG的时候,会发现无论如何你改变你的输入框的内容,根本都不会触发这两个事件。在Sun的论坛上,有个人回了这样一句话来解决这个问题:“A component will only receive input method events from input methods if it also overrides getInputMethodRequests to return an InputMethodRequests instance.”

不愿意为这个问题多纠结,给出解决方案就是使用DocumentListener。这个接口提供了三个方法来侦听所绑定的文本的内容。对于我们需要的监听对象,直接添加这个侦听器,并实行其中的方法即可。

Document doc1 = jTextFieldId.getDocument();
doc1.addDocumentListener(new DocumentListener() {
            String name;
            String pwd;

            public void insertUpdate(DocumentEvent e) {
                name = jTextFieldId.getText();
                pwd = new String(jPasswordFieldPassword.getPassword());
                if(!name.equals("") && !pwd.equals("")){
                    jButtonSignIn.setEnabled(true);
                } else {
                    jButtonSignIn.setEnabled(false);
                }

            }

            public void removeUpdate(DocumentEvent e) {
                name = jTextFieldId.getText();
                pwd = new String(jPasswordFieldPassword.getPassword());
                if(!name.equals("") && !pwd.equals("")){
                    jButtonSignIn.setEnabled(true);
                } else {
                    jButtonSignIn.setEnabled(false);
                }
            }

            public void changedUpdate(DocumentEvent e) {

            }
        });

Java查漏补缺2 - 等于判断

基础的只是大家都很清楚,对于原始类型如int, float,直接用==就可以比较。对于Class类型的,在Java中使用的是reference的比较,因此需要使用的是equals.

Integer a1 = new Integer(1);
Integer a2 = new Integer(1);
System.out.println(a1==a2); //false
System.out.println(a1.equals(a2)); //true

因此在上述代码中,尽管使用的看上去就是int,但是因为实际已经使用了Integer,所以单纯使用==是不能比较的。

对于自己定义的类型,如果直接使用equals来比较,将会同样返回非期望的值。因为新定义的类,一般不会去重写equals的方法,而会直接调用其父类的equals方法,将也是直接比较reference。如果我们需要比较自定义的类型的时候,只需要重写equals方法就可以了。

class MyClass{
        private int count;
        public MyClass(int a){
            this.count=a;
        }

    @Override
    public boolean equals(Object obj) {
        MyClass newmc = (MyClass)obj;
        return this.count==newmc.count ? true : false;
    }

MyClass m1 = new MyClass(1);
MyClass m2 = new MyClass(1);
System.out.println(m1==m2);
System.out.println(m1.equals(m2));

Java查漏补缺1-Binding时间

在编程语言中,有两种binding方式,一是在compile期间binding,被称作Early-binding,一种是在execute期间binding,被称作Late-binding。
在Java中,更多的采用的是Late-binding这种方式。要做一个比较好的解释,可以看看关于继承的例子。以下这段代码显示了一个很简单的继承关系,父类是Shape,子类是Circle和Rectangle,其中分别实现了各自的draw()方法。

public class Shape {
    public void draw(){
        System.out.println("Draw shape");
    }
}

public class Circle extends Shape{
    public void draw(){
        System.out.println("Draw circle");
    }
}

public class Rectangle extends Shape{
    public void draw(){
        System.out.println("Draw rectangle");
    }
}

public class Test {
    public static void main(String[] args){
            Shape shape = new Shape();
            shape.draw();
            Shape shape1 = new Rectangle();
            shape1.draw();
            Shape shape2 = new Circle();
            shape2.draw();
        }
}

在以上的示例中,我们在main函数中看到生成了三个分别是以上三个类的实例,但是它们共用了同样的Shape声明。这也就是Java最重要的多态的之所在。不过不是本文的重点,略过。我们发现既然三个实例享有同样的声明,在编译期间,编译器是无法判断到底每一个实例属于的是哪一个类,需要调用的是哪一个draw方法。而在执行期间,run-time会自动根据new关键字对应的类型,将其binding上。这就是所谓的late-binding。在传统的大多数非OOP语言中,early-binding占据绝大多数。总之,early-binding意味着在程序编译期间,运行时系统将确定需要调用的函数的地址,而late-binding则会在系统运行时根据当时情况动态决定。(在C++中,也支持类似的late-binding,不过需要显示的加以virtual关键字)

Older Entries Newer Entries
  • English Version

    • Cannot read Chinese? Please take a look at my English site, hope you can find more you need there!
  • 感谢支持

  • twitter

    facebook

    linkedin

    • You are currently browsing the archives for the IT category.

  • Categories