阳光Emi
阳光Emi

Reputation: 143

How to get action URL in JSP using Struts 2?

I have the URL: http://demo.lendingclub.com/account/summary.action.

When visit this URL, it will first go to the authenticate interceptor, in the interceptor class, If I use:

String uri = req.getRequestURI();

it will return /account/summary.action

But, if I use it in JSP:

<%
    HttpServletRequest req = ServletActionContext.getRequest();
    String uri = req.getRequestURI();
%>

it will return : /mainapp/pages/account/summary.jsp

Why they're different, and how can I get action URL in JSP?

Upvotes: 4

Views: 9966

Answers (2)

Quaternion
Quaternion

Reputation: 10458

The easiest way to get the current actions url is: <s:url/> if you supply namespace and action parameters you can make it point at other actions but without these parameters it defaults to the current url.

Upvotes: 6

Roman C
Roman C

Reputation: 1

You could get the action URL or any other value if you set property to the action, and then retrieve that property from the value stack via OGNL.

private String actionURL;

public String getActionURL(){
  return actionURL;
}

the code to calculate the action URL is similar you posted to the comments

public String getPath(){
  ActionProxy proxy = ActionContext.getContext().getActionInvocation().getProxy();
  String namespace =  proxy.getNamespace();
  String name = proxy.getActionName();
  return namespace+(name == null || name.equals("/") ?"":("/"+name));
}

this code is not supported .action extension, if you need to add the extension to the path then you need to modify this code correspondingly.

then write your action method

public String excute() {
   actionURL = getPath();
   ...
   return SUCCESS;
}

in the JSP

<s:property value="%{actionURL}"/>

you have been used dispatcher result to forward request to the JSP as a result you get the URI pointed to the JSP location.

Upvotes: 2

Related Questions