当HttpServletResponse / HttpServletRequest作为方法参数添加时,Spring请求会挂起

时间:2015-08-13 07:25:24

标签: java rest spring-mvc spring-boot

按照spring.io为creating a simple REST service提供的示例,我遇到了一个奇怪的问题。

如果我向localhost:8080/greeting发出请求,则会调用问候路线并收到预期的回复:

{"id":1, "content":"Hello, World!"}

如果我添加路线" / test"然后向localhost:8080/test发出HTTP GET请求我得到了预期的响应:

I'm a teapot

当我做两件事之一时会出现问题。首先,如果我将HttpServletResponse或HttpServletRequest作为参数添加到测试路由并向localhost:8080/test发出HTTP GET请求,请求挂起,路由不会被调用/执行,并且可能但不总是返回以下内容:

BODY: OK STATUS CODE: UNKNOWN 43

第二种情况是我尝试使用@Autowire注释来克服这个问题。如果我删除HttpServletResponse / HttpServletRequest方法参数,而是将它们作为类成员自动装配,我会得到相同的行为。

如果我向任何其他无效/未定义的路线发出请求,例如HTTP GET localhost:8080/undefinedroute我收到了预期的404。

package hello;

import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    //@Autowired
    //HttpServletRequest request;

    //@Autowired
    //HttpServletResponse response;

    @RequestMapping("/test")
    public String index() {
       return HttpStatus.I_AM_A_TEAPOT.getReasonPhrase();
    }

    //@RequestMapping("/test")
    //public String index(HttpServletResponse response) {
       //response.setStatus(HttpStatus.I_AM_A_TEAPOT.ordinal());
       //return HttpStatus.I_AM_A_TEAPOT.getReasonPhrase();
    //}

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

1 个答案:

答案 0 :(得分:0)

您无法自动装配HttpServletRequest或HttpServletResponse,因为这些对象是在服务器接收并处理HTTP请求时创建的。它们不是Spring应用程序上下文中的bean。

由于此行,您的回复状态代码为43(未知):

response.setStatus(HttpStatus.I_AM_A_TEAPOT.ordinal()); // status 43?

ordinal()为您提供枚举声明的位置,而不是状态代码的值。 I_AM_A_TEAPOT是在HttpStatus中声明的第43个枚举。请求挂起,因为43是无效的状态代码,您的浏览器不知道如何处理它。你应该使用:

response.setStatus(HttpStatus.I_AM_A_TEAPOT.value()); // status 418
相关问题