Get more servlet request variables using wildcards [duplicate] - java

This question already has answers here:
Wildcard path for servlet?
(2 answers)
Closed 7 years ago.
I'm sorry, I come from a PHP web world.
I'm used to using a router in frameworks like Laravel to send to controllers and get parameters. I know how to get get and post parameters using servlets by routing things with the web.xml servlet-mapping and using * wildcards, but am unfamiliar with how to get those url wildcards with the HttpServletRequest variable passed through doGet or doPost.
Is there anything where I can grab the wildcards of those urls, such as, if the url was a username or a particular page I didn't want to hard code into the web.xml? I'm sure there is.
Id like to know things like what I can get in PHP's $_SERVER variables for reading data about the incoming request. Stuff like cookies are also needed. Can someone give me a quick pointer with Java Servlets?
EDIT:
Or maybe I should just stick the variables to where variables belong and not make "pages" out of fake variables. I'm also open to that idea as well.
My main problem is that I don't know how to get url wildcards in doGet or doPost after it's routed from web.xml, so I'd either like to know how or be told that's a stupid thing to do and not do it at all.

Check out Spring MVC. With Spring Controllers you get to do URL paths like
#RequestMapping("/fixed/{id}/{user}")
public String getSomeData(#PathVariable("id") String id, #PathVariable("user") String user) {
...
}
or even
#RequestMapping("/{id}/**")
public void doSomething(#PathVariable("id") int id, HttpServletRequest request) {
String remainingUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}

Related

Dynamic URL from database and MVC in JSP

I am learning JAVA and Spring Framework. I wanted to know that is it possible in java to create Dynamic URL in spring framework using values from url and fetching from database.
I am trying to make URL Shortner in Java and I will need to lookup for url's short code in my database and as we all know, url shortner will look like "url/ShorTCode" and my script will look for "ShorTCode" keyword in database and will redirect to associated weblink.
So I wanted to know that is it even possible in JAVA and Spring? And one more thing, if I make something like this "url/yt/VIdeoCode" or "url/fb/UserProfile"
So it will look at yt object which will redirect to youtube link only and fb object which will redirect to facebook user profile.
I want to clarify that I am still learning JAVA, JSP and Spring but I want to keep this thing in my mind while I am learning so I can focus on some particular things.
Thank you all fro helping me.
If you're asking how your controller could respond with a dynamic redirect, the answer is either:
(1) Have the controller return a "redirect:" result instead of view name. It must be followed with an absolute url, and behavior might depend on your spring version and configuration, but basically it looks like this:
#RequestMapping(...)
public String myMethod(){
String url=... // database lookup, e.g. "http://myUrl"
return "redirect:"+url;
}
(2) Less elegant but sometimes useful: get direct access to the response. If your controller method has a parameter of type HttpServletResponse spring will automatically inject it. So:
#RequestMapping(...)
public String myMethod(HttpServletResponse resp){
...
response.sendRedirect(...)
}

Alternative of URL parameter for deciding which method to call

Right now based on the site name in the URL parameter, we decide the appropriate actions to take(method calls etc) in the Java (Standard Jsp/Servlet web applications). For example, the request would be something like www.oursite.com?site=Ohio
Wondering what would be the alternative of doing this without having to provide URL parameter.
You could use POST instead of GET.
GET appends request parameters to the end of the URL.
POST sends encoded data using a form.
http://www.tutorialspoint.com/jsp/jsp_form_processing.htm
Why not just code it into the path?
www.oursite.com/Ohio
If you're just using straight servlet api, you can just do something of this nature:
String path = request.getPathInfo();
String site = path.split("/")[0];
That being said, most web frameworks have some support for helping with this.
For example, in spring mvc:
#RequestMapping(value="/{site}/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
Of course you could do this at the controller level too if all your methods need that sort of mapping:
#Controller
#RequestMapping(value="/{site}")
public class MyController {
#RequestMapping(value="/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
}
I believe this is cleaner than a query param, though it still shows up in your URL. There's other, more complex methods like using apache's reverse proxying and virtual host capabilities to switch based on site names. You could do something at login, and store the site in session. It all depends on your requirements.
You could use an alternate URL, like ohio.oursite.com. This process could be automated by having your server respond to *.oursite.com. I would probably set up a filter that looked at what the subdomain was and compared that with a predefined list of allowed sites. If it didn't exist, you could redirect back to the main (www) site. If it did, you could set a request attribute that you could use in a similar way that you currently use the request parameter now.

How servlet handle multiple request from same jsp page

Sorry friends if this question is very easy but i am confuse i unable to find out solution.
As we all know in spring MVC framework we create controller which will handle multiple request from same page using #requestmapping annotation.
but same thing i want to do in servlet how can i do ?
Suppose i have a jsp which which will contain a jqgrid,and two forms i want to use only one servlet to load the data into jqgrid and that servlet only will handle request from both the form . Since we have only doGet and doPost in servlet how one servlet fulfill all three request. Hope you understand my question if you have and link where i get sample or and tutorial link plz reply me
Well, the only easy way to do this would be to use a request parameter to control how the processing happens.
In a very basic example, you may have something like a requestType value that gets passed as either part of the query string or the request body. You would assign values of 1-3 (or 0-2) with each value indicating a different type of request. Your servlet would then parse the request accordingly.
This actually is how the DispatcherServlet in SpringMVC works. There's only one servlet class instance and when a request comes in, it examines the query string along with other parts of the request to determine which controller should handle the request.

Why does getAttribute() in HttpServletRequest works for GET method but not for POST method?

I'was debugging a client-side AJAX problem that is making request to servlet. But the bug turned out to be at server side. You can refer to my original question here. From the discussion with more experienced people, I found out that servlet is using request.getAttribute() method to retrieve parameters from the request instead of getParameter(). So I thought to open a new question to clear my doubt.
Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?
You should always use getParameter, when attribute come from GET or POST method. And use getAttribute when request is forwarded from another servlet/jsp. Such as :
ServletA:
request.setAttribute("test","value")
request.getRequestDispatcher("/ServletB").forward(request, response)
ServletB:
request.getAttribute("test") <-- you can get test attribute by using getAttribute
Now my question is: If I use GET method to pass parameters from client to server, getAttribute() in Servlet works fine and I can get param values. But when I use POST method, getAttribute() returns null. Why does it work for GET and not for POST?
Complete nonsense. You're apparently working on an existing project which has a lot of other existing servlets and filters. My cents that there's another filter in the request-response chain which maps request parameters to request attribtues for some unobvious reason.
Please create a blank playground project and create a playground servlet to familarize yourself better with servlets without all that noise in existing projects.
See also:
Our Servlets wiki page

Java using Spring restful URL

I am using Java with Spring framework.
I have a multiaction controller which is having lots of service methods, and I want to to create restful URLs like as following:
http://server.com/url/events/multiActionMethod1
http://server.com/url/events/multiActionMethod2
http://server.com/url/events/multiActionMethod3
http://server.com/url/events/multiActionMethod4
http://server.com/url/events/multiActionMethod5
How can I achieve above tasks?
I think maybe something isn't coming through clearly in your question. It reads like all you're looking for is this:
#RequestMapping("/events/multiActionMethod1")
public ReturnType multiActionMethod1(SomeParameter param) {
//request handling logic
}
is there more to the question you could elaborate on?
edit: ugh no, none of that is in 2. You'd need 2.5 for annotations and 3 if you want support for using parts of the url as parameters. The easiest thing to do if you really want it to work that way in an older version is slap a URL rewriter on the front and convert it to regular query string before it hits spring.

Categories