Hao Hao - 3 years ago 63
Java Question

What's the difference between "http://localhost/app/hello" and "http://localhost/app/hello/"?

I have write a controller based on Spring MVC.

@Controller
@RequestMapping("/hello")
public class JsonController {

@RequestMapping(value="/",method=RequestMethod.GET)
@ResponseBody
public Person service(){
Person person=new Person();
person.setId(3);
person.setName("666");
return person;
}


When I access "http://localhost/app/hello",I get 404;
When I access "http://localhost/app/hello/", I get 202 OK.
What's the difference between "http://localhost/app/hello" and "http://localhost/app/hello/"?

Answer Source

look your controller code

@RequestMapping("/hello")
public class JsonController

you controller have url mapping -> "/hello"

and action(service) url mapping is "/"

@RequestMapping(value="/",method=RequestMethod.GET)
    @ResponseBody
    public Person service()

Now whenever we provided the mapping for our controller then every action of controller need this controller url path as prefix (if url mapping is define in controller), as you have mention your controller mapping with "/hello" and action service mapping with "/" so when you need to access the service action then -> you need basepath of controller (if Request url mapping define in controller) + action url mapping

-> "/hello" + "/"   => "/hello/"

so in case of "http://localhost/app/hello/" so when you trying to access url"http://localhost/app/hello/" its easily find service action

Now when you trying "http://localhost/app/hello" to access, url mapping with search this mapping and will find with controoler mapping but there is no action define it thats why are will getting 404.

You can define it default action like:

@RequestMapping(method=RequestMethod.GET)
    public Person defaultAction() { 
----your code
}

so now if you will hit "http://localhost/app/hello" this your you will get the response

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download