Reputation: 15
What's the difference between localhost/user/user123
, localhost/user?user=user123
and localhost/?user=user123
?
How to get the parameter user123
from a URL localhost/user/user123
in servlet?
Thanks in advance
Upvotes: 0
Views: 2823
Reputation: 4873
You can parse from the getPathInfo() of HttpServletRequest Object.
sample code
String urlPath = request.getPathInfo();
System.out.println("" + urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()- 1));
Upvotes: 3
Reputation: 39
localhost/user/user123
- this url will be handled by pattern /user/user123
localhost/user?user=user123
- this url will be handled by pattern /user
, with user
parameter set to user123
(for GET request)localhost/?user=user123
- this url will be handled by pattern /
with user
parameter set to user123
(again, for GET)I don't know how to retrieve user123
from url localhost/user/user123
with pure servlets, but it's pretty easy with web MVC frameworks. Spring example:
@Controller
@RequestMapping("/user")
public class Controller {
@RequestMapping(value = "/{user}")
public String getUser((@PathVariable String user) {
//here variable "user" is available and set to "user123" in your case
}
}
Upvotes: 0
Reputation: 1270
Generally you pass parameters like
/localhost/Servlet?parameter1=one
or for a JSP
/localhost/mypage.jsp?parameter1=one
In a servlet you can access the parameters by using the request object. So generally like this:
String parameter1 = request.getParameter("parameter1");
Here is some detail on getParameter for HttpServletRequest
Hope this helps.
Upvotes: 0
Reputation: 15758
These all are accessible from Servlet API. Check HttpServletRequest, you can access all information from there.
The actual values may differ how your webapp was deployed, but usually
localhost
is the Context Path?
is the Query String - you have to parse it, if you want to useUpvotes: 0
Reputation: 315
localhost/user/user123 looks like a RESTful way to identify a resource.
The two others aren't, I think.
Upvotes: 0