SpringMVC框架(二)—RestFul风格、重定向与转发
RestFul风格
一、传统写法
1、 新建RestFulController类并编写
package com.study.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add")
public String test1( int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
2、运行测试
3、传统的方法给它赋值参数
二、使用RestFul风格
重新编写RestFulController类
在参数前面使用【@PathVariable】注解
package com.study.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
运行测试
重定向和转发
一、先将视图解析器注释掉
二、编写代码实现重定向和转发
package com.study.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelTest1 {
//转发方式一
@RequestMapping("m1/t1")
public String test1(Model model){
model.addAttribute("msg","ModelTest1");
return "/WEB-INF/jsp/test.jsp";
}
//转发方式二:forward:
@RequestMapping("/m2/t2")
public String test2(){
return "forward:/index.jsp";
}
//重定向
@RequestMapping("/rsm/t3")
public String test3(){
return "redirect:/index.jsp";
}
}
访问m1/t1路径,可以转发到WEB-INF/jsp/test.jsp