jersey构建Web项目、Json格式传输

通过mvn创建jersey项目:

https://jersey.java.net/download.html
mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes \
    -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.23.2

创建项目后index.jsp会报错
有两种解决方法,第一种删掉
第二种右键项目-》Target Runtimes=》选择tomat=》Apply=》ok

maven+jersey+grizzly容器部署rest api:

不用tomcat,直接运行主函数就可以通过网站访问restful api了,用内置的grizzly代替了tomcat

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes \
    -DarchetypeArtifactId=jersey-quickstart-grizzly2 -DarchetypeVersion=2.23.2

jersey与json配套使用:

一个类继承ResourceConfig


import org.glassfish.jersey.moxy.json.MoxyJsonFeature;
import org.glassfish.jersey.moxy.xml.MoxyXmlFeature;
import org.glassfish.jersey.server.ResourceConfig;


public class AppResourceRegister extends ResourceConfig {

    private final String APIPath = "api类所在包名";

    public AppResourceRegister() {
        /*
         * add the API resource
         */
        packages(APIPath);
        /*
         * add feature to use the JSON
         */

        register(MoxyJsonFeature.class);
        /*
         * add feature to use the XML
         */
        register(MoxyXmlFeature.class);
    }
}

定义传输的数据格式javabean,在类名上标记@XmlRootElement,添加get和set方法

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class TableInfo {

    private String tableName;
    private String tablePath;

    public TableInfo() {

    }

    public TableInfo(String tableName, String tablePath) {
        this.tableName = tableName;
        this.tablePath = tablePath;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getTablePath() {
        return tablePath;
    }

    public void setTablePath(String tablePath) {
        this.tablePath = tablePath;
    }

}




import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BaseResponse {

    private int statusCode;
    private String message;

    public BaseResponse() {

    }

    public BaseResponse(int statusCode, String message) {
        this.statusCode = statusCode;
        this.message = message;
    }

    public BaseResponse(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}



import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement
public class TableResponde extends BaseResponse {

    private TableInfo tableInfo;

    public TableResponde() {
    }

    public TableResponde(int statusCode, String message,TableInfo tableInfo)    {
        super(statusCode, message);
        this.tableInfo = tableInfo;

    }

    public TableResponde(int statusCode,TableInfo tableInfo) {
        super(statusCode);
        this.tableInfo = tableInfo;

    }

    public TableInfo getTableInfo() {
        return tableInfo;
    }

    public void setTableInfo(TableInfo tableInfo) {
        this.tableInfo = tableInfo;
    }

}

在rest api上标记
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Path("table")
public class TableAPIService {

    private static final Logger logger = LoggerFactory.getLogger(TableAPIService.class);
    private final String GET_TABLE_SUCCESS_MESSAGE = "Success to get the table";
    private final String GET_TABLE_FAIL_MESSAGE = "Fail to get the table: table is not exist.";

    private final String PUT_TABLE_SUCCESS_MESSAGE = "Success to put the table";
    private final String PUT_TABLE_FAIL_MESSAGE = "Fail to put the table: table is exist";

    private final String DELETE_TABLE_SUCCESS_MESSAGE = "Success to delete the table";
    private final String DELETE_TABLE_FAIL_MESSAGE = "Fail to delete the table: table is not exist ";

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<TableInfo> getTables() {
        logger.info("get all tables");
        List<TableInfo> list = new ArrayList<>();
        Map<String, TableInfo> map = TableInfoStorage.getTablesMap();
        for (String tableId : map.keySet()) {
            list.add(map.get(tableId));
        }
        return list;
    }

    @GET
    @Path("/{tableId}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public TableResponde getTable(@PathParam("tableId") String tableId) {
        logger.info("get tableId : {}", tableId);
        TableResponde responde = new TableResponde();
        /*
         * check this table exist or not
         */
        if (TableInfoStorage.IsTableExist(tableId)) {
            TableInfo info = TableInfoStorage.getTableInfo(tableId);
            responde.setStatusCode(StatusCode.SUCCESS);
            responde.setMessage(GET_TABLE_SUCCESS_MESSAGE);
            responde.setTableInfo(info);
        } else {
            responde.setStatusCode(StatusCode.FAIL);
            responde.setMessage(GET_TABLE_FAIL_MESSAGE);
        }
        logger.info(responde.getMessage());
        return responde;
    }

    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public TableResponde putTalbe(TableInfo tableInfo) {

        logger.info("put tableInfo <<< tableName:{}, tablePath:{}", tableInfo.getTableName(), tableInfo.getTablePath());
        TableResponde responde = new TableResponde();

        if (TableInfoStorage.createTable(tableInfo)) {
            responde.setStatusCode(StatusCode.SUCCESS);
            responde.setMessage(PUT_TABLE_SUCCESS_MESSAGE);

        } else {
            responde.setStatusCode(StatusCode.FAIL);
            responde.setMessage(PUT_TABLE_FAIL_MESSAGE);
        }
        responde.setTableInfo(tableInfo);
        logger.info(responde.getMessage());
        return responde;
    }

    @DELETE
    @Path("/{tableId}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public TableResponde deleteTable(@PathParam("tableId") String tableId) {
        logger.info("delete table <<< tableid:{}", tableId);
        TableResponde responde = new TableResponde();
        if (TableInfoStorage.deleteTable(tableId)) {
            responde.setStatusCode(StatusCode.SUCCESS);
            responde.setMessage(DELETE_TABLE_SUCCESS_MESSAGE);
        } else {
            responde.setStatusCode(StatusCode.FAIL);
            responde.setMessage(DELETE_TABLE_FAIL_MESSAGE);
        }
        logger.info(responde.getMessage());
        return responde;
    }
}

传输的时候就可以使用json格式了,很方便。

jersey使用JSON反序列化成bean的问题:

自定义的POJO类,用@XmlRootElement标记的类,用来传输json时,里面不能有Object,如果有测试不能通过,但是网页请求可以收到json字符串,应该是不能反序列化成类的对象。而且里面任何自定义类都需要进行标记。

大家有兴趣的可以关注我的公众号(分布式系统斗者),涉及分布式系统、大数据和个人成长分享,欢迎大家一起交流进步

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值