How to receive and get parameters from the URL in struts2?

Member

by dorothea , in category: SEO , 2 years ago

How to receive and get parameters from the URL in struts2?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

Member

by dortha , 2 years ago

@dorothea 

In Struts2, you can receive and get parameters from the URL in the following ways:

  1. Using Action class: You can retrieve URL parameters using the getParameters method of the Action class in Struts2.
1
Map<String, String[]> params = ServletActionContext.getRequest().getParameterMap();


  1. Using OGNL: You can access URL parameters using OGNL expressions in your JSP pages.
1
<s:property value="#parameters['paramName']"/>


  1. Using ModelDriven: You can use a model driven approach, where you can define a model class and bind the request parameters to its properties.
1
2
3
4
5
6
public class MyAction extends ActionSupport implements ModelDriven<MyModel>{
   private MyModel model = new MyModel();
   public MyModel getModel() {
      return model;
   }
}


You can then access the URL parameters using the properties of the MyModel class in your JSP pages.

by clarabelle , 2 years ago

@dorothea 

In Struts2, you can receive parameters from the URL by using the Action class and the get and set methods. Here's a simple example:

  1. Define an action class that implements the Action interface:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class ExampleAction implements Action {

    private String parameter;

    public String getParameter() {
        return parameter;
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    @Override
    public String execute() throws Exception {
        // Use the parameter in your logic here
        return SUCCESS;
    }
}


  1. Configure the action in the struts.xml file:
1
2
3
4
<action name="example" class="com.example.ExampleAction">
    <param name="parameter">{parameter}</param>
    <result name="success">/example.jsp</result>
</action>


  1. Pass the parameter in the URL, for example: http://localhost:8080/example?parameter=value
  2. The parameter value can then be accessed in the JSP page using the parameter property of the action:
1
<s:property value="parameter"/>


In this example, the parameter value from the URL is automatically set in the ExampleAction class using the setParameter method. The execute method then returns the SUCCESS result, which is mapped to the example.jsp page in the struts.xml configuration file. In the JSP page, you can use the s:property tag to access the parameter value and display it on the page.