1、先在pom.xml文件中添加依赖:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
</dependencies>
2、在web.xml中添加jersey类
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.example.AirApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
其中com.example.AirApplication类扫描所有的对外服务类
3、新建对外服务类
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
@Path("myresource1")
public class MyResource1 {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it222!";
}
}
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource1" path)
*/
@Path("myresource1")
public class MyResource1 {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it222!";
}
}
4、在AirApplication类中扫描服务类
package com.example;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class AirApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(MyResource.class);
classes.add(MyResource1.class);
return classes;
}
}
这样在tomcat中启动就可以访问资源类中的方法。