SpingMVC学习-
Controller
controller实现方式接口或者注解,一般使用注解的方法实现,负责解析用户的请求,并转换成一个模型返回给视图解析器
一下四个注解等效
- @Component 组件
@Service service层
@Controller 控制层controller
@Repository dao
上两篇博客分别使用接口SpringMVC学习-helloSpringMVC执行原理理解和注解实现SpringMVC学习-使用注解开发这里不再将所有代码拷贝过来,具体步骤可以看下上面两篇博客,一般开发时都是用@Controller注解的方式实现。下面简单说下二者的区别:
- 使用Controller接口实现的一个控制器中只能写一个方法,并且每写一个Controller类都需要在springmvc-servlet.xml配置文件中配置相应的bean
- 使用@Controller注解只需在Controller类上配置@Controller这个类就会被spring接管,被这个注解的类中的所有方法,再在类、方法上配置@RequestMapping(“xxx”)即可,一个Controller类中可以有多个方法
@RequestMapping
@RequestMapping注解用于映射url到控制器或者一个特定的处理程序方法,可用于类或者方法上,用在类上时,表示类中的所有响应请求的方法都是以该地址作为父路径。
使用示例
@Controller
@RequestMapping("/t3")
public class ControllerTest3 {
@RequestMapping("/test1")
public String test1(Model model){
model.addAttribute("msg","t3/test1");
return "test";//test.jsp页面
}
@RequestMapping("/test2")
public String test2(Model model){
model.addAttribute("msg","t3/test2");
return "test";
}
}
RestFul
RestFul是一种网络应用程序的设计风格和开发方式,基于HTTP,可以使用XML格式定义或JSON格式定义。RESTFUL适用于移动互联网厂商作为业务接口的场景,实现第三方OTT调用移动网络资源的功能,动作类型为新增、变更、删除所调用资源。
传统方式操作资源,post、get
使用RestFul操作资源:可以通过不同的请求方式实现不同的效果
特点:简洁、高效、安全
1、每一个URI代表1种资源;
2、客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
3、通过操作资源的表现形式来操作资源;
4、资源的表现形式是XML或者HTML;
5、客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。
传统方式:
// 原来的:http://localhost:8080/add?a=1&b=2
@RequestMapping("add")
public String test1(int a, int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
RestFul方式:
//RestFul:http://localhost:8080/add/a/b
@RequestMapping("add2/{a}/{b}")
public String test2(@PathVariable int a,@PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
可以通过设置参数method = RequestMethod.XXX限定资源访问方式
// method = RequestMethod.GET限定资源访问方式
@RequestMapping(value = "add2/{a}/{b}",method = RequestMethod.GET)
也可以使用注解进行限定,以上语句等价于
@GetMapping("add2/{a}/{b}")//只能通过get方式访问
类似有:
@GetMapping
@PostMapping
@DeleteMapping
@PutMapping