返回值是内置类型 不能更改

在上一篇文章中 ,我们研究了如何使用MOXy的功能来控制特定实体的数据输出级别。 这篇文章着眼于Jersey 2.x提供的抽象,它允许您定义一组自定义的批注以具有相同的效果。

与之前一样,我们几乎没有什么琐碎的资源可以返回Jersey会为我们转换为JSON的对象,请注意,目前此代码中没有任何内容可以进行过滤–我不会将注释传递给
Response对象,如Jersey示例中所示:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;@Path("hello")
public class SelectableHello {@GET@Produces({ "application/json; level=detailed", "application/json; level=summary", "application/json; level=normal" })public Message hello() {return new Message();}
}

在我的设计中,我将定义四个注释: NoViewSummaryViewNormalViewDetailedView 。 所有根对象都必须实现NoView注释,以防止暴露未注释的字段-您可能觉得设计中没有必要。 所有这些类看起来都一样,所以我只显示一个。 请注意,创建AnnotationLiteral的工厂方法必须优先于创建动态代理以具有相同效果的工厂使用。 2.5中有代码,将忽略由java.lang.reflect.Proxy对象实现的任何注释,其中包括您可能从类中检索到的所有注释。 我正在为此提交修复程序。

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;import javax.enterprise.util.AnnotationLiteral;import org.glassfish.jersey.message.filtering.EntityFiltering;@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EntityFiltering
public @interface NoView {/*** Factory class for creating instances of the annotation.*/public static class Factory extends AnnotationLiteral<NoView> implements NoView {private Factory() {}public static NoView get() {return new Factory();}}}

现在,我们可以快速浏览一下Message Bean,这比我以前的示例稍微复杂一点,以非常简单的形式显示子图的过滤。 正如我之前说过的那样,在类的根部使用NoView注释进行注释–这应该意味着privateData永远不会返回给客户端,因为它没有特别注释。

import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement
@NoView
public class Message {private String privateData;@SummaryViewprivate String summary;@NormalViewprivate String message;@DetailedViewprivate String subtext;@DetailedViewprivate SubMessage submessage;public Message() {summary = "Some simple summary";message = "This is indeed the message";subtext = "This is the deep and meaningful subtext";submessage = new SubMessage();privateData = "The fox is flying tonight";}// Getters and setters not shown
}public class SubMessage {private String message;public SubMessage() {message = "Some sub messages";}// Getters and setters not shown
}

如前所述,资源类中没有用于处理过滤的代码–我认为这是一个横切关注点,因此我将其抽象为WriterInterceptor。 请注意,如果使用的实体没有NoView批注,则会抛出该异常。

import java.io.IOException;import java.lang.annotation.Annotation;import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;import javax.ws.rs.ServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;@Provider
public class ViewWriteInterceptor implements WriterInterceptor {private HttpHeaders httpHeaders;public ViewWriteInterceptor(@Context HttpHeaders httpHeaders) {this.httpHeaders = httpHeaders;}@Overridepublic void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException,WebApplicationException {// I assume this case will never happen, just to be sureif (writerInterceptorContext.getEntity() == null) {writerInterceptorContext.proceed();return;}else{Class<?> entityType = writerInterceptorContext.getEntity().getClass();String entityTypeString = entityType.getName();// Ignore any Jersey system classes, for example wadl//if (entityType == String.class  || entityType.isArray() || entityTypeString.startsWith("com.sun") || entityTypeString.startsWith("org.glassfish")) {writerInterceptorContext.proceed();return;}// Fail if the class doesn't have the default NoView annotation // this prevents any unannotated fields from showing up//else if (!entityType.isAnnotationPresent(NoView.class)) {throw new ServerErrorException("Entity type should be tagged with @NoView annotation " + entityType, Response.Status.INTERNAL_SERVER_ERROR);}}// Get hold of the return media type://MediaType mt = writerInterceptorContext.getMediaType();String level = mt.getParameters().get("level");// Get the annotations and modify as required//Set<Annotation> current = new LinkedHashSet<>();current.addAll(Arrays.asList(writerInterceptorContext.getAnnotations()));switch (level != null ? level : "") {default:case "detailed":current.add(com.example.annotation.DetailedView.Factory.get());case "normal":current.add(com.example.annotation.NormalView.Factory.get());case "summary":current.add(com.example.annotation.SummaryView.Factory.get());}writerInterceptorContext.setAnnotations(current.toArray(new Annotation[current.size()]));//writerInterceptorContext.proceed();}
}

最后,您必须手动启用EntityFilterFeature,为此,您可以在Application类中简单地注册它

import java.lang.annotation.Annotation;import javax.ws.rs.ApplicationPath;import org.glassfish.jersey.message.filtering.EntityFilteringFeature;
import org.glassfish.jersey.server.ResourceConfig;@ApplicationPath("/resources/")
public class SelectableApplication extends ResourceConfig {public SelectableApplication() {packages("...");// Set entity-filtering scope via configuration.property(EntityFilteringFeature.ENTITY_FILTERING_SCOPE, new Annotation[] {NormalView.Factory.get(), DetailedView.Factory.get(), NoView.Factory.get(), SummaryView.Factory.get()});register(EntityFilteringFeature.class);}}

一旦一切就绪并运行,应用程序将像以前一样响应:

GET .../hello Accept application/json; level=detailed or application/json
{"message" : "This is indeed the message","submessage" : {"message" : "Some sub messages"},"subtext" : "This is the deep and meaningful subtext","summary" : "Some simple summary"
}GET .../hello Accept application/json; level=normal
{"message" : "This is indeed the message","summary" : "Some simple summary"
}GET .../hello Accept application/json; level=summary
{"summary" : "Some simple summary"
}

这是直接使用MOXy注释的更好选择–使用自定义注释应该更容易将应用程序移植到过度实现中,即使您必须提供自己的过滤器也是如此。 最后,值得探讨的是Jersey扩展,它允许基于角色的筛选 ,我认为这在安全方面很有用。

参考: 通过改变内容类型来选择返回的详细程度,第二部分来自我们的JCG合作伙伴 Gerard Davison,位于Gerard Davison的博客博客中。

翻译自: https://www.javacodegeeks.com/2014/02/selecting-level-of-detail-returned-by-varying-the-content-type-part-ii.html

返回值是内置类型 不能更改

返回值是内置类型 不能更改_选择通过更改内容类型返回的详细程度,第二部分...相关推荐

