构建基本的Java Restful服务

本文简记通过Maven构建Java Restful服务的过程。

Maven命令构建项目

mvn archetype:generate -DgroupId=com.aspect -DartifactId=SpringAspectJTest -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false -DarchetypeCatalog=internal

interactiveMode:交互模式,默认为true。上述命令是一次性把信息都输入进去了,免去了交互。

archetypeCatalog=internal 表示部分配置从本地获取,例如archetype-catalog.xml

参考:http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

项目结构

添加依赖包和插件

在pom.xml中添加需要的依赖包和插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringAspectJTest</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>TomcatServer</server>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
添加逻辑类代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.aspect;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class TestServlet {
@GET
@Path("/{param}")
public Response getMessage(@PathParam("param") String value){
String output="Hello "+value;
return Response.status(200).entity(output).build();
}
}
修改Servlet配置web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.aspect</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
运行测试

http://localhost:8080/rest/hello/world

热评文章