开发者

How do I get Web.xml context-param values in controller action method?

开发者 https://www.devze.com 2023-02-23 08:12 出处:网络
This feels l开发者_StackOverflowike a basic question, but I haven\'t had much luck Googling. My app connects to an SMTP server and sends mail through it. I need this SMTP server to be configurable ba

This feels l开发者_StackOverflowike a basic question, but I haven't had much luck Googling.

My app connects to an SMTP server and sends mail through it. I need this SMTP server to be configurable based on which environment the app is deployed to.

How can I specify the specify the SMTP server name in my web.xml config file and access it from my Spring MVC 3.0 controller?

The controller does not extend or implement anything. It is completely annotation driven with @Controller and @RequestMapping. From what I have seen online, people access context-params via the servlet API. Being annotation driven, I do not have access to the servlet object.


I solved this.

Make your controller implement ServletContextAware, which requires a method called

setServletContext(ServletContext servletContext)

Spring MVC will inject the servlet context into this method if your controller is ServletContextAware.

Create a private variable on your controller to store the servletController that is injected into the above method. You can now use servletContext just as you would if you were using a regular servlet.

hth.


Adding an instance of Servletcontext and autowiring it worked for me

@Controller
public MyController {

// other instances relevant to your requirement

    @Autowired
    private ServletContext sCtx;

//other methods relevant to your requirement

}


I suppose following also should work:

void action(final HttpServletRequest request) {
    final paramValue = request.getSession().getServletContext().getInitParameter("paramName");
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号