  1. python input与返回值-Python 详解基本语法_函数_返回值

    Python 详解基本语法 概要: 函数的返回值是函数重要的组成部分.函数的根本在于实现程序的部分功能,所以很多时候我们需要将函数执行后的结果返回给程序再由程序作出进一步的操作.可以说是函数的返回值令 ...

  2. python3主函数返回值_Python 详解基本语法_函数_返回值

    Python 详解基本语法 概要: 函数的返回值是函数重要的组成部分.函数的根本在于实现程序的部分功能,所以很多时候我们需要将函数执行后的结果返回给程序再由程序作出进一步的操作.可以说是函数的返回值令 ...

  3. inline函数返回值_C++ 内联函数 inline的详细分析

    1. 什么是内联函数?   就是使用了关键字inline的函数,如 inline int max(int a, int b){ 2. 内联函数有什么作用?   C++在调用函数时,会执行一系列的操作: ...

  4. shell中返回值是1为真还是假_肝!Shell 脚本编程最佳实践

    阅读本文大概需要 12.5 分钟. 来自:Myths https://blog.mythsman.com/2017/07/23/1/ 前言 由于工作需要,最近重新开始拾掇shell脚本.虽然绝大部分命 ...

  5. 关于ExecuteNonQuery执行存储过程的返回值 、、实例讲解存储过程的返回值与传出参数、、、C#获取存储过程的 Return返回值和Output输出参数值...

    关于ExecuteNonQuery执行存储过程的返回值 用到过ExecuteNonQuery()函数的朋友们在开发的时候肯定这么用过. if(cmd.ExecuteNonQuery("xxx ...

  6. 100内奇数之和流程图_干货分享| 画管道仪表流程图,详细步骤都在这里!

    一键获取技术资料 <现代煤化工政策汇编及解读>2020版.<煤制烯烃产业研究报告>2020版.<煤制油产业研究报告>2020版.<煤制天然气产业研究报告> ...

  7. (14年)2.写一个函数int func(int n)其返回值是n的逆序整数,例如n=123函数返回321.n=72839,函数返回93827

    #include <stdio.h> #include <stdlib.h> /*写一个函数int func(int n)其返回值是n的逆序整数 例如n=123.函数返回321 ...

  8. 选择通过更改内容类型返回的详细程度,第二部分

    在上一篇文章中 ,我们研究了使用MOXy的功能来控制特定实体的数据输出级别. 这篇文章着眼于Jersey 2.x提供的抽象,它允许您定义一组自定义的批注以具有相同的效果. 与之前一样,我们几乎没有什么 ...

  9. 没有返回值的方法mock怎么写_【方法】小学生怎么写读书笔记?

    什么是读书笔记 读书笔记,是指人们在阅读书籍或文章时,遇到值得记录的东西和自己的心得.体会,随时随地把它写下来的一种文体. 古人有条著名的读书治学经验,叫做读书要做到:眼到.口到.心到.手到.这&qu ...

最新文章

  1. ASP.NET程序中常用的三十三种代码 〔转〕
  2. Android之GSON解析JSON
  3. (59)逆向分析 KiSwapContext 和 SwapContext —— 线程切换核心代码
  4. ETL的四个基本过程.
  5. 使用蚂蚁借呗会影响房贷申请吗?
  6. 小程序开发初体验,从静态demo到接入Bmob数据库完全实现
  7. 通过修改explorer.exe内存隐藏文件及注册表项
  8. abview查找范例时说 NI服务器未定位 这是怎么回事?
  9. java ffmpeg amr转wav_FFmpeg转音频格式为wav
  10. 使用 Litho 改进 News Feed 上的 Android 视频表现
  11. 计算机网络路由交换技术运用,计算机网络路由交换的技术应用与发展趋势研究...
  12. Z-Wave 700 秘钥生成、固件签名、及OTA过程
  13. 简单的修改项目中的头像
  14. html日期格式化引用fmt报错
  15. 多态知识整理实现主人与宠物玩耍功能
  16. MobilePose: Real-Time Pose Estimation for Unseen Objects with Weak Shape Supervision
  17. Java-二维码生成与识别(二)
  18. 前端页面性能优化 - 字体加载优化
  19. aardio - 修改虚表颜色带来的各种视觉效果
  20. 【每天读一点英文】gnuhpc注释版:Love Your Life

热门文章

  1. 【随机】Ghd(CF364D)
  2. 【DP】Table(CF232B)
  3. 纪中C组模拟赛总结(2019.9.7)
  4. Jsoup解析HTML实例及文档方法详解
  5. 关于SimpleDateFormat时间格式化线程安全问题
  6. Shell入门(二)之变量
  7. mysql中如何将默认用户名root改成其他?
  8. JS中使用工厂模式创建对象
  9. 2018蓝桥杯省赛---java---B---7(螺旋折线)
  10. 2017蓝桥杯省赛---java---B---7(日期问题)