SpringMVC02注解与Rest风格

SpringMVC02

SpringMVC的注解

一、@RequestParam

1、@RequestParam注解介绍
  • 位置:在方法入参位置
  • 作用:指定参数名称,将该请求参数 绑定到注解参数的位置
  • 属性
    • name:指定要绑定的请求参数名称; name属性和value属性互为别名。
    • required:指定请求参数是否必传。默认值为true,表示必须提交参数(无参数400)。
    • defaultValue:指定当没有传入请求参数时的默认取值。
  • 注意:如果required 和 defaultValue 都存在, required属性失效。
2、@RequestParam使用示例

(1)页面请求定义

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--<a href="">测试</a>--%>
    <form action="testController/test01" method="get" enctype="application/x-www-form-urlencoded">
        账号:<input type="text" name="username">
        <br>
        <input type="submit" >
    </form>
</body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>main</title>
</head>
<body>
    <h1>这里是main页面</h1>
</body>
</html>

(2) 执行器方法

测试一

@Controller
@RequestMapping("/testController")
public class TestController {

    @RequestMapping(value = "test01",method = {RequestMethod.GET})
    public String test01(@RequestParam(name = "username",required = true) String username){
        System.out.println("username = " + username);
        return "main";
    }

}

测试二

去掉index.jsp中的input标签,再测试,报400

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--<a href="">测试</a>--%>
    <form action="testController/test01" method="get" enctype="application/x-www-form-urlencoded">
        <%--账号:<input type="text" name="username">--%>
        <br>
        <input type="submit" >
    </form>
</body>
</html>

测试三

据测试二,添加属性defaultValue

@RequestMapping(value = "test01",method = {RequestMethod.GET})
public String test01(@RequestParam(name = "username",required = true,defaultValue = "小李") String username){
    System.out.println("username = " + username);
    return "main";
}

二、@RequestHeader

1、@RequestHeader注解介绍
  • 位置:方法入参位置
  • 作用:用于获取请求头信息
  • 属性
    • value:指定头的名称;
    • name:和value属性会别名
    • require:是否是必须, true,必须传递, 没传递。400
    • defaultValue: 如果前台没传递头信息, 指定默认值。 require冲突。
2、@RequestHeader使用示例

(1)页面定义请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--<a href="">测试</a>--%>
    <form action="testController/test02" method="post" enctype="application/x-www-form-urlencoded">
        <%--账号:<input type="text" name="username">--%>
        <br>
        <input type="submit" >
    </form>
</body>
</html>

(2) 执行器方法

@RequestMapping(value = "test02",method = {RequestMethod.POST})
public String test02(@RequestHeader(name = "Upgrade-Insecure-Requests") String data){
    System.out.println("data = " + data);
    return "main";
}

三、@RequestBody

1、@RequestBody注解介绍
  • 位置:方法入参位置
  • 作用:获取请求体内容,get 请求方式不适用。通常用于将json格式字符串绑定到bean对象中;
  • 使用:直接使用得到是 key=value&key=value…结构的数据。
2、@RequestBody使用示例
(1)直接获取请求体内容

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--<a href="">测试</a>--%>
    <form action="testController/test03" method="post" enctype="application/x-www-form-urlencoded">
        账号:<input type="text" name="username">
        密码:<input type="password" name="password">
        <br>
        <input type="submit" >
    </form>
</body>
</html>

执行器方法

@RequestMapping(value = "test03",method = {RequestMethod.POST})
public String test03(@RequestBody String data){
    System.out.println("data = " + data);
    return "main";
}
(2)将json格式请求参数绑定到指定bean中

Student实体

