@PathVarible
@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值
语法:
@PathVariable("xxx")
通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/hello/show5/1/james
测试环境:
环境:jdk1.8 Tomcat8.5 idea2018 manven父工程子模块
步骤:
1、创建web工程、引入依赖
2、配置SpringMvc入口文件 --DispatcherServlet--为总调度、web.xml里配置
3、创建Springmvc.xml文件--理解为:适配器(这里不需要自已指定适配、springmvc会自动指定)--视图解析器
4、创建 业务处理器 Controller类
5、测试
工程结构:
![](https://img-blog.csdnimg.cn/img_convert/f323b89cc4c53d5dad818bf43c8ea3f8.png#align=left&display=inline&height=408&margin=[object Object]&originHeight=408&originWidth=382&size=0&status=done&style=none&width=382)
步骤1、2、3、参考:SpringMvc入门案例:https://blog.csdn.net/sswqzx/article/details/84171999
业务处理器HelloController.java
package com.day01springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
/**
* @ Author :ShaoWei Sun.
* @ Date :Created in 20:58 2018/11/16
*/
@Controller
@RequestMapping("hello")
public class HelloController2 {
/**
*3、占位符映射
* 语法:@RequestMapping(value=”user/{userId}/{userName}”)
* 请求路径:http://localhost:8080/hello/show5/1/james
* @param ids
* @param names
* @return
*/
@RequestMapping("show5/{id}/{name}")
public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
mv.setViewName("hello2");
return mv;
}
}
测试
![](https://img-blog.csdnimg.cn/img_convert/892641eb4383ed76e6d5a98fd3a5e4a9.png#align=left&display=inline&height=189&margin=[object Object]&originHeight=189&originWidth=798&size=0&status=done&style=none&width=798)
@RestController
@Controller 包括了 @RestController。@RestController 是 Spring4 后新加的注解,从 RestController 类源码可以看出 @RestController 是 @Controller 和 @ResponseBody 两个注解的结合体。
@Controller=@RestController+@ResponseBody
如下 @RestController 的源码可以看出他们的关系
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(
annotation = Controller.class
)
String value() default "";
}
@Controller 与 @RestController应用场景
- @Controller 一般应用在有返回界面的应用场景下.
例如,管理后台使用了 thymeleaf 作为模板开发,需要从后台直接返回 Model 对象到前台,那么这时候就需要使用 @Controller 来注解。 - @RestController 如果只是接口,那么就用 RestController 来注解.
例如前端页面全部使用了 Html、Jquery来开发,通过 Ajax 请求服务端接口,那么接口就使用 @RestController 统一注解。