Can I configure Spring in 开发者_如何转开发such a way that I add a property, "isHttps" to the request, and this property can be accessed from anywhere in the code, e.g. a bean class:
public class MyItem{
public String getImageUrl(){
if (isHttps){
//return https url
}
//return http url;
}
}
I can do this using ThreadLocal, but I would like to avoid taking that route.
Another alternative:
You can get the current request as follows:
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();
This uses thread-local under the covers.
If you are using Spring MVC that's all you need. If you are not using Spring MVC then you will need to register a RequestContextListener or RequestContextFilter in your web.xml
.
Create a request-scoped bean
<bean id="requestBean" class="com.foo.RequestBean" scope="request"/>
Then in that class, autowire the request (reference here):
@Autowired
private HttpServletRequest request;
Add a method in RequestBean that determines if the request is HTTPS.
public boolean isHttp() { // ... }
Then inject requestBean into your other beans that need to call isHttp().
精彩评论