2 Controller
2.1 控制器
- 控制器负责提供访问应用程序的行文,通常通过接口定义或者注解定义两种方法
- 控制器负责解析用户的请求并将其转换为一个模型
- SpringMVC中一个控制器类可以包含多个方法
- SpringMVC中,对于Controller的配置方式有很多种
2.2 实现Controller接口
Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法
@FunctionalInterface
public interface Controller {
@Nullable
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
2.2.1 implements接口实现
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// ModelAndView模型和视图
ModelAndView mv = new ModelAndView();
// 封装对象,放在ModelAndView中
mv.addObject("msg", "HelloSpringMVC");
mv.setViewName("hello"); // 根据配置,自动拼接前后缀(/WEB-INF/jsp/hello.jsp)
return mv;
}
}
注意: 需要在servlet-bean.xml中对Controller进行注册
2.2.2 注解实现
- 类似的注解
@Component 表明是一个组件
@Controller
@Service
@Repository Dao方法的注解
使用注解要在 servlet-bean.xml中进行配置,自动扫描装配注解
<context:component-scan base-package="com.miao.controller"/>
@Controller
public class UserController {
@RequestMapping("hello")
public String say(Model model){
model.addAttribute("msg", "hello");
return "hello";
}
}
2.3 RestFul
-
概念
RestFul就是一个资源定位以及资源操作的风格。不是标准也不是协议。
优点:让软件更简洁,更有层次感,更易于实现缓存机制。 -
功能
资源:互联网所有事物可以被抽象为资源
资源操作:使用 POST、DELETE、PUT、GET,使用不同方法对资源进行操作
传统操作:参数使用?name=value&name2=value2的方式
http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POSTRestFul风格: 参数使用 / 来分隔
http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE -
不同的注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
- 实现
@RequestMapping(path=“xxx”, method=enum.type)与@GetMapping相同
@Controller
public class RestFulController {
@GetMapping("/add")
public String add(){
return "add";
}
@RequestMapping(path = "/result/{a}/{b}", method = RequestMethod.GET)
public String add(@PathVariable int a, @PathVariable int b, Model model){
int c = a+b;
model.addAttribute("msg", c);
return "result";
}
}