IntelliJ IDEA + Maven + Jetty + Jersey搭建RESTful服务
这次参考的是这个博客,完全按照这个我这里会出一些问题,一会再说就是了。
https://www.cnblogs.com/puyangsky/p/5368132.html
一、首先新建一个项目,选择Java Enterprise -> RESTful Web Serice

这里就会有一个问题,是选择Use library就是选择自己的jar包,还是编译器从网上下载Jersey-2.2的相关jar包。因为我想要的是后面自己使用maven加入jersey和jetty依赖,所以应该是都不选的,所以点击旁边的Configure

把要下载的jar包都取消掉
二、创建完项目后,对项目点击右键 -> Add Frameworks Support,分别勾选Web Application和Maven


三、在pom.xml中加入jersey和jetty依赖:
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19.1</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.25</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19.1</version>
</dependency>
</dependencies>
四、在java下创建自己的包,然后新建一个HelloWorld类
package test; import javax.ws.rs.*; //Path注解来设置url访问路径 @Path("/hello") public class HelloWorld { //GET注解设置接受请求类型为GET @GET //Produces表明发送出去的数据类型为text/plain //与Produces对应的是@Consumes,表示接受的数据类型为text/plain @Produces("text/plain") public String getString() { return "hello jersey!"; } }
五、使用Jetty创建一个服务器类StartEntity类:
public class StartEntity { public static void main(String[] args) { Server server = new Server(8090); ServletHolder sh = new ServletHolder(ServletContainer.class); sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", PackagesResourceConfig.class.getCanonicalName()); sh.setInitParameter("com.sun.jersey.config.property.packages", "test");//这里的第二个参数需要修改成自己的包名 //start server Context context = new Context(server, null); context.addServlet(sh, "/*"); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } } }
然后,点击右键,Run "StartEntity.main()"
五、在浏览器中输入http://localhost:8090/hello,就可以得到以下结果

这样就算搭建完了

浙公网安备 33010602011771号