How to access url parameters in Action classes Struts 2

后端 未结 4 1455
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 07:39

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

相关标签:
4条回答
  • 2020-12-15 07:50

    Try this:

    ActionContext context = ActionContext.getContext();
    Map<String, Object> params = context.getParameters();
    String userId = findParam("idUser", params);
    
    public String findParam(String key, Map<String, Object> params) {
      Object obj = params.get(key);
      if(obj != null) {
        String[] values = (String[])obj;
        return values.length > 0 ? values[0] : null;
      } 
      return null;
    }
    
    0 讨论(0)
  • 2020-12-15 07:51

    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

    0 讨论(0)
  • 2020-12-15 07:58
    public class MyAction extends ActionSupport {
        HttpServletRequest request;
        String idUser = request.getParameter("idUser");
        System.out.println(idUser);
    
    }
    

    Try this!

    0 讨论(0)
  • 2020-12-15 08:00

    Well, I'm not a Struts expert, but what I do in my Struts 2.2 project (and it works ok) is:

    String paramValue = ServletActionContext.getRequest().getParameter("paramName");
    

    Here paramName would be "idUser".

    0 讨论(0)
提交回复
热议问题