我写了一个基于 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;
}
当我访问“ http://localhost/app/hello ”时,我得到 404;当我访问“ http://localhost/app/hello/ ”时,我得到 202 OK。“ http://localhost/app/hello ”和“ http://localhost/app/hello/ ”有什么区别?
看看你的控制器代码
@RequestMapping("/hello")
public class JsonController
你的控制器有 url 映射 -> "/hello"
和 action(service) url 映射是“/”
@RequestMapping(value="/",method=RequestMethod.GET)
@ResponseBody
public Person service()
现在,每当我们为控制器提供映射时,控制器的每个动作都需要控制器 URL 路径作为前缀(如果 URL 映射在控制器中定义),正如您提到的控制器映射为“/hello”,动作服务url 映射为“ /"所以当您需要访问服务操作时 -> 您需要控制器的基本路径(如果请求 URL 映射在控制器中定义)+ 操作 URL 映射
-> "/hello" + "/" => "/hello/"
所以在访问 URL“ http://localhost/app/hello/ ”的情况下,它很容易找到service
操作并返回响应
现在,当您尝试访问 URL“ http://localhost/app/hello ”时,URL 映射搜索此映射并在您的控制器映射中找到它(因为它在您的情况下定义)但没有为它定义任何操作,为什么正在获得 404。
您可以定义它的默认操作,例如:
@RequestMapping(method=RequestMethod.GET)
public Person defaultAction() {
----your code
}
所以现在如果你点击“ http://localhost/app/hello ”,你将返回有效的响应而不是 404
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句