4、Controller 及 RestFul风格

Controller本质还是一个Servlet

4.1、控制器Controller

  • 控制器负责提供访问应用程序的行为, 通常通过借口定义两种方法实现。
  • 控制器负责解析用户的请求并将其转换为一个模型。
  • 在Spring MVC中一个控制器类可以包含多个方法
  • 在Spring MVC中, 对于Controller的配置有很多种

步骤:
1、配置web.xml
2、编写一个Controller类, 继承Controller借口

//只要实现了Controller接口的类,说明这就是一个控制器了
public class Controller01 implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //返回一个模型视图
        ModelAndView mv = new ModelAndView();

        mv.addObject("msg","Controller01");

        mv.setViewName("test");
        return mv;
    }
}

3、编写Springmvcservlet.xml完毕后, 去Spring配置文件中注册请求的bean; name对应请求路径, class对应处理请求的类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--视图解析器: 模板引擎 Thymeleaf Freemarker...(核心之一,不可省)-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean name="/t1" class="com.controller.Controller01"/>
</beans>

4、其他步骤省略
总结:
①实现接口是较老的办法(不建议使用),
②如果要多个方法则需要定义多个Controller; 定义的方式比较麻烦

4.2、使用注解@Controller、@RequestMappin(重点)

@Component 组件
@Service service
@Controller controller
@Repository dao
以上四个组件等效
步骤:
1、配置web
2、编写一个Controller类, 打注解(@Controller、@RequestMappin)
@Controller: //表示这个类已被springmvc-servlet.xml托管
被注解的类,其中所有方法,如果返回值是String,

并且有具体的页面可以跳转, 那么就会被视图解析器处理
@RequestMapping("/映射地址"): 用在方法和注解上,表示访问地址
这个方法的参数除了Model(主要用于给前端传数据),其余都是通过地址栏(前端传进来)传进来的

@Controller//表示这个类已被springmvc-servlet.xml托管
//被注解的类,其中所有方法,如果返回值是String,并且有具体的页面可以跳转, 那么就会被视图解析器处理
public class Controller02 {

    //访问地址: http://localhost:8080/t2
    @RequestMapping("/t2")
    public String test2(Model model) {
        //封装数据(可在jsp页面中取出并渲染出来)
        model.addAttribute("msg", "Controller02");
        return "test";//会被视图解析器处理(跳转到test页面)
    }

    //访问地址: http://localhost:8080/t3
    @RequestMapping("/t3")
    public String test3(Model model) {
        //封装数据(可在jsp页面中取出并渲染出来)
        model.addAttribute("msg", "Controller03");
        return "test";//会被视图解析器处理(跳转到test页面)
    }
}

3、编写Springmvcservlet.xml(固定的)

     - 让IOC的注解生效													`<**context:component-scan base-package="com.controller"**/>`
     - 静态资源过滤 : HTML、JS、CSS、图片、视频……							`<**mvc:default-servlet-handler**/>`
     - MVC的注解驱动													`<**mvc:annotation-driven**/>`

支持mvc注解驱动
在spring中一般采用@RepuestMapping注解来完成映射关系
想要使@RepuestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--自动扫描包, 让指定包下的注解生效, 由IOC容器统一管理-->
    <context:component-scan base-package="com.controller"/>

    <!--SpringMVC不处理静态资源  .css、.js、.html、.mp3、.mp4-->
    <mvc:default-servlet-handler/>

    <!--支持mvc注解驱动-->
    <mvc:annotation-driven/>

    <!--视图解析器: 模板引擎 Thymeleaf Freemarker...(核心之一,不可省)-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

4.3、RestFul风格

概念

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计软件可以更简洁, 更有层次, 更易实现缓存等机制


功能

  • 资源: 互联网所有的事务都可以被抽象为资源
  • 资源操作: 使用POST、DELETE、PUT、GET, 使用不同方法对资源进行操作
  • 分别对应 添加、删除、修改、查询。


优点

  • 简洁
  • 高效
  • 安全

传统方式操作资源

通过不同参数来实现不同的效果! 方法单一, post和get
![image.png](https://img-blog.csdnimg.cn/img_convert/61fc604b151ca6e83b55eeb79039dddd.png#clientId=u067dd4e7-6c9b-4&from=paste&height=144&id=aEA46&margin=[object Object]&name=image.png&originHeight=139&originWidth=720&originalType=binary&ratio=1&size=81641&status=done&style=none&taskId=u5b66c259-7563-4b5e-85f8-856cb913e93&width=748)

使用RESTful操作资源

可以通过不同的请求方式来实现不同的效果! 如下: 请求地址一样, 但是功能可以不同!
![image.png](https://img-blog.csdnimg.cn/img_convert/8c99ffe623375bd1c63ee5088dd6d6e9.png#clientId=u067dd4e7-6c9b-4&from=paste&height=127&id=uce634207&margin=[object Object]&name=image.png&originHeight=131&originWidth=790&originalType=binary&ratio=1&size=55590&status=done&style=none&taskId=u8aa83240-8ff7-42d2-8544-1571af1e1fa&width=767)

使用方法 :
在Spring MVC中可以使用@PathVariable注解, 让方法参数的值对应绑定到一个URL模板变量上
@RequestMapping(**"/add/{a}/{b}"**) 默认方法是get
**public **String test(@PathVariable **int **a, @PathVariable **int **b, Model model)

@Controller
public class RestFulController {
   //原方式传参访问: http://localhost:8080/add?a=1&b=6
   //RestFul: http://localhost:8080/add/a/b
    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model) {
        model.addAttribute("msg", "结果为: " + (a + b));
        return "test";
    }
}



方法类型: POST、DELETE、PUT、GET,

Spring MVC的@RequestMapping注解能够处理HTTP请求的方法, 比如POST、DELETE、PUT、GET以及PATCH
例如:
_//以get方式请求_
@RequestMapping(value = **"/add/{a}/{b}"**,method = RequestMethod.**_GET_**)
_//以_**_Post_**_方式请求_(主要用于表单提交)
@RequestMapping(path = **"/add/{a}/{b}"**,method = RequestMethod.**_Post_**)

所有的地址栏请求默认都是HTTP GET 类型的


方法级别的注解变体有如下几个: 组合注解

组合注解是@RequestMapping的一个快捷方式(简便方法)

@GetMapping @GetMapping(**"/add/{a}/{b}"**)
@PostMapping @PostMapping(**"/add/{a}/{b}"**)(主要用于表单提交)
例:

    @PostMapping("/add/{a}/{b}")
    public String test3(@PathVariable int a, @PathVariable int b, Model model) {
        model.addAttribute("msg", "test3结果为: " + (a + b));
        return "test";
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/add/2/6" method="post">
    <input type="submit">
</form>
</body>
</html>

@PutMapping
@DeleteMapping
@PatchMapping

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值