Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

servlets - Accessing HttpServletRequest object in a normal Java class from Spring

I have a normal Java class in a Spring MVC 3.06 web application.

In this class I would like to inject or get hold of the HttpServletRequest object in a method.

I know I can pass this around, but I was wondering how can I get hold of the request without passing it in to the method. Perhaps using annotations or similar?

Also, what are the "real" concerns with getting hold of the request this way, except some peoples opinions of it being ugly coding. I mean, is it unstable to access it this way?

Preferably non application server dependent way.

I have seen

(HttpServletRequest) RequestContextHolder.getRequestContext().getExternalContext().getNativeRequest() 

but this doesn't seem to work for Spring MVC 3.06 . RequestContextHolder doesn't have the method getRequestContext().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

I'm not sure where you got RequestContextHolder.getRequestContext(), that's completely wrong.

is it unstable to access it this way?

No, it's stable enough, assuming you're always running the code as part of an HttpServlet request thread. The main issue is that yes, it's ugly, and it makes your code hard to test. That is reason enough not to use it.

If you must use it, then decouple it from your code, e.g.

public void doSomething() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    doSomething(request);
}

void doSomething(HttpServletRequest request) {
   // put your business logic here, and test this method
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...