Access url parameters in Action classes Struts 2 in AJAX call?

和自甴很熟 提交于 2020-12-06 07:01:46

问题


I know that 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+)

However, when I do this in an AJAX call like this:

 $.ajax({
    url: '/gma/getJSONData.action?tspName='+tspName+'&thresholdType='+thresholdType,

I don't get the tspName parameter inside action class. I created the getter/setter for it. It's displaying null value.

Am I wrong somewhere?

EDIT: I was checking the value of tspName in my Action class constructor, so was printing null. However, in my execute method it displays the value correctly. Why is it so? It means before constructor call it does not initialize values?


回答1:


I was checking the value of tspName in my Action class constructor, so was printing null. However, in my execute method it displays the value correctly. Why is it so?? It means before constructor call it does not initialize values?

Probably you should learn the basics how Struts2 works. When you make a request a filter is invoked and the dispatcher is handling the request via creating the action context and building action instance.

Then interceptors are invoked on this action. One of the interceptors of the defaultStack is params interceptor. It's responsible to populate your action with request parameters, to be more Struts2 action context parameters.

It means you can always get parameters from the action context. See How can we access request parameters passed into an Action.

The constructor of the action is called before any interceptor is invoked, so the action is not populated yet and properties aren't initialized. On the other hand when the action is executed all interceptors are already invoked, so the action is populated. Before constructor or after constructor it doesn't matter. What is matter is params interceptor in the action configuration.

You can always get parameters like described in the link above, or directly from the servlet request like in this answer. All features of Struts2 framework is available to you.



来源:https://stackoverflow.com/questions/20322322/access-url-parameters-in-action-classes-struts-2-in-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!