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,就可以得到以下结果

这样就算搭建完了

 

转载于:https://www.cnblogs.com/xxbbtt/p/7902585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值