1.Hello World - WebWebService
Create a new Maven webapp project in Eclipse
- 参考此篇文章,在Eclipse创建一个基于Maven的webapp项目。其中Artifact Id按照如下设置
http://www.cnblogs.com/xxuan/p/6739633.html -
修改Maven项目文件pom.xml,如下。增加对jersey的依赖。
pom.xml<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xuan..tutorial</groupId> <artifactId>hello-world-ws</artifactId> <packaging>war</packaging> <version>1.0.0</version> <name>hello-world-ws Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> </dependencies> <build> <finalName>hello-world-ws</finalName> </build> <repositories> <repository> <id>snapshot-repository.java.net</id> <name>Java.net Snapshot Repository for Maven</name> <url>https://maven.java.net/content/repositories/snapshots/</url> <layout>default</layout> </repository> </repositories> </project>
Add HelloWorld Web Service Implementation
- 在src/main/java目录下新增Web Service实现源码文件HelloWorldService.java
-
编辑HelloWorldService.java文件,内容如下
-
1 package com.xuan.flight.tutorial.ws; 2 3 import javax.ws.rs.GET; 4 import javax.ws.rs.Path; 5 import javax.ws.rs.PathParam; 6 7 @Path("/hello") 8 public class HelloWorldService 9 { 10 @GET 11 @Path("/{param}") 12 public String sayHello(@PathParam("param") String msg) 13 { 14 String output = "Hello : " + msg; 15 return output; 16 } 17 }
-
编辑WEB-INF下的web.xml文件,注册Jersey的Servlet“com.sun.jersey.spi.container.servlet.ServletContainer“, 并将刚才生成的Web Service目录作为其初始化参数 “init-param“, “com.sun.jersey.config.property.packages“.
-
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 <web-app> 5 <display-name>Archetype Created Web Application</display-name> 6 7 <servlet> 8 <servlet-name>jersey-serlvet</servlet-name> 9 <servlet-class> 10 com.sun.jersey.spi.container.servlet.ServletContainer 11 </servlet-class> 12 <init-param> 13 <param-name>com.sun.jersey.config.property.packages</param-name> 14 <param-value>com.ctrip.flight.tutorial.ws</param-value> 15 </init-param> 16 <load-on-startup>1</load-on-startup> 17 </servlet> 18 <servlet-mapping> 19 <servlet-name>jersey-serlvet</servlet-name> 20 <url-pattern>/rest/*</url-pattern> 21 </servlet-mapping> 22 </web-app>
Compile & Deploy
- 进入项目所在目录(pom.xml文件所在位置),运行命令mvn clean package。在target目录下生成了文件hello-world-ws.war。
- 将hello-world-web.war文件copy到${TOMCAT_HOME}/webapps目录下,重启tomcat。
-
在浏览器中访问http://localhost:8080/hello-world-ws/rest/hello/world,可以看到如下输出。