我有一个像这样的休息 Controller :
@RequestMapping(
value = "/foo",
method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<JsonNode> getFOOs(@Valid Payload payload) {
/** some code **/
}
Payload 类如下所示:
@OneOrTheOther(first = "a", second = "b")
public final class Payload {
private final String userName;
private final String a;
private final String b;
@NotNull
private final String c;
@NotEmtpy{message="At least 1 item"}
private List<String> names = new ArrayList<String>();
}
ArgumentResolver 看起来像这样:
public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(Payload.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
if(supportsParameter(methodParameter)) {
HttpServletRequest requestHeader = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
String userName = requestHeader.getHeader("userName");
ObjectMapper mapper = new ObjectMapper();
JsonNode requestBody = mapper.readTree(CharStreams.toString(requestHeader.getReader()));
JsonNode a = requestBody.path("a");
String a = a.isMissingNode() ? null : a.asText();
JsonNode b = requestBody.path("b");
String b = b.isMissingNode() ? null : b.asText();
JsonNode c = requestBody.path("c");
String c = c.isMissingNode() ? null : c.asText();
JavaType type = mapper.getTypeFactory().constructCollectionType(ArrayList.class, String.class);
List<String> ids
= requestBody.path("ids").isMissingNode()
? null : mapper.readValue(requestBody.path("ids").toString(), type);
return new Payload(username, a, b, c, ids);
}
return null;
}
}
目前,这完成了我希望它完成的大约 95%。它成功地从 header 和请求正文中检索了所有项目,并创建了一个 Payload 对象。但是在创建对象之后,我想运行在 Payload 类中注释的验证,例如 NotNull、NotEmpty 或我的客户 validator OneOrTheOther。
我做了一些挖掘,发现了一些堆栈文章 here和 here .我不知道如何实现第一个,第二个似乎过于复杂和繁琐,所以我不想真正走那条路。似乎使用 validateIfApplicable 方法是可行的方法,但我将如何在我的上下文中调用它?
最佳答案
您可以在您的类中添加一个 SmartValidator 实例。只需添加:
@Autowired
SmartValidator payloadValidator;
一旦注入(inject),您只需调用它的验证方法,传递您的 bean 和错误列表。
供引用:
智能 validator :http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/SmartValidator.html
错误:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/Errors.html
关于参数解析器后的 Java 手动验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527695/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"