Spring MVC - what is url path info? - java

I would like to know what is a url path info?
For example in
http://myserver:8080/servletname/handlermethod
Is it the whole path including server name:
http://myserver:8080/servletname/handlermethod
or is it just
/servletname/handlermethod

getPathInfo() according to the doc:
Returns any extra path information associated with the URL the client
sent when it made this request. The extra path information follows the
servlet path but precedes the query string and will start with a "/"
character.
so in your example it will return /handlermethod
If you want to have /servletname/handlermethod you should use getRequestURI().
getRequestURL() will return the full URL made by the client (except string parameters).

The path info in Spring MVC may imply for the info sent via a URL. In a Spring MVC Controller you can easily set a request mapping which include a variable value place holder which is bound to an argument with #PathVariable annotation in the method signature - related to the request mapping. For eaxmple:
#RequestMapping(value = "/user/{userId}")
public ModelAndView getUserByPathVariable(#PathVariable Long userId, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Got request param: " + userId);
You take a look here for a more detailed example: Spring MVC Controller Example

Related

Forwarding request to a new controller

I have this two controller from two separate projects lets name them:
project1.controller1
project2.controller1
Obviously these are two Spring controllers from different projects.What I want is to make project1.controller1 a gateway all request will be sent here. And will process the request if it will go to project2.controller1 or a new controller.
Some pseudoCode:
#Controller
public class someClassFromProject1{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//some processing, converting request to string, etc
if("someStringThatIsPartOfTheRequest".equals("someString"))
//carry request and forward it to project2.controller1
else
//go to another external controller
}
}
And in project2.controller 1 will look something like this:
#Controller
public class someClassFromProject2{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//processing
}
}
I've already tried return "forward:/someUrl"; and return "redirect:someUrl";. It didn't work and it didn't reach project2.controller1. So any ideas on this one?
Edit: Forgot to add this one, different project means different WAR but deployed on the same sever. And the request should be carried over from project1.controller1 to project2.controller1 because I'm gonna process the request there.
Thanks!
You need to use redirect instead of forward.
The protocol is required if the host is different to that of the current host
return "redirect:http://www.yahoo.com";
Have a look at the redirect: prefix section from Spring Web MVC framework also check this
A logical view name such as redirect:/myapp/some/resource will
redirect relative to the current Servlet context, while a name such as
redirect:http://myhost.com/some/arbitrary/path will redirect to an
absolute URL.
Figured it out but then it's kind of messy, I've used HttpClient to Post my Request to the URL. It also carried the request along with the forwarding. Anyway, thanks for all the help guys. Thanks :)

SpringMVC RequestMapping for GET url parameters

How to make the RequestMapping to handle GET parameters in the url? For example i have this url
localhost:8080/MyApplication/spm/gcNkyLXkwv
how to get the spm value from the above url
This can be done using PathVariable. I will just give example how it can be done. You can incorporate in your example
Suppose you want to write a url to fetch some order, you can say
www.mydomain.com/order/123
where 123 is orderId.
So now the url you will use in spring mvc controller would look like
/order/{orderId}
Now order id can be declared a path variable
#RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(#PathVariable String orderId){
//fetch order
}
if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring
Also note that PathVariable differ from requestParam as pathVariable are part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

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.

Handling special characters in post parameters for Spring-mvc

I have an application using spring-mvc 3.0.
The controllers are configured like this:
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView updateValues(
#RequestParam("einvoiceId") String id){
...}
When posting an id that contains special characters (in this case pipe |), url-encoded with UTF-8 (id=000025D26A01%7C2014174) the string id will contain %7C. I was expecting spring-mvc to url decode the parameter. I am aware that I can solve this by using
java.net.URLDecoder.decode()
but since I have a large number of controllers, I would like this to be done automatically by the framework.
I have configured the Tomcat connector with URIEncoding="UTF-8" and configured a CharacterEncodingFilter, but as I understand it this will only affect GET requests.
Any ideas on how I can make spring-mvc url decode my post parameters?
http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q3
This page says CharacterEncodingFilter can change POST parameters
I believe you encounter the same issue as I did.
Try using #PathVariable instead #RequestParam.
#PathVariable is to obtain some placeholder from the uri (Spring call it an URI Template) — see Spring Reference Chapter 16.3.2.2 URI Template Patterns
If you do, you have to change your url and don't provide parameter 'id'.
Just "/update/000025D26A01%7C2014174".
More information can be found where I found the solution for my problem #RequestParam vs #PathVariable

Get the variable in the path of a URI

In Spring MVC I have a controller that listens to all requests coming to /my/app/path/controller/*.
Let's say a request comes to /my/app/path/controller/blah/blah/blah/1/2/3.
How do I get the /blah/blah/blah/1/2/3 part, i.e. the part that matches the * in the handler mapping definition.
In other words, I am looking for something similar that pathInfo does for servlets but for controllers.
In Spring 3 you can use the # PathVariable annotation to grab parts of the URL.
Here's a quick example from http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
#RequestMapping(value="/hotels/{hotel}/bookings/{booking}", method=RequestMethod.GET)
public String getBooking(#PathVariable("hotel") long hotelId, #PathVariable("booking") long bookingId, Model model) {
Hotel hotel = hotelService.getHotel(hotelId);
Booking booking = hotel.getBooking(bookingId);
model.addAttribute("booking", booking);
return "booking";
}
In Spring 2.5 you can override any method that takes an instance of HttpServletRequest as an argument.
org.springframework.web.servlet.mvc.AbstractController.handleRequest
In Spring 3 you can add a HttpServletRequest argument to your controller method and spring will automatically bind the request to it.
e.g.
#RequestMapping(method = RequestMethod.GET)
public ModelMap doSomething( HttpServletRequest request) { ... }
In either case, this object is the same request object you work with in a servlet, including the getPathInfo method.

Categories