Struts 2 - Sending mail with embedded URL

℡╲_俬逩灬. 提交于 2019-11-29 05:06:46

You need to create the properties (dependencies) in your action

@Inject
public void setActionMapper(ActionMapper actionMapper) {
  this.actionMapper = actionMapper;
}

private UrlHelper urlHelper;

@Inject
public void setUrlHelper(UrlHelper urlHelper) {
  this.urlHelper = urlHelper;
}

then in the action you could write something like

Map<String, Object> parameters = new HashMap<>();
ActionMapping mapping = new ActionMapping("action", "namespace", "", parameters);
String uri = actionMapper.getUriFromActionMapping(mapping);
String url  = urlHelper.buildUrl(uri, ServletActionContext.getRequest(), ServletActionContext.getResponse(), parameters, "http", true, false, true, false);

You may take a look at Struts' UrlProvider.determineActionURL, which does what you need.

UPDATE Indeed I needed to use this method some weeks ago and I remember some NPE's rising around... At the end, I was able to write the following code (adapted from my app):

String getMyActionUrl() throws Exception {

    ActionInvocation invocation = (ActionInvocation) ActionContext
            .getContext().get(ActionContext.ACTION_INVOCATION);

    org.apache.struts2.components.URL url = new org.apache.struts2.components.URL(invocation.getStack(), getServletRequest(),
            getServletResponse());
    url.addParameter("parameterToBeDeleted", null);
    url.addParameter("newParam", newValue);
    url.setActionMapper(new DefaultActionMapper());
    url.setUrlHelper(new DefaultUrlHelper());

    String myUrl = url
            .getUrlProvider()
            .determineActionURL(
                    "MyActionName",
                    invocation.getProxy().getNamespace(),
                    invocation.getProxy().getMethod(),
                    getServletRequest(),
                    getServletResponse(),
                    getServletRequest().getParameterMap(),
                    "http",
                    true, true, false, false);

    return myUrl;

}

Notes:

  • MyActionName is here as a String -- not a great maintanable code. Make sure it matches the name you give to the action (which may differ from the name of the Action class handling calls to that action).

  • http is hardcoded. Change if needed.

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