Jersey框架:嵌入式Web应用

本文介绍如何使用嵌入式Jetty容器在Jersey中集成Webapp应用,前端以最简单的html和jquery方式实现。

业务场景

几乎所有Apache所有的大数据组件自带的Web界面都采用Jersey和内置容器Jetty的实现方案,如HDFS、Spark、Hive、Storm、Nifi、Zeppelin等。
如HDFS服务,后端API和前端Web界面均默认使用50070端口启动,API为Web界面提供REST接口支持。
在这里插入图片描述
Jersey+Jetty方案的优点
(1)前后端使用同一端口,共同存亡,方便服务维护;
(2)使用Jetty作为嵌入式Web容器,无需再维护额外Web容器,节约运维成本。

Jersey集成Webapp

在Jersey中使用嵌入式Web应用,需要jetty-webapp的支持,在maven依赖中加入以下库。

<!--webapp -->
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-webapp</artifactId>
    <version>${jetty.version}</version>
</dependency>

在服务器启动类中,使用以下方法创建一个WebAppContext,然后再将其加入到服务器的处理器中。

private static WebAppContext createWebappContext() {
    WebAppContext context = new WebAppContext();
    context.setBaseResource(Resource.newClassPathResource("webapp"));
    context.setContextPath("/web");
    context.setWelcomeFiles(new String[]{"index.html"});
    return context;
}

//加入Server处理器
HandlerList handlerList = new HandlerList();
handlerList.addHandler(createWebappContext());
handlerList.addHandler(apiContext);
server.setHandler(handlerList);
server.start();

后端API

以JSON方式模拟一个获取APP列表的请求。

@Path("/app")
public class AppRes {
    @Path("")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response get() {
        //使用JSON模拟数据
        JSONArray apps = new JSONArray();
        JSONObject app1 = new JSONObject();
        app1.put("id", 100001);
        app1.put("name", "News");
        app1.put("desc", "News app");

        JSONObject app2 = new JSONObject();
        app2.put("id", 100002);
        app2.put("name", "Sports ");
        app2.put("desc", "Sports app");

        apps.add(app1);
        apps.add(app2);

        JSONObject resp = new JSONObject();
        resp.put("apps", apps);
        resp.put("total", 100);

        return Response.ok(JSON.toJSONString(resp, SerializerFeature.PrettyFormat)).build();
    }
}

访问http://localhost:8081/app响应数据如下:

{
  "total": 100,
  "apps": [
    {
      "name": "News",
      "id": 100001,
      "desc": "News app"
    },
    {
      "name": "Sports ",
      "id": 100002,
      "desc": "Sports app"
    }
  ]
}

前端界面

使用Jquery发起ajax请求,请求APP列表数据,并将其显示到表格中。

<script type="text/javascript">
    $.ajax({
        url: '/app/',
        type: 'GET',
        dataType: 'json',
        success: function (app) {
            $(".count").html(app['total']);
            var apps = app['apps'];
            for (var o in apps) {
                $("table").append("<tr><td>" + apps[o]['id'] + "</td>" +
                    "<td>" + apps[o]['name'] + "</td>" +
                    "<td>" + apps[o]['desc'] + "</td>" +
                    "</tr>");
            }
        },
        error: function (err) {
            console.log(err)
        }
    });
</script>

测试

访问http://localhost:8081/web/,使用开发者工具查看后端请求,结果如图所示。

在这里插入图片描述
完整案例代码:https://github.com/majxbear/jetty-rest

猜你喜欢

转载自blog.csdn.net/majianxiong_lzu/article/details/89632450