what's different between servlet url path and parameter? - java

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

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));

localhost/user/user123 looks like a RESTful way to identify a resource.
The two others aren't, I think.

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
the String after that is the Servlet PAth
the parameters after the ? is the Query String - you have to parse it, if you want to use

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.

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
}
}

Related

How to hide the parameter values in url

I am working on a project using hibernate and Spring MVC architecture.
My problem is that I am using (*.htm) url pattern in my web application , in this case when I sent a product's id to controller for editing, the product's id is shown in url for eg.
"localhost:8080/MyApp/editProduct.htm?productId=03".
But I don't want this . I just want
"localhost:8080/MyApp/editProduct.htm?productId" or "localhost:8080/MyApp/editProduct.htm/productId/03"
and I am unable to use #PathVariable Annotation in my controller because of my url pattern(*.htm) and using of #PathVariable Annotation the JSP page never load properly.
Any Suggestions . Thanks in Advance.
Controller:-
#RequestMapping(value = "/{sId}/deleteState.htm")
public ModelAndView deleteState(#PathVariable("sId") int sId ){
ModelAndView mav = new ModelAndView();
try{
stateDAO.deleteById(sId);
mav.addAllObjects(prepapareModel());
mav.addObject("msg", "State Deleted Succesdfully");
mav.setViewName("admin/viewState");
return mav;
}catch(Exception e){
e.printStackTrace();
mav.addAllObjects(prepapareModel());
mav.addObject("err", "Failed to Delete State");
mav.setViewName("admin/viewState");
return mav;
}
}
public Map prepapareModel(){
Map map = new HashMap();
map.put("states", stateDAO.findAll());
return map;
}
Url after deleting the State from database:-
http://localhost:8080/PujaInBox/10/deleteState.htm
I think the Id of State is creating the problem . 10 is Id of state.
If you want to make use of #PathVariable annoation, then URL should be
/MyApp/productId/03/editProduct.htm - ending with your extension and your controller mapping should be like this
#RequestMapping(value="/productId/{id}/editProduct")
public String editProduct(#PathVariable String id, Model model) {
}
One more change to note here is that I mentioned a relative URL instead of absolute URL like localhost:8080/MyApp/productId/03/editProduct.htm including host name and port. This won't work when you deploy your application in an actual server because localhost always refers to your current machine but your application is deployed on some other host.
Hope that makes sense :)
Change servlet default url pattern to:
<servlet-mapping>
<servlet-name>servlet_name</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
But in this situation better option is to manage your #PathVariables in the middle part of URL, like:
/myapp/product/{productId}/edit.html
I am doing an assignment in a class.
I am guessing the first step is to use wildcard (*) to map your URL. In your pages, you can use whatever the URL you prefer.
Then you can invoke the method getPathInfo() in your servlet.
String action = request.getPathInfo();
Or you can call getHeader("referer") to get your URL then manipulate your string to get the information you need.
Finally, you can put the string in your if-else or switch statement.
All you have to do is create a form in your html page with method=post
<form method="post">
Then create fields inside this form and if you don't have any fields that should be displayed used input with type hidden.
<input type="hidden" name="parametername" id="parameterid" value="parametervalue">
This will do the trick, it won't show any parameter value in the URL and you can access the values as you already do.
Hope this helps....

Spring mvc rewrite url "myapp.com/Foo/12345/test-one" to "myapp.com/Foo/12345/test-one-a-b"

I want to use a normal spring mvc controler and request mapping using path variables.
I do not want to forward or redirect, just change the string that user sees.
#RequestMapping(value = "/Foo/{id}/*", method = RequestMethod.GET)
public ModelAndView getFoo(#PathVariable final String friendlyUrl) {
//how can I rewite the url that user sees ?
}
(the same behaviour as when you change the title of an existing question on stackoverflow)
If you watch the traffic in wireshark, firebug or something you see, that stackoverflow sends a HTTP 301 Moved Permanently to the final URL.
You could do the same.
For this you need the HttpServletResponse, you can add it to the method signature to get it injected.
Set the permanent redirect:
String rightUrl = urlCompleter.complete(friendlyUrl);
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", rightUrl);
Where you need to implement urlCompleter on your own, eg. look in the database table of entries and locate the right url component.

Setting parameters in jsp and in servlets

