1. 安装好jdk
2. 根据前面的文章介绍,创建好tomcat运行时环境
3. 这里对tomcat的配置重点提出来,以避免本人在实验的时候遇到的众多诡异问题
tomcat解压后有RUNNING.txt。
根据里面的guide,大家需要配置好以下内容
CATALINA_HOME的环境变量为E:\apache-tomcat-8.0.30
CATALINA_BASE不需要设置
JAVA_HOME设置为E:\java
JRE_HOME不需要设置
验证方法:
windows: %CATALINA_HOME%\bin\startup.bat
Linux: $CATALINA_HOME/bin/startup.sh
http://localhost:8080/ 能看到正常tomcat网页则表示通过
好了,前面都是一些小插曲,下面介绍如何创建jersey resful service
1. 创建动态web项目,注意一路点next,最后勾选"generate .web.xml"
2. 为防止万一,首先将jersey中所有的jar包都拷贝到web-inf下的lib中,右击web项目---refresh
3. 右击web项目,build path----configure build path----libraries---add jars---将web项目中web-inf下的lib中所有jar包导入进来
4. 创建class 例如 RestApplication
package fei;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
public class RestApplication extends ResourceConfig{
public RestApplication() {
packages("fei"); 指定包名,将会加载此包中的所有资源类
register(LoggingFilter.class);
}
}
5. 创建class 例如 HelloCloud
package fei;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloCloud { 资源类,注意path的位置
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getWebServiceInfo() {
return "Hello,RESTful web service!";
}
}
6. 修改web.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>fei</display-name>
<servlet>
<servlet-name>hello cloud</servlet-name> 名字任意取
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 固定
<init-param>
<param-name>javax.ws.rs.Application</param-name> 固定
<param-value>fei.RestApplication</param-value> 包名.类名
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello cloud</servlet-name> 同上名字
<url-pattern>/*</url-pattern> 客户端访问的路径前缀
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
7. 右键项目,选择run as ---run on server ---选择tomcat
8. 浏览器中访问http://localhost:8080/fei/hello
前面是包名,后面是资源类中path的内容
即可看到内容
Hello,RESTful web service!
至此,地一个简单的restful app开发完成
上面有很多注意事项,务必严格按照上面的步骤执行,否则可能出现问题需要调试。