18

I've got the URL like this:

http://test.com/testapp/test.do?test_id=1&test_name=SS

Is there any way we can get only this part

/test.do?test_id=1&test_name=SS

4
  • 6
    "Is there any way we can get only this part" - Yes. Commented Feb 4, 2014 at 6:59
  • yes ofc. What are you using. Servlets or Spring MVC? Commented Feb 4, 2014 at 7:00
  • 1
    docs.oracle.com/javase/7/docs/api/java/net/URL.html Commented Feb 4, 2014 at 7:01
  • "testapp" is your application context, "test.do" the operation you are executing and the rest - request parameters. Since we don't know what framework you are using (looks like struts but...) ther is no clear answer. Give some more information. Commented Feb 4, 2014 at 7:02

3 Answers 3

32

Use java.net.URL to parse a url string:

URL url = new URL("http://test.com/testapp/test.do?test_id=1&test_name=SS");
System.out.println(url.getPath()+"?"+url.getQuery());
Sign up to request clarification or add additional context in comments.

2 Comments

but it returns /testapp/test.do?test_id=1&test_name=SS
Note: new URL(String) is deprecated since Java 20. It's better to use URI.create("http://test.com").toURL()
1

Inside your ActionClass

String actionName = (String)ActionContext.getContext().get(ActionContext.ACTION_NAME);

will give you "test".

HttpServletRequest request = ServletActionContext.getRequest();

is your servlet request where from you can get all the parameters. Anyway, take a look at ActionContext.getContext(). Lot of thing you can get from there. Hope this helps.

2 Comments

ActionContext is not a generic class. Please, avoid this answers type.
@atrujillofalcon, I don't agree. But even so, after the critisism, can you propose something that do the job? Believe me, I know what I'm talking about - I had the same problem, very rare situation btw, in my real job and that was the best way to achieve it.
1

Not really URL parsing but this would do your job:

String[] parts = "http://test.com/testapp/test.dotest_id=1&test_name=SS".split("/");

return "/"+parts[parts.length-1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.