Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access url parameters in Action classes Struts 2

I'm new to Java EE and Struts2. I need to know if I'm doing it wrong or not.

I've got a link like this : http://localhost:8080/myProject/deleteUser?idUser=42

All I want is to get the idUser value.

Here is what I use to get the parameter value in my action class :

HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
                                  .get(ServletActionContext.HTTP_REQUEST);
System.out.println(request.getParameter("idUser"));
like image 414
SupaCoco Avatar asked Mar 06 '12 11:03

SupaCoco


People also ask

How can I access URL parameters?

For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object. By using Separating and accessing each parameter pair.

How can we access request parameters passed into an action?

You can obtain the request parameters by asking the ActionContext or implementing ParameterAware. Implementing ParameterAware is preferred.

How do URL parameters work?

What Are URL Parameters? Also known by the aliases of query strings or URL variables, parameters are the portion of a URL that follows a question mark. They are comprised of a key and a value pair, separated by an equal sign. Multiple parameters can be added to a single page by using an ampersand.


1 Answers

S2 provides a clean way to fetch the request parameters in you action class all you need to follow these simple rules.

  1. Create a property with same name as request parameter name.
  2. create getter and setters for this property or make property public (for S2.1+)

S2 will check the request parameter and will look for matching property in your action class and will inject the value in respected property.

in your case all you need to do

public class MyAction extends ActionSupport{

 private String idUser;
 getter and setters   

}

So in this case S2 will find the idUser property in your action class and its build in interceptor will inject the value in the idUser property

like image 54
Umesh Awasthi Avatar answered Oct 21 '22 04:10

Umesh Awasthi