SpringMVC-lesson05-controller&Restful风格-2023-03-22

发布时间 2023-03-23 22:16:31作者: Rui2022

第一种:实现接口Controller定义控制器是比较老的办法

缺点:一个控制器只有一个方法,如果有多个方法需要定义多个controller,定义方式比较麻烦

 

第二种:使用注解 @Controller  视图可以被复用

几种常用的注解

@Component            组件

@Service                  service

@Controller              controller

@Respository          dao

@Controller
public class ControllerTest2 {
    @RequestMapping("/t2")
    public String test2(Model model){
        model.addAttribute("msg","controllerTest2");
        return "test";
    }

    @RequestMapping("/t3")
    public String test3(Model model){
        model.addAttribute("msg","controllerTest3");
        return "test";
    }
}
@Controller
@RequestMapping("/admin")   //不推荐这样写
public class ControllerTest3 {
    //@RequestMapper注解用于映射url到控制器类或一个特定的处理程序方法,可用于类或方法上。
    // 用于类上,表示类中所有响应请求的方法都是以该地址作为父路径
@RequestMapping("/t1")    //推荐这种写法,宁愿多写一级:/admin/t1
    public String test1(Model model){
    model.addAttribute("msg","controllerTest-c3/t1");
        return "admin/test";
    }
}

第三:restful风格 就是一个资源定位及资源操作的风格,

localhost:8080/method?add1=1& add2=2

restful风格 是以斜线作为风格    localhost:8080/method/item/52

功能

1、资源

2、资源操作:get post delete put使用不同的方法对资源进行操作 原来传统的只能通过不同的参数(链接)来实现不同的效果

3、restful风格                                                                                                        通过不同的请求方式来实现不同的效果 有可能请求方式一样,但输出不同

传统的方法-案例

@Controller
public class RestfulController {

    @RequestMapping("/add")
    public  String test(int a, int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为:"+res);
        return "test";
    }
}

url 输入:http://localhost:8080/add?a=3&b=6  否则会报500错误,一定要给a,b传值

restful风格-案例

    @RequestMapping("/add/{a}/{b}")
    public  String test(@PathVariable int a, @PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为:"+res);
        return "test";
    }
}

url输入:http://localhost:8080/add/2/6

更为简便的方法 @GetMapping 和@PostMapping方法  默认GetMapping方法

// 可以简化如下: @RequestMapping(name = "/add/{a}/{b}",method = RequestMethod.GET)
@PostMapping("/add/{a}/{b}")
public  String test1(@PathVariable int a, @PathVariable int b, Model model){
    int res=a+b;
    model.addAttribute("msg","结果1为:"+res);
    return "test";
}

@GetMapping("/add/{a}/{b}")
public  String test2(@PathVariable int a, @PathVariable int b, Model model){
    int res=a+b;
    model.addAttribute("msg","结果2为:"+res);
    return "test";
}

restful风格的好处:简洁,高效,安全,传出去的值其他人并不知道。

小黄鸭调试法:就是发现错误时,尝试自己跟自己讲一遍,在讲的过程中可能你一下子就顿悟了。《程序员修炼之道》