Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice? Where do I put configuration parameters for my own application in Struts2?

Tags:

java

struts2

In Java servlet, there is <context-param>. In desktop applications, we usually define our own configuration file.

Where should I put configuration parameters for my Struts2 application? For example, my application needs to set a time limit for user input, or save and read files stored somewhere, or the maximum time the user can type a wrong password, etc. I want those things configurable.

What's the way people usually do it in Struts2 applications? Any best practice?

like image 341
Haozhun Avatar asked Sep 02 '11 17:09

Haozhun


People also ask

What are best practices to follow while developing Struts 2 application?

Some of the best practices while developing Struts2 application are: 1. Always try to extend struts-default package while creating your package to avoid code redundancy in configuring interceptors. 2. For common tasks across the application, such as logging request params, try to use interceptors.

What are the different configuration files are required to develop any struts application?

The struts application contains two main configuration files struts. xml file and struts. properties file.

Which of the following is true in the life cycle of a request in Struts 2 application?

Q 10 - Which of the following is true in the life cycle of a request in Struct2 application? A - Selected action is executed to perform the requested operation.


1 Answers

If you are familiar with the ServletContext approach that you mentioned, you can stick with that. In your web.xml, just add your <context-param>s.

Then, to get the ServletContext in your actions, just implement ServletContextAware and it will be automatically injected for you.

Here's a brief example:

web.xml

<context-param>
  <param-name>someSetting</param-name>
  <param-value>someValue</param-value>
</context-param>

Your Action

public class YourAction extends ActionSupport implements ServletContextAware {
  private ServletContext servletContext;

  @Override
  public String execute() throws Exception {
    String someValue = (String) servletContext.getAttribute("someSetting");

    return SUCCESS;
  }

  @Override
  public void setServletContext(final ServletContext context) {
    this.servletContext = servletContext;
  }
}
like image 71
Steven Benitez Avatar answered Sep 27 '22 19:09

Steven Benitez