Day02controller,requestMapping,RestFul风格,重定向和转发

1. 控制器Controller

1.1简介

  • 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现

  • 控制器负责解析用户的请求并将其转换为一个模型

  • 在Spring MVC中一个控制器类可以包含多个方法

  • 在Spring MVC中,对于Controller的配置方式有很多种

1.2实现Controller接口

​ Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法;

//实现该接口的类获得控制器功能
@FunctionalInterface
public interface Controller {
    //处理请求且返回一个模型与视图对象
    @Nullable
    ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}

测试:

  1. 新建一个Moudle,springmvc-04-controller。

    • 删掉HelloController
    • mvc的配置文件只留下视图解析器
  2. 编写一个Controller类,ControllerTest1

package com.liu.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 23862
 */

//只要实现了Controller接口的类,说明这就是一个控制器了
public class ControllerTest1 implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        mv.addObject("msg","ControllerTest1");
        mv.setViewName("test");
        return mv;
    }
}
  1. 编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应请求的类
<bean name="/t1" class="com.liu.controller.ControllerTest1"/>
  1. 编写前端test.jsp,注意在WEB-INF/jsp目录下编写,对应我们的视图解析器
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>
  1. 配置Tomcat运行测试,这里没有项目发布名,配置的就是一个/,所以不用加项目名

在这里插入图片描述

​ 说明:

  • 实现接口Controller定义控制器是较老的办法
  • 缺点:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦

1.3使用注解@Controller

  • @Controller注解类型用于声明Spring类的实例是一个控制器;
  • Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
	<!--自动扫描指定的包,下面所有注解类交给IOC容器管理-->
    <context:component-scan base-package="com.liu.controller"/>
  • 增加一个ControllerTest2类,可添加多个映射路径,使用注解实现;
package com.liu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 23862
 */

/**该注解代表这个类会被spring接管,被这个注解作用的类
其中的所有方法,如果返回值是String并且有具体页面可以跳转,
那么就会被视图解析器解析*/
@Controller
public class ControllerTest2 {

    @RequestMapping("/t2")
    public String test1(Model model){
        model.addAttribute("msg","ControllerTest2");
        return "test";  //WEB-INF/jsp/test.jsp
    }

    @RequestMapping("/t3")
    public String test3(Model model){
        model.addAttribute("msg","ControllerTest3");
        return "test";
    }
}

  • 运行Tomcat测试

在这里插入图片描述

在这里插入图片描述

​ 可以发现,多个请求可以指向同一个视图(test.jsp),但页面结果不一样,可以看出视图是被复用的,而控制器与视图之间是弱耦合关系。

2. RequestMapping

​ @RequestMapping

  • RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
  • 为了测试结果更准确,可以加上一个项目名测试web项目
  • 只注解在方法上面
@Controller
public class ControllerTest3 {

    @RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg","ControllerTest4");
        return "test";
    }
}

访问路径:http://localhost:8080/项目名/t1

  • 同时注解类和方法
@Controller
@RequestMapping("/c4")
public class ControllerTest3 {

    @RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg","ControllerTest4");
        return "test";
    }
}

访问路径:http://localhost:8080/项目名/c4/t1,需要先指定类的路径再指定方法的路径;

3. RestFul风格

3.1简介

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

​ 功能:

  • 资源:互联网所有的事物都可以被抽象为资源

  • 资源操作:使用POST,DELETE,PUT,GET,使用不同方法对资源进行操作。

  • 分别对应 添加,删除,修改,查询。

    传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,post和get。

  • 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

    学习测试:

  1. 新建一个类RestFulController
@Controller
public class RestFulController {
}
  1. 在Spring MVC中可以使用@PathVariable(路径变量)注解,让方法参数的值对应绑定到一个URL模板变量上。
@Controller
public class RestFulController {

    //传统方式需要在URL中输入值:http://localhost:8080/add?a=1&b=2
    //RestFul风格:http://localhost:8080/add/a/b
    @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";
    }

}

​ 运行结果:

在这里插入图片描述

  1. 写两个方法并限定请求方法的方式,在请求路径相同时测试会执行哪个方法:
@Controller
public class RestFulController {

    //传统方式需要在URL中输入值:http://localhost:8080/add?a=1&b=2
    //RestFul风格:http://localhost:8080/add/a/b

    //@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.POST)//限定请求方法的方式为POST
    @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";
    }

    //@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.GET)//限定请求方法的方式为GET
    @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";
    }


}

​ 运行结果:

在这里插入图片描述

  • 发现运行了方法2,识别了Get方式
  1. 在web文件夹下加入a.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="/add/1/2" method="post">
    <input type="submit">
</form>

</body>
</html>

​ 运行结果:

在这里插入图片描述

在这里插入图片描述

  • 发现通过Post方式访问执行了方法1

3.2小结

​ Spring MVC的@RequestMapping注解能够处理HTTP请求的方法,比如GET,PUT,POST,DELETE以及PATCH。

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

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

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

​ @GetMapping是一个组合注解

​ 他所扮演的是@RequestMapping(method = RequestMethod.GET)的一个快捷方式。

4.结果跳转方式

4.1ModelAndView

设置ModelAndView对象,根据view的名称,和视图解析器跳转到指定的页面。

页面:{视图解析器} + viewName + {视图解析器后缀}

    <!--视图解析器(ViewResolver)-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

对应的controller类

//只要实现了Controller接口的类,说明这就是一个控制器了
public class ControllerTest1 implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        mv.addObject("msg","ControllerTest1");
        mv.setViewName("test");
        return mv;
    }
}

4.2ServletAPI

通过设置ServletAPI,不需要视图解析器。

  1. 通过HttpServletResponse进行输出
  2. 通过HttpServletResponse实现重定向
  3. 通过httpServletRequest实现转发
@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test1(HttpServletRequest request, HttpServletResponse httpServletResponse){

        HttpSession session = request.getSession();
        System.out.println(session.getId());

        return "test";
    }
}

4.3SpringMVC

通过SpringMVC来实现转发和重定向,无需视图解析器;

测试前,需要将视图解析器注释掉

@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test1(Model model){
        //转发
        model.addAttribute("msg","ModelTest1");
        //此处不写 forward: 会默认执行转发操作
        return "forward:/WEB-INF/jsp/test.jsp";
    }
}
@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test1(Model model){
        //重定向(重定向时网页的URL会改变)
        model.addAttribute("msg","ModelTest1");
        return "redirect:/index.jsp";
    }
}

通过SpringMVC来实现转发和重定向 (有视图解析器时);

重定向不需要视图解析器,本质就是重新请求一个新地方,所以注意路径问题。

可以重定向到另一个请求实现。

@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test1(Model model){
        //转发
        model.addAttribute("msg","ModelTest1");
        
        return "test";
    }
}
@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test1(Model model){
        //重定向(重定向时网页的URL会改变)
        model.addAttribute("msg","ModelTest1");
        return "redirect:/index.jsp";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值