Why use ServletRequestAware instead of ServletActionContext?

╄→гoц情女王★ 提交于 2020-12-04 04:59:56

问题


To get a servlet request in Struts 2 we can use either ServletRequestAware or ServletActionContext. However, in a particular internet resource, it is told that ServletRequestAware should be used instead of ServletActionContext.

Does that have something to do with the fact that ServletActionContext will be a shared resource in a multi-threaded environment or is there any other reason behind this?


回答1:


The ServletActionContext is a helper class that contains only static methods, one of them used to retrieve servlet request from action context. But action context is ThreadLocal, so it can't be shared in multi-threaded environment.

There's also no multi-threded environment per request in Struts2, except a background thread used by the executeAndWait interceptor.

The reason to use ServletRequestAware is because it's guaranteed method to obtain a servlet request object if servletConfig interceptor is included in the stack.

You can use ServletActionContext from anywhere, but it doesn't guarantee that a request object instead of null will be returned.




回答2:


ServletRequestAware is a better approach because it decouples action methods from static accessors.

In order to test something using ServletActionContext you need to mock static methods and mock the request. To test ServletRequestAware methods you only need to mock the request.

While tools exist that make mocking static methods easier, it's easier yet to implement the interface and pass in a mocked request. This is the reason ServletRequestAware exists.



来源:https://stackoverflow.com/questions/26699019/why-use-servletrequestaware-instead-of-servletactioncontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!