SpringMVC-02-Controller和RestFul

2 Controller

2.1 控制器

  1. 控制器负责提供访问应用程序的行文,通常通过接口定义或者注解定义两种方法
  2. 控制器负责解析用户的请求并将其转换为一个模型
  3. SpringMVC中一个控制器类可以包含多个方法
  4. 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

  1. 概念
    RestFul就是一个资源定位以及资源操作的风格。不是标准也不是协议。
    优点:让软件更简洁,更有层次感,更易于实现缓存机制。

  2. 功能
    资源:互联网所有事物可以被抽象为资源
    资源操作:使用 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或POST

    RestFul风格: 参数使用 / 来分隔
    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

  3. 不同的注解

	@GetMapping
	@PostMapping
	@PutMapping
	@DeleteMapping
	@PatchMapping
  1. 实现
    @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";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值