spring mvc의 controller에서 method 에 parameter를 추가하지 않고 HttpServletRequest를 받아오는 방법이 있나요?
조회수 7824회
spring mvc의 controller 에서 HttpServletRequest를 받아오려면 아래처럼 함수의 parameter를 추가하면 되는 걸로 알고 있습니다.
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Map<String, Object> model) throws IOException {
...
}
->
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpServletRequest request, Map<String, Object> model) throws IOException {
request.doSomething();
}
그런데, 혹시 이렇게 parameter를 추가하지 않고 controller 함수 내에서 그냥 request를 꺼내서 쓸 수 있는 방법은 없을까요? spring 에선 ThreadLocal을 많이 쓰던데, 어딘가엔 request 저장해놨을 것 같은데 찾을 수가 없네요.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
첫 번째 방법은 다음과 같습니다. (Spring 2.0 이상)
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest();
예시
@RequestMapping(value = "/", method = RequestMethod.GET) public String index() throws IOException { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); // do something ... }
두 번째 방법은 다음과 같이 클래스의 멤버에 선언하고 Wiring 하는 방법이 있습니다.
@Autowired(required=true) private HttpServletRequest request;
댓글 입력