【问题标题】:Is there any request method enum in Servlet API? [duplicate]Servlet API 中是否有任何请求方法枚举? [复制]
【发布时间】:2017-08-18 10:37:31
【问题描述】:

有没有更优雅的方法来做到这一点?

if (request.getMethod() == "OPTIONS") {
   ...
}

我的意思是我可以使用enumclass 来参考吗?

例子:

if (request.getContentType().equals(MediaType.APPLICATION_JSON)) {
    ...
}

【问题讨论】:

  • 您可以使用具有mathces(String method)resolve(String method) 方法的org.springframework.http.HttpMethod 枚举。喜欢:HttpMethod.OPTIONS.matches(request.getMethod())

标签: servlets


【解决方案1】:

有没有更优雅的方法来做到这一点?

if (request.getMethod() == "OPTIONS") {    
    ... 
}

这甚至都不正确。在 Java 中,您必须使用 equals() 而不是 == 进行 String 比较:

if ("OPTIONS".equals(request.getMethod())) {    
     ... 
}

我可以使用任何枚举或类来引用吗?

HttpServlet 类中,您会找到一些 HTTP 方法的常量,但它们是私有的,因此您将无法使用它们。

如果您使用的是 JAX-RS,则可以使用 HttpMethod 中定义的常量。为DELETEGETHEADOPTIONSPOSTPUT 方法定义了常量。从 JAX-RS 2.1 开始,PATCH 的常量将可用。

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多