RESTEasy使用入门

1. 使用maven生成代码框架

mvn archetype:generate -DgroupId=win.mengx.study -DartifactId=RESTfulExample -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

运行命令后,会建立如下目录树:

RESTfulExample
├── pom.xml
└── src
└── main
├── resources
└── webapp
├── index.jsp
└── WEB-INF
└── web.xml

2. 生成idea可使用的工程文件

mvn idea:idea

3. 编辑pom.xml,增加resteasy库的依赖

--- a/pom.xml
+++ b/pom.xml
@@ -14,6 +14,11 @@
3.8.1
test

+ 
+ org.jboss.resteasy
+ resteasy-jaxrs
+ 2.2.1.GA
+ 


4. 创建REST Service

添加文件/src/main/java/win/mengx/study/MessageRestService.java

package win.mengx.study;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/message")
public class MessageRestService {

@GET
@Path("/{param}")
public Response printMessage(@PathParam("param") String msg) {

String result = "Restful example : " + msg;

return Response.status(200).entity(result).build();

}

}

5. 修改web.xml

修改文件src/main/webapp/WEB-INF/web.xml




Restful Web Application



resteasy.scan
true




resteasy.servlet.mapping.prefix
/rest




org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap




resteasy-servlet

org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher




resteasy-servlet
/rest/*



上面的例子,resteasy-servlet url-pattern/rest/*,所以必须设置resteasy.servlet.mapping.prefix/rest[2]。

到此例子可以在tomcat中运行了,只需要编译出war包即可。

运行命令mvn package,在target目录下会生成RESTfulExample.war,把此文件放到tomcat的webapps目录(如果是ubuntu用apt安装的tomcat7,所在目录为/var/lib/tomcat7/webapps)下。重启tomcat服务service tomcat7 restart。打开浏览器,在地址栏中输入http://localhost:8080/RESTfulExample/rest/message/mengx,会显示Restful example : mengx这样的页面。

6. 在IntelliJ IDEA Ultimate中集成tomcat

打开设定窗口,在Application Servers页面,点击+,选择Tomcat Server

RESTEasy使用入门_第1张图片

在弹出的窗口中选择tomcat安装的目录/usr/share/tomcat7

RESTEasy使用入门_第2张图片

注意:这里可能会提示"Error running Tomcat : Can't find directory '/usr/share/tomcat7/conf'",需要在此目录下建立一个conf链接,链接到/var/lib/tomcat7/conf,并且确保此目录对于IDEA来说有读权限[3]。

7. 配置项目

  1. 配置项目的Modules,设置src目录为项目的Sources目录。
    RESTEasy使用入门_第3张图片
  2. 在module中add web


    RESTEasy使用入门_第4张图片
  3. 修改Web Resource Directories,选择目录src/main/webapp
    RESTEasy使用入门_第5张图片

    RESTEasy使用入门_第6张图片
  4. 增加Artifacts,见下图


    RESTEasy使用入门_第7张图片

    RESTEasy使用入门_第8张图片

    RESTEasy使用入门_第9张图片
  5. 配置调试服务


    RESTEasy使用入门_第10张图片
  6. 配置服务端口,例如8088
    RESTEasy使用入门_第11张图片
  7. 点击Deployment标签,添加Artifact
    RESTEasy使用入门_第12张图片

    RESTEasy使用入门_第13张图片

8. 调试

启动调试,用浏览器访问http://localhost:8088/rest/message/mengx,会显示Restful example : mengx这样的页面。注意:这时候,uri中不需要写RESTfulExample

参考链接

  1. RESTEasy hello world example
  2. Can't run Tomcat from Intellij Idea

你可能感兴趣的:(RESTEasy使用入门)