public class Student {
    private String id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

引入json的解析器,pom.xml中

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
</dependency>

静态页面无法加载,在application.xml配置信息

<mvc:default-servlet-handler></mvc:default-servlet-handler>

页面定义请求index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.6.3.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                // 发送Ajax请求
                $.ajax({
                    url:"testController/test04",
                    type:"post",
                    data:'{"id":1,"name":"小胡","age":22}',
                    contentType:"application/json",
                    success:function (resp) {
                        alert(resp);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="button" id="btn" value="测试">
</body>
</html>

执行器方法

@RequestMapping(value = "test04",method = {RequestMethod.POST})
public String test04(@RequestBody Student student){
    System.out.println("student = " + student);
    return "main";
}

四、@CookieValue

1、@CookieValue注解介绍
  • 位置:方法入参位置
  • 作用:把指定 cookie 名称的值传入控制器方法参数
2、@CookieValue使用示例

原生的Cookie的获取

Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if(name.equals("JSESSIONID")){
                //获得cookie的值: 
                String value = cookie.getValue();
            }
        }

@CookieValue注解

  • 方式一:通过cookie的名称获得cookie对应的值

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test01</title>
</head>
<body>
    <a href="testController/test05">test05</a>
</body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>main</title>
</head>
<body>
    <h1>这里是main页面</h1>
</body>
</html>

执行器方法

@RequestMapping(value = "test05",method = {RequestMethod.GET})
public String test05(@CookieValue("JSESSIONID") String data){
    System.out.println("data = " + data);
    return "main";
}
  • 方式二:通过Cookie的名称直接获得cookie对应的对象
@RequestMapping(value = "test06",method = {RequestMethod.GET})
public String test06(@CookieValue("JSESSIONID") Cookie cookie){
    System.out.println("key = " + cookie.getName() + "," + "value = " + cookie.getValue());
    return "main";
}

五、@ModelAttribute

1、@ModelAttribute注解介绍
  • 位置:方法入参位置,修饰方法。SpringMVC4.3版本以后新加入的
  • 作用
    • 参数上:获取指定的数据给参数赋值
    • 方法上:表示当前方法会在控制器的方法执行之前,先执行。它可修饰无返回值和有返回值得方法。
2、@ModelAttribute使用示例
// 注解在方法上
@ModelAttribute("param")
public String test07(){
    System.out.println("这是 ModelAttribute 注解的方法");
    return "hello world";
}

// 注解在参数位置
@RequestMapping(value = "test08",method = {RequestMethod.GET})
public String test08(@ModelAttribute("param") String data){
    System.out.println("ModelAttribute 注解的参数 data = " + data);
    return "main";
}

六、@SessionAttribute

1、@SessionAttribute注解介绍
  • 位置:在类上,
  • 作用:将请求域中的参数存放到session域中,用于参数共享。
2、@SessionAttribute使用示例

页面请求

test01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test01</title>
</head>
<body>
    <a href="sessionController/test01">test01</a><br>
    <a href="sessionController/test02">test02</a><br>
</body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>main</title>
</head>
<body>
    <h1>这里是main页面</h1>
    <span>${studnet}</span>
</body>
</html>

执行器方法

@Controller
@RequestMapping("/sessionController")
@SessionAttributes("student")
public class SessionController {

    @RequestMapping(value = "test01",method = {RequestMethod.GET})
    public ModelAndView test01(ModelMap modelMap){
        ModelAndView modelAndView = new ModelAndView();
        modelMap.addAttribute("studnet",new Student("1","tom",22));
        modelAndView.setViewName("main");
        return modelAndView;
    }

    @RequestMapping(value = "test02",method = {RequestMethod.GET})
    public String test02(){
        return "main";
    }
}

测试过程:先点test02,后点test01,才能看到session的Attribute值

  • 注意:@SessionAttributes(“student”) 和 modelMap.addAttribute(“studnet”,new Student(“1”,“tom”,22));两个中 key的值要相同

Rest风格

一、Rest风格URL规范介绍

1、什么是restful?
  • restful是一种软甲架构风格、设计风格,并不是标准。
  • 它只是提供了一组设计原则和约束条件。
  • 它主要用于客户端和服务器交互类的软件。
  • 基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
2、restful的优点
  • 结构清晰
  • 符合标准
  • 易于理解
  • 扩展方便
  • 屏蔽url中动词
3、restful的特性
  • 统一资源定位符体现形式1:http://localhost:8080/user/ URL
  • 统一资源定位符体现形式2:http://localhost:8888/user/id ,id作为了url地址的一部分

传统请求url

功能统一资源定位符请求方式
新增http://localhost:8888/user/addPOST
修改http://localhost:8888/user/updatePOST
删除http://localhost:8888/user/deleteById?id=1GET
查询一个http://localhost:8888/user/findById?id=1GET
查询所有http://localhost:8888/user/findAllGET

Rest风格请求

功能统一资源定位符请求方式
新增http://localhost:8888/userPOST
修改http://localhost:8888/userPUT
删除http://localhost:8888/user/1DELETE
查询一个http://localhost:8888/user/1GET
查询所有http://localhost:8888/userGET

二、@PathVariable注解

1、@PathVariable介绍
  • 位置:方法参数

  • 作用:用于绑定 url 中的占位符,url 支持占位符是 spring3.0 之后加入的,是springmvc 支持 rest 风格 URL 的一个重要标志。

    • 例:请求 url 中/annotation/test9/{id},其中 {id} 就是 url 占位符。
  • 属性:

    • value:指定 url 中占位符名称
    • required:是否必须提供占位符
  • 使用:

    • 前端: localhost:8080/user/findUser/1001
    • 后端: @RequestMapping(“findUser/{uid}”)
    • 参数:PathVariable(“uid”) Integer id
2、@PathVariable使用案例
(1) 构建页面发起请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test01</title>
</head>
<body>
    <%--<a href="testController/test05">test05</a><br>
    <a href="testController/test06">test06</a><br>
    <a href="testController/test08">test08</a><br>
    <a href="sessionController/test01">test01</a><br>
    <a href="sessionController/test02">test02</a><br>--%>
    <h1>新增</h1>
    <form action="studentController/addStudent" method="post" enctype="application/x-www-form-urlencoded">
        编号:<input type="text" name="id"><br>
        姓名:<input type="text" name="name"><br>
        年龄:<input type="number" name="age"><br>
        <input type="submit" value="添加">
    </form>
    <h1>修改</h1>
    <form action="studentController/updateStudent" method="post" enctype="application/x-www-form-urlencoded">
        <input type="hidden" name="_method" value="PUT">
        编号:<input type="text" name="id"><br>
        姓名:<input type="text" name="name"><br>
        年龄:<input type="number" name="age"><br>
        <input type="submit" value="修改">
    </form>
    <h1>删除</h1>
    <form action="studentController/deleteStudent" method="post" enctype="application/x-www-form-urlencoded">
        <input type="hidden" name="_method" value="DELETE">
        编号:<input type="text" name="id"><br>
        <input type="submit" value="删除">
    </form>
    <h1>查询</h1>
    <a href="studentController/getStudent/1">获取学生信息</a>
</body>
</html>
(2) 定义控制层处理请求
a、页面

form表单针对 PUT 和 DELETE:实际填写 POST

hidden隐藏域: _method PUT | DELETE

b、后端处理器
  • ​ @GetMapping 处理get请求。 查询操作。
  • ​ @PostMapping 处理post请求。 新增操作
  • ​ @PutMapping 处理put请求。 修改操作。
  • ​ @DeleteMapping 处理delete 请求, 删除操作。

执行器方法

@Controller
@RequestMapping("/studentController")
public class StudentController {

    /*@RequestMapping(value = "addStudent",method = {RequestMethod.POST})*/
    @PostMapping("addStudent")
    public String addStudent(Student student){
        System.out.println("add student = " + student);
        return "main";
    }

    /*@RequestMapping(value = "getStudent/{sid}",method = {RequestMethod.GET})*/
    @GetMapping("getStudent/{sid}")
    public String getStudent(@PathVariable("sid") int id){
        System.out.println("get id = " + id);
        return "main";
    }

    /*@RequestMapping(value = "updateStudent",method = {RequestMethod.PUT})*/
    @PutMapping("updateStudent")
    public String updateStudent(Student student){
        System.out.println("update student = " + student);
        return "main";
    }

    /*@RequestMapping(value = "deleteStudent",method = {RequestMethod.DELETE})*/
    @DeleteMapping("deleteStudent")
    public String deleteStudent(int id){
        System.out.println("dlelete id = " + id);
        return "main";
    }
}
(3) 引入请求方法转换过滤器

过滤器web.xml文件中

<!--过滤请求方式:自动识别请求体中是否有_method数据,如果有,将其值设为当前请求方式,如果没有,直接放行-->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
(4)测试

响应数据及结果视图

一、返回值分类

1、返回值为字字符串(常用)
  • 用于指定返回的逻辑视图名称;
@GetMapping("resp01")
public String resp01() {
    return "main";
}
2、void类型
  • 通常使用原始servlet处理请求时,返回该类型
@GetMapping("resp02")
public void resp02(HttpServletRequest request, HttpServletResponse response) throws IOException {
   response.sendRedirect("../main.jsp");
}
3、ModelAndView
  • 用于绑定模型数据和视图路径;
@GetMapping("resp03")
public ModelAndView resp03(ModelMap modelMap) {
    ModelAndView modelAndView = new ModelAndView();
    modelMap.addAttribute("username","小李");
    modelAndView.setViewName("main");
    return modelAndView;
}
4、返回值自定义类型(重点)

(1) 引入依赖包

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

(2)ResponseBody注解: 能够将bean List Map 转换成Json格式,异步响应会客户端浏览器

页面定义请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test02</title>
</head>
<body>
    <a href="responseController/resp01">resp01</a>
    <a href="responseController/resp02">resp02</a>
    <a href="responseController/resp03">resp03</a>
    <a href="responseController/resp04">resp04</a>
</body>
</html>

执行器方法

  • 原始方式
@Controller
@RequestMapping("/responseController")
public class ResponseController {

    @GetMapping("resp01")
    public void resp01(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Student> list = new ArrayList<Student>();
        list.add(new Student("1","mary",18));
        list.add(new Student("2","tom",18));
        list.add(new Student("3","jack",18));
        ObjectMapper mapper = new ObjectMapper();
        String string = mapper.writeValueAsString(list);
        PrintWriter writer = response.getWriter();
        writer.print(string);
        writer.close();
    }
}
  • 对象
@GetMapping("resp02")
@ResponseBody
public Student resp02(){
    return new Student("3","jack",18);
}
  • 单列集合
@GetMapping("resp03")
@ResponseBody
public List<Student> resp03(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<Student> list = new ArrayList<Student>();
    list.add(new Student("1","mary",18));
    list.add(new Student("2","tom",18));
    list.add(new Student("3","jack",18));
    return list;
}
  • 双列集合
@GetMapping("resp04")
@ResponseBody
public Map<String,Object> resp04(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<Student> list = new ArrayList<Student>();
    list.add(new Student("1","mary",18));
    list.add(new Student("2","tom",18));
    list.add(new Student("3","jack",18));
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("students",list);
    return map;
}

二、转发和重定向

1、forword 请求转发
@GetMapping("resp02")
public String resp02() throws IOException {
     System.out.println("进来了");
     return "forward:../main.jsp";
}
2、redirect重定向
@GetMapping("resp02")
public String resp02() throws IOException {
    System.out.println("进来了");
    return "redirect:../main.jsp";
}

Postman工具

一、Postman工具介绍

​ 开发者 在开发或者调试网路或者是 B/S 模式的程序时,需要一些方法来跟踪网页请求的,用户可以使用一些网络的监视工具比如著名的Firebug等网页调试工具。

​ Postman可以调试 简单的css、html、脚本等简单的网页基本信息。它还可发送几乎所有的 HTTP请求。Postman 在发送网络 HTTP 请求方面可以说是 Chrome插件类产品中的代表产品之一。

二、Postman工具的下载安装

  1. 下载地址:https://www.postman.com/downloads/
  2. 安装步骤:next 下一步傻瓜式安装。

三、Postman工具的使用

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咸鱼不咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值