In my web application , I get a request from the client. I process the request in my jsp page or the servlet(which ever is called) and want to forward to other jsp's or servlets accordingly. But before forwarding I want to set a few parameters and then forward it with these new parameters. The old parameters should not be present when forwarding. Only the new parameters should be present. How can this be done?
Can I forward from a servlet to jsp and vice-versa?
Please tell how the above can be accomplished?
If you have no use for the request parameters and your jsp/servlet has not written anything to the response, then I suppose it would be fine to use redirect instead of forward, since redirecting will discard the request along with the parameters.
When you do redirect, you can create dynamically and set the querystring like so:
response.sendRedirect("url?a=" + var1 +"&b=" + var2);
Take note that this will be a GET method to the url. If url will be resolved to a servlet, you can implement the doGet method to just call the doPost.
Please note that a redirect will be ignored if the jsp/servlet has written something already on the response...
You can use request dispatcher and redirect as per your need and requirement.
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("url");
rd.forward(request,response);
or
response.sendRedirect("url");
sendRedirect() sends the header back to the browser , which contains the name of the resource to be redirected to. So this will be a new request to the resource from the browser .
forward() action takes place within the server without the knowledge of the browser .
yes you can forward the parameter servlet to jsp and jsp to servlet.
when you can set the attribute in request then it will lost on destination.means you can not access that on third resource.
request.setAttribute(attribute name,attribute value)
you can do same thing in session also.
You have to forward to JSP/Servlet using RequestDisptcher. Set the request attribute on the request to set parameters using
request.setAttribute(name, value)
The Forwarded JSP can read the parameter using
request.getAttribute(name)
But, You cannot hide the attribute existing before forward by default. You can achieve this using Request Wrapper. Wrap the request before forwarding override the set and get attribute methods.
Below code explains
RequestDisptcher dispatcher = req.getRequestDispatcher("url");
HideExistingRequestWrapper requestWrapper =
new HideExistingRequestWrapper(request);
requestWrapper.setAtribute("forwarded", "forwarded value");
dispatcher.forward(requestWrapper, response);
Here is the code of wrapper implementation:
class HideExistingRequestWrapper extends HttpServletRequestWrapper {
private Map localattributes = new HashMap();
public HideExistingRequestWrapper (HttpServletRequest orignialRequest) {
super(orignialRequest);
}
public Object getAttribute(java.lang.String name) {
return localattributes.get(name);
}
public Object setAttribute(java.lang.String name, java.lang.String value) {
return localattributes.put(name, value);
}
}
use
ServletRequest.removeAttribute(name of your old attribute)
ServletRequest.setAttribute(name , value)
After setting the attributes, get the RequestDispatcher using
getRequestDispatcher(url)
and then use forward() method

How to find the base URL of the current webapp in Spring?

I'd like to find the absolute URL of the webapp in Spring, from the Controller. I'm aware of JSTL c:url, but I need this info from inside the Controller.
#Controller
public class AuthorizeController {
#Autowired
private Authorizer auth;
#RequestMapping("/auth")
public String sendToAuthorization() {
String baseUrl = "http://localhost:8080/tasks/";
return "redirect:" + auth.getAuthorizationUrl(baseUrl);
}
}
As you can see the baseUrl is hardcoded, and I could provide it to the Authorizer class via Spring configuration, but I am sure that it's possible to get this information from Spring within the Controller. I tried to google "spring mvc url" and could not find a way to solve this problem.
I think that getting absolute url is only possible while processing the request as your server may have many IP addresses and domain names.
#RequestMapping("/auth")
public String sendToAuthorization(HttpServletRequest request) {
String baseUrl = String.format("%s://%s:%d/tasks/",request.getScheme(), request.getServerName(), request.getServerPort());
return "redirect:" + auth.getAuthorizationUrl(baseUrl);
}
As for the servlet, it may also have several mappings in web.xml.
similar question
P.S. Anyway, url parsing in runtime does not look like a good idea to me.
Very late to this answer, but a variant to Boris's answer, if you don't want to push servlet objects into method signatures, is to use RequestContextHolder from a utility class/method. This would also give the ability to abstract fallback logic (e.g., pulling from a property file). Cheesy example:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(null != requestAttributes && requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
// build URL from request
}
else {
// fallback logic if request won't work...
}
This presumes you have org.springframework.web.context.request.RequestContextListener registered as a listener in web.xml

Tapestry internal redirection to static page

I just want a Tapestry page to redirect to a static page like this :
http://www.myWebSite.com/home/myPage.tml
-> http://www.myWebSite.com/static/myStaticPage.html
I try to do this by returning a new URL, but i need to know the web site address for that (http://www.myWebSite.com/). So, i would like to know how to do this without knowing the web site address ?
Thank you.
You can inject (using #Inject) the HttpServletRequest directly in your page directly, without using RequestGlobals, and use its getServerName() method to get the server name. Not tested:
#Inject
private HttpServletRequest request;
Object onActivate() {
return new java.net.URL("http://" + request.getServerName() " + "/myStaticPage.html");
}
Found : using the RequestGlobals service
String baseUrl = requestGlobals.getHTTPServletRequest().getRequestURL().toString().replaceFirst(requestGlobals.getHTTPServletRequest().getRequestURI(), "");
Just use it to build your URL string put it in a URL instance.

Categories

